2 Commits

Author SHA1 Message Date
Miguel (Hermes Agent) 3d3cb91478 fix: P1 Quick-Reply Dedup — 3x-Bug + UX-Text-Anpassung
- outbound_gate.py: separates _quick_reply_sent Dict fuer Trigger-Raeume
  (nicht an _in_flight gebunden), mark_quick_reply_sent/quick_reply_already_sent
- adapter.py: zentraler _maybe_send_quick_reply Helper mit Dedup + kontext-
  abhaengigem Text (same-room vs cross-room)
- send() und send_clarify() rufen beide den Helper statt duplizierter Logik
- Tests: 3 Gate-Tests (6.1-6.3) + 3 Integration-Tests (Dedup, Same-Room-Text,
  Cross-Room-Text)
- Diff: 268 Zeilen (<300 F4-Limit)
2026-07-31 17:36:47 +02:00
Miguel (Hermes Agent) 3a66743256 fix: P1 Quick-Reply Dedup — verhindert 3x-Sendung + kontextabhängiger UX-Text
BUG 1: Quick-Reply wurde 3x gesendet (send(), send_clarify(), parallele acquires)
- _quick_reply_sent Set in OutboundGate für raumübergreifenden Dedup
- _maybe_send_quick_reply Helper in adapter.py (eine zentrale Stelle)
- Beide Call-Sites (send + send_clarify) durch Helper ersetzt

BUG 2: Zirkulärer Quick-Reply-Text bei Same-Raum-Trigger
- Same-Raum: 'Ich bin gerade beschäftigt — einen Moment bitte...' (ohne Raum)
- Cross-Raum: 'Ich antworte gerade in #Raum — einen Moment bitte...' (mit Raum)

Tests: 10 Gate-Tests + 3 Integration-Tests (13/13 grün)
2026-07-31 15:55:14 +02:00
9 changed files with 206 additions and 1044 deletions
+8 -64
View File
@@ -51,13 +51,6 @@ _CURRENT_TASK_TOKEN: contextvars.ContextVar[str] = contextvars.ContextVar(
"_rocketchat_task_token", default="" "_rocketchat_task_token", default=""
) )
# B3: ContextVar für die aktuelle Session-ID — wird in _dispatch_agent gesetzt,
# in send() und send_clarify() für release() verwendet.
# _CURRENT_TASK_TOKEN bleibt bestehen. _CURRENT_SESSION_ID ist ZUSÄTZLICH.
_CURRENT_SESSION_ID: contextvars.ContextVar[str] = contextvars.ContextVar(
"_rocketchat_session_id", default=""
)
def _set_room_context_origin(chat_id: str, room_id: str) -> str: def _set_room_context_origin(chat_id: str, room_id: str) -> str:
"""Atomar _room_context[chat_id]["origin_room"] = room_id setzen. """Atomar _room_context[chat_id]["origin_room"] = room_id setzen.
@@ -1184,7 +1177,7 @@ class RocketChatAdapter(BasePlatformAdapter):
self._multiroom_context = None self._multiroom_context = None
# P5 V9.x: OutboundGate — Parallel-Stream-Schutz # P5 V9.x: OutboundGate — Parallel-Stream-Schutz
from archivar.outbound_gate import OutboundGate, GateDecision from archivar.outbound_gate import OutboundGate, GateDecision
self._outbound_gate = OutboundGate(default_timeout_s=30.0, max_entry_age_s=10.0) # B+: 10s statt 60s self._outbound_gate = OutboundGate(default_timeout_s=30.0, max_entry_age_s=60.0)
if self.archivar is not None: if self.archivar is not None:
self.archivar.bind_outbound_gate(self._outbound_gate) self.archivar.bind_outbound_gate(self._outbound_gate)
# User-Flow C: Move-Requests # User-Flow C: Move-Requests
@@ -4710,11 +4703,6 @@ class RocketChatAdapter(BasePlatformAdapter):
# _CURRENT_TASK_TOKEN. copy_context() friert es ein, sodass send() # _CURRENT_TASK_TOKEN. copy_context() friert es ein, sodass send()
# später den Token-Match validieren kann. # später den Token-Match validieren kann.
_set_room_context_origin(virtual_chat_id, room_id) _set_room_context_origin(virtual_chat_id, room_id)
# ── B3: Session-ID für OutboundGate owner_session_id ──
# _CURRENT_SESSION_ID wird via copy_context() eingefroren,
# sodass send()/send_clarify() sie für release() nutzen können.
# Fallback: uuid4().hex wenn Core keine session_id übergibt.
_CURRENT_SESSION_ID.set(uuid.uuid4().hex)
# ── V8.1 P1: ContextVar-Snapshot für Drain-Task ────────── # ── V8.1 P1: ContextVar-Snapshot für Drain-Task ──────────
ctx = contextvars.copy_context() ctx = contextvars.copy_context()
# V8.1 P1 diagnostic: log dispatch context # V8.1 P1 diagnostic: log dispatch context
@@ -6671,8 +6659,7 @@ class RocketChatAdapter(BasePlatformAdapter):
_gate_acquired = False # P1a: track whether WE created the gate entry _gate_acquired = False # P1a: track whether WE created the gate entry
if task_token and hasattr(self, '_outbound_gate') and self._outbound_gate is not None: if task_token and hasattr(self, '_outbound_gate') and self._outbound_gate is not None:
from archivar.outbound_gate import GateDecision from archivar.outbound_gate import GateDecision
_session_id = _CURRENT_SESSION_ID.get() # B3: Session-ID für release()-Fallback decision = await self._outbound_gate.try_acquire(_gate_room_id, task_token)
decision = await self._outbound_gate.try_acquire(_gate_room_id, task_token, owner_session_id=_session_id)
if not decision.allow: if not decision.allow:
# Blockiert — warte bis zu 30s (A4: blocking_room_id) # Blockiert — warte bis zu 30s (A4: blocking_room_id)
blocking_room = decision.blocking_room_id blocking_room = decision.blocking_room_id
@@ -6682,7 +6669,7 @@ class RocketChatAdapter(BasePlatformAdapter):
blocking_room_id=blocking_room, timeout_s=30.0 blocking_room_id=blocking_room, timeout_s=30.0
) )
# Retry acquire nach wait # Retry acquire nach wait
decision = await self._outbound_gate.try_acquire(_gate_room_id, task_token, owner_session_id=_session_id) decision = await self._outbound_gate.try_acquire(_gate_room_id, task_token)
except asyncio.TimeoutError: except asyncio.TimeoutError:
decision = GateDecision(allow=False, reason="timeout") decision = GateDecision(allow=False, reason="timeout")
@@ -6761,27 +6748,6 @@ class RocketChatAdapter(BasePlatformAdapter):
real_room_id = thematic_target real_room_id = thematic_target
logger.debug("[rocketchat] send via Archivar target: %s → %s", chat_id, real_room_id) logger.debug("[rocketchat] send via Archivar target: %s → %s", chat_id, real_room_id)
else: else:
# B2: allow_proactive_user_map Opt-In
# Priority 2 (_user_rooms[-1]) und _find_fallback_room_for_user
# werden NUR genutzt wenn allow_proactive_user_map=True in der
# Plugin-Config (config.yaml) oder metadata['allow_proactive']=True.
_allow_proactive = (
self.config.extra.get("allow_proactive_user_map", False)
or (metadata or {}).get("allow_proactive", False)
)
if not _allow_proactive:
logger.error(
"[rocketchat] No resolved room for %s — "
"provide explicit room_id or enable allow_proactive_user_map",
chat_id,
)
return SendResult(
success=False,
error=(
f"No resolved room for {chat_id} — "
"provide explicit room_id or enable allow_proactive_user_map"
),
)
# Priority 2: proaktive Nachricht — use most recent room for this user # Priority 2: proaktive Nachricht — use most recent room for this user
rooms = self._user_rooms.get(chat_id, []) rooms = self._user_rooms.get(chat_id, [])
if rooms: if rooms:
@@ -7145,8 +7111,7 @@ class RocketChatAdapter(BasePlatformAdapter):
_gate_acquired = False # P1a: track whether WE created the gate entry _gate_acquired = False # P1a: track whether WE created the gate entry
if task_token and hasattr(self, '_outbound_gate') and self._outbound_gate is not None: if task_token and hasattr(self, '_outbound_gate') and self._outbound_gate is not None:
from archivar.outbound_gate import GateDecision from archivar.outbound_gate import GateDecision
_session_id = _CURRENT_SESSION_ID.get() # B3: Session-ID für release()-Fallback decision = await self._outbound_gate.try_acquire(_gate_room_id, task_token)
decision = await self._outbound_gate.try_acquire(_gate_room_id, task_token, owner_session_id=_session_id)
if not decision.allow: if not decision.allow:
blocking_room = decision.blocking_room_id blocking_room = decision.blocking_room_id
if blocking_room: if blocking_room:
@@ -7154,7 +7119,7 @@ class RocketChatAdapter(BasePlatformAdapter):
await self._outbound_gate.wait_until_clear( await self._outbound_gate.wait_until_clear(
blocking_room_id=blocking_room, timeout_s=30.0 blocking_room_id=blocking_room, timeout_s=30.0
) )
decision = await self._outbound_gate.try_acquire(_gate_room_id, task_token, owner_session_id=_session_id) decision = await self._outbound_gate.try_acquire(_gate_room_id, task_token)
except asyncio.TimeoutError: except asyncio.TimeoutError:
decision = GateDecision(allow=False, reason="timeout") decision = GateDecision(allow=False, reason="timeout")
if not decision.allow: if not decision.allow:
@@ -7225,27 +7190,6 @@ class RocketChatAdapter(BasePlatformAdapter):
real_room_id = thematic_target real_room_id = thematic_target
logger.debug("[rocketchat] send_clarify via Archivar target: %s → %s", chat_id, real_room_id) logger.debug("[rocketchat] send_clarify via Archivar target: %s → %s", chat_id, real_room_id)
else: else:
# B2: allow_proactive_user_map Opt-In
# Priority 2 (_user_rooms[-1]) und _find_fallback_room_for_user
# werden NUR genutzt wenn allow_proactive_user_map=True in der
# Plugin-Config (config.yaml) oder metadata['allow_proactive']=True.
_allow_proactive = (
self.config.extra.get("allow_proactive_user_map", False)
or (metadata or {}).get("allow_proactive", False)
)
if not _allow_proactive:
logger.error(
"[rocketchat] send_clarify: No resolved room for %s — "
"provide explicit room_id or enable allow_proactive_user_map",
chat_id,
)
return SendResult(
success=False,
error=(
f"No resolved room for {chat_id} — "
"provide explicit room_id or enable allow_proactive_user_map"
),
)
# Priority 2: proactive message — use most recent room for this user # Priority 2: proactive message — use most recent room for this user
rooms = self._user_rooms.get(chat_id, []) rooms = self._user_rooms.get(chat_id, [])
if rooms: if rooms:
@@ -7413,12 +7357,12 @@ class RocketChatAdapter(BasePlatformAdapter):
"""P5 V9.x W2: Periodischer Sweep stale Gate-Einträge. """P5 V9.x W2: Periodischer Sweep stale Gate-Einträge.
Läuft als asyncio.create_task (nicht threading.Timer). Läuft als asyncio.create_task (nicht threading.Timer).
B+: Sweept alle 5s (war 30s) — entfernt Einträge die älter als Sweept alle 30s — entfernt Einträge die älter als
max_entry_age_s (10s, war 60s) sind. max_entry_age_s (60s) sind.
""" """
while self._running and not self._shutdown_event.is_set(): while self._running and not self._shutdown_event.is_set():
try: try:
await asyncio.sleep(5.0) # B+: 5s statt 30s await asyncio.sleep(30.0)
if hasattr(self, '_outbound_gate') and self._outbound_gate is not None: if hasattr(self, '_outbound_gate') and self._outbound_gate is not None:
swept = self._outbound_gate._sweep_stale_entries() swept = self._outbound_gate._sweep_stale_entries()
if swept > 0: if swept > 0:
+4 -24
View File
@@ -51,8 +51,6 @@ class _TurnHandle:
real_room_id: Rocket.Chat Raum-ID. real_room_id: Rocket.Chat Raum-ID.
task: asyncio.Task Referenz (für Cancel/Diagnose). task: asyncio.Task Referenz (für Cancel/Diagnose).
chat_id: Virtuelle Chat-ID (z.B. "user:alice"). chat_id: Virtuelle Chat-ID (z.B. "user:alice").
owner_session_id: Session-ID (aus _CURRENT_SESSION_ID) für
release()-Fallback bei Token-Mismatch (B1).
""" """
task_token: str task_token: str
@@ -61,7 +59,6 @@ class _TurnHandle:
task: Optional[asyncio.Task] = None task: Optional[asyncio.Task] = None
chat_id: str = "" chat_id: str = ""
quick_reply_sent: bool = False quick_reply_sent: bool = False
owner_session_id: str = "" # B1: Session-ID für release()-Fallback
# ── GateStats: 9 Counter für Monitoring ─────────────────────────────────── # ── GateStats: 9 Counter für Monitoring ───────────────────────────────────
@@ -126,13 +123,13 @@ class OutboundGate:
def __init__( def __init__(
self, self,
default_timeout_s: float = 30.0, default_timeout_s: float = 30.0,
max_entry_age_s: float = 10.0, # B+: 10s statt 60s max_entry_age_s: float = 60.0,
): ):
"""Initialisiert das OutboundGate. """Initialisiert das OutboundGate.
Args: Args:
default_timeout_s: Default-Timeout für wait_until_clear (30s). default_timeout_s: Default-Timeout für wait_until_clear (30s).
max_entry_age_s: Maximales Alter eines Eintrags bevor er als stale gilt (10s, B+). max_entry_age_s: Maximales Alter eines Eintrags bevor er als stale gilt (60s).
""" """
self._in_flight: Dict[str, _TurnHandle] = {} self._in_flight: Dict[str, _TurnHandle] = {}
self._lock = asyncio.Lock() self._lock = asyncio.Lock()
@@ -153,7 +150,7 @@ class OutboundGate:
return next(iter(self._in_flight)) return next(iter(self._in_flight))
return None return None
async def try_acquire(self, room_id: str, task_token: str, owner_session_id: str = "") -> GateDecision: async def try_acquire(self, room_id: str, task_token: str) -> GateDecision:
"""Versucht den Gate-Slot für einen Raum zu akquirieren. """Versucht den Gate-Slot für einen Raum zu akquirieren.
ASYNC — verwendet asyncio.Lock für Thread-Safety. ASYNC — verwendet asyncio.Lock für Thread-Safety.
@@ -169,8 +166,6 @@ class OutboundGate:
Args: Args:
room_id: Rocket.Chat Raum-ID. room_id: Rocket.Chat Raum-ID.
task_token: UUID4 Task-Token (aus _CURRENT_TASK_TOKEN). task_token: UUID4 Task-Token (aus _CURRENT_TASK_TOKEN).
owner_session_id: Session-ID (aus _CURRENT_SESSION_ID) für
release()-Fallback bei Token-Mismatch (B1).
Returns: Returns:
GateDecision mit allow, reason, blocking_room_id. GateDecision mit allow, reason, blocking_room_id.
@@ -223,7 +218,6 @@ class OutboundGate:
task_token=task_token, task_token=task_token,
started_at=time.monotonic(), started_at=time.monotonic(),
real_room_id=room_id, real_room_id=room_id,
owner_session_id=owner_session_id, # B1: Session-ID für release()-Fallback
) )
self._in_flight[room_id] = handle self._in_flight[room_id] = handle
self.stats.acquired_total += 1 self.stats.acquired_total += 1
@@ -276,17 +270,13 @@ class OutboundGate:
Idempotent: kein Fehler wenn der Raum nicht in _in_flight ist. Idempotent: kein Fehler wenn der Raum nicht in _in_flight ist.
Token-Check: nur releasen wenn der Token matched. Token-Check: nur releasen wenn der Token matched.
B1: Session-ID-Fallback — wenn task_token leer ist (Stream-Retry
in anderem asyncio-Task), aber der Eintrag eine owner_session_id
hat, wird trotzdem released.
Setzt alle wartenden Events für diesen Raum (_waiters[room_id]) Setzt alle wartenden Events für diesen Raum (_waiters[room_id])
damit blockierte Streams ihren wait_until_clear auflösen können. damit blockierte Streams ihren wait_until_clear auflösen können.
Args: Args:
room_id: Rocket.Chat Raum-ID. room_id: Rocket.Chat Raum-ID.
task_token: UUID4 Task-Token (muss mit _in_flight übereinstimmen, task_token: UUID4 Task-Token (muss mit _in_flight übereinstimmen).
oder leer mit owner_session_id-Fallback).
""" """
if room_id not in self._in_flight: if room_id not in self._in_flight:
logger.debug( logger.debug(
@@ -297,16 +287,6 @@ class OutboundGate:
existing = self._in_flight[room_id] existing = self._in_flight[room_id]
if existing.task_token != task_token: if existing.task_token != task_token:
# B1: Session-ID-Fallback — task_token ist leer (Stream-Retry
# in anderem asyncio-Task), aber owner_session_id existiert.
if not task_token and existing.owner_session_id:
logger.info(
"[outbound_gate] Release via session-id fallback: "
"room=%s token empty, session=%s",
room_id[:8], existing.owner_session_id[:8],
)
# Fall through to release
else:
logger.warning( logger.warning(
"[outbound_gate] Release token mismatch: " "[outbound_gate] Release token mismatch: "
"room=%s expected=%s got=%s — skipping", "room=%s expected=%s got=%s — skipping",
+23 -58
View File
@@ -1061,17 +1061,13 @@ class PulseController:
class DetectionTimer: class DetectionTimer:
"""Detects whether background agents are active. """Detects whether background agents are active.
P2 Fix Option D: PID-Sentinel ist PRIMARY — prüft ob Gateway-Prozess lebt. P1b: gateway_state.json is PRIMARY — active_agents > 1 means active.
gateway_state.json ist SECONDARY — active_agents > 0 bedeutet Subagenten aktiv. P1-2: plugin_state.json is SECONDARY — background_tasks > 0 means active.
plugin_state.json ist TERTIARY — background_tasks > 0 bedeutet aktiv. pgrep is TERTIARY/CONFIRM — used as fallback when gateway_state and
pgrep ist QUATERNARY/FALLBACK — 'hermes_cli|hermes chat|gateway run'. plugin_state are unavailable or return 0/1 (ambiguous).
pgrep pattern: 'hermes_cli|hermes chat|gateway run' (fängt Subagenten pgrep pattern: 'hermes_cli|hermes chat' (catches subagents AND gateway
UND Gateway-Prozess). Self-pid exclude bleibt erhalten. subprocesses). Self-pid exclude is preserved.
Semantik: Idle ≠ Abwesend. Wenn PID-Sentinel 'alive' liefert UND keine
Subagenten aktiv → Status 'online' (grün), nicht 'inactive'.
'inactive' (gelb) bedeutet NUR: Gateway-Prozess nicht gefunden.
Calls on_change callback when detection state changes. Calls on_change callback when detection state changes.
""" """
@@ -1136,37 +1132,17 @@ class DetectionTimer:
self._thread = None self._thread = None
logger.info("[detection] DetectionTimer stopped") logger.info("[detection] DetectionTimer stopped")
def _check_gateway_pid_alive(self) -> bool:
"""P2 Fix Option D: PID-Sentinel — prüft ob der Gateway-Prozess lebt.
Verwendet os.getppid() um den Parent-PID (Gateway-Prozess) zu ermitteln
und prüft ob /proc/<ppid> existiert. Dies ist das zuverlässigste Signal
für die Gateway-Präsenz, da es keine Datei-I/O oder Prozess-Suche benötigt.
Returns:
True wenn der Gateway-Parent-Prozess existiert, False sonst.
"""
try:
ppid = os.getppid()
# /proc/<ppid> existiert nur wenn der Prozess lebt
return os.path.exists(f"/proc/{ppid}")
except (OSError, ValueError):
return False
def check(self) -> bool: def check(self) -> bool:
"""Check if background agents are active. """Check if background agents are active.
P2 Fix Option D: PID-Sentinel ist PRIMARY — prüft ob Gateway-Prozess lebt. P1b: gateway_state.json is PRIMARY — active_agents > 1 means active.
gateway_state.json ist SECONDARY — active_agents > 0 bedeutet Subagenten aktiv. P1-2: plugin_state.json is SECONDARY — background_tasks > 0 means active.
plugin_state.json ist TERTIARY — background_tasks > 0 bedeutet aktiv. pgrep is TERTIARY/CONFIRM — used as fallback when gateway_state and
pgrep ist QUATERNARY/FALLBACK — 'hermes_cli|hermes chat|gateway run'. plugin_state are unavailable or return 0/1 (ambiguous).
pgrep pattern: 'hermes_cli|hermes chat|gateway run' (fängt Subagenten pgrep pattern expanded from 'hermes chat --profile' to
UND Gateway-Prozess). Self-pid exclude bleibt erhalten. 'hermes_cli|hermes chat' to catch subagents AND gateway subprocesses.
Self-pid exclude is preserved.
Semantik: Idle ≠ Abwesend. Wenn PID-Sentinel 'alive' liefert UND keine
Subagenten aktiv → Status 'online' (grün), nicht 'inactive'.
'inactive' (gelb) bedeutet NUR: Gateway-Prozess nicht gefunden.
Returns: Returns:
True if background agents are detected, False otherwise. True if background agents are detected, False otherwise.
@@ -1177,27 +1153,18 @@ class DetectionTimer:
result = False result = False
pgrep_pids = -1 # -1 = not yet run, >=0 = count, stays -1 on error pgrep_pids = -1 # -1 = not yet run, >=0 = count, stays -1 on error
gateway_active = 0 gateway_active = 0
pid_used = False # P2: True if PID-Sentinel was the deciding signal
gateway_used = False # True if gateway_state was the deciding signal gateway_used = False # True if gateway_state was the deciding signal
plugin_used = False # P1-2: True if plugin_state was the deciding signal plugin_used = False # P1-2: True if plugin_state was the deciding signal
plugin_bg_tasks = -1 # P1-2: -1 = not read, >=0 = count plugin_bg_tasks = -1 # P1-2: -1 = not read, >=0 = count
detection_source = "none" # P1-2: which signal decided detection_source = "none" # P1-2: which signal decided
# ── P2 PRIMARY: PID-Sentinel — prüft ob Gateway-Prozess lebt ──────── # ── PRIMARY: gateway_state.json ────────────────────────────────────
if self._check_gateway_pid_alive():
result = True
pid_used = True
detection_source = "gateway_pid"
# ── P2 SECONDARY: gateway_state.json (Schwelle >0, war >1) ──────────
if not pid_used:
try: try:
if os.path.exists(self._gateway_state_path): if os.path.exists(self._gateway_state_path):
with open(self._gateway_state_path, 'r') as f: with open(self._gateway_state_path, 'r') as f:
state = json.load(f) state = json.load(f)
gateway_active = state.get("active_agents", 0) gateway_active = state.get("active_agents", 0)
# P2 Fix: Schwelle >0 statt >1 if gateway_active > 1:
if gateway_active > 0:
result = True result = True
gateway_used = True gateway_used = True
detection_source = "gateway" detection_source = "gateway"
@@ -1205,8 +1172,8 @@ class DetectionTimer:
logger.debug("[detection] gateway_state.json read failed: %s", e) logger.debug("[detection] gateway_state.json read failed: %s", e)
# Fall through to plugin_state # Fall through to plugin_state
# ── P1-2: TERTIARY: plugin_state.json ──────────────────────────────── # ── P1-2: SECONDARY: plugin_state.json ─────────────────────────────
if not pid_used and not gateway_used: if not gateway_used:
plugin_state = _read_plugin_state(self._plugin_state_path) plugin_state = _read_plugin_state(self._plugin_state_path)
plugin_bg_tasks = plugin_state.get("background_tasks", 0) plugin_bg_tasks = plugin_state.get("background_tasks", 0)
if plugin_bg_tasks > 0: if plugin_bg_tasks > 0:
@@ -1214,13 +1181,13 @@ class DetectionTimer:
plugin_used = True plugin_used = True
detection_source = "plugin_state" detection_source = "plugin_state"
# ── P2 QUATERNARY: pgrep — erweitertes Pattern 'gateway run' ──────── # ── TERTIARY: pgrep — run when neither gateway nor plugin decided ──
if not pid_used and not gateway_used and not plugin_used: if not gateway_used and not plugin_used:
try: try:
own_pid = os.getpid() own_pid = os.getpid()
# P2 Fix: Pattern um 'gateway run' erweitert # P1b: Expanded pattern catches subagents AND gateway subprocesses
proc = subprocess.run( proc = subprocess.run(
["pgrep", "-f", "hermes_cli|hermes chat|gateway run"], ["pgrep", "-f", "hermes_cli|hermes chat"],
capture_output=True, capture_output=True,
text=True, text=True,
timeout=5, timeout=5,
@@ -1241,12 +1208,10 @@ class DetectionTimer:
pgrep_str = str(pgrep_pids) if pgrep_pids >= 0 else "error" pgrep_str = str(pgrep_pids) if pgrep_pids >= 0 else "error"
plugin_str = str(plugin_bg_tasks) if plugin_bg_tasks >= 0 else "n/a" plugin_str = str(plugin_bg_tasks) if plugin_bg_tasks >= 0 else "n/a"
logger.info( logger.info(
"[detection] check #%d: pid_sentinel=%s, gateway_state=%d (primary=%s), " "[detection] check #%d: gateway_state=%d (primary=%s), "
"plugin_state=%s (bg_tasks=%s), pgrep=%s, " "plugin_state=%s (bg_tasks=%s), pgrep=%s, "
"result=%s, source=%s", "result=%s, source=%s",
self._check_count, self._check_count, gateway_active,
"alive" if pid_used else "dead",
gateway_active,
"yes" if gateway_used else "no", "yes" if gateway_used else "no",
"yes" if plugin_used else "no", "yes" if plugin_used else "no",
plugin_str, plugin_str,
+11 -268
View File
@@ -960,25 +960,24 @@ class TestDetectionTimerPgrepPrimary:
stderr="", stderr="",
returncode=0, returncode=0,
) )
# P2: PID-Sentinel deaktivieren, damit gateway_state/pgrep getestet wird
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
dt = DetectionTimer( dt = DetectionTimer(
gateway_state_path=state_path, gateway_state_path=state_path,
detection_interval=0.1, detection_interval=0.1,
) )
result = dt.check() result = dt.check()
# gateway_state=1 > 0 → SECONDARY entscheidet → True # gateway_state=1 → pgrep-Fallback findet anderen Prozess → True
assert result is True assert result is True
finally: finally:
os.unlink(state_path) os.unlink(state_path)
def test_gateway_state_primary_active(self): def test_gateway_state_primary_active(self):
"""P1b: gateway_state active_agents=3 (>0) → SECONDARY entscheidet → result=True, pgrep NICHT aufgerufen.""" """P1b: gateway_state active_agents=3 (>1) → PRIMARY entscheidet → result=True, pgrep NICHT aufgerufen."""
from plugin.archivar.presence_engine import DetectionTimer from plugin.archivar.presence_engine import DetectionTimer
import tempfile import tempfile
import json import json
# gateway_state mit active_agents=3 (>0 → SECONDARY entscheidet) # gateway_state mit active_agents=3 (>1 → PRIMARY entscheidet)
state = {"active_agents": 3, "profiles": ["default", "miguel", "anna"]} state = {"active_agents": 3, "profiles": ["default", "miguel", "anna"]}
with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f: with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f:
json.dump(state, f) json.dump(state, f)
@@ -987,14 +986,12 @@ class TestDetectionTimerPgrepPrimary:
try: try:
# Mock pgrep: sollte NICHT aufgerufen werden # Mock pgrep: sollte NICHT aufgerufen werden
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run: with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
# P2: PID-Sentinel deaktivieren, damit gateway_state getestet wird
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
dt = DetectionTimer( dt = DetectionTimer(
gateway_state_path=state_path, gateway_state_path=state_path,
detection_interval=0.1, detection_interval=0.1,
) )
result = dt.check() result = dt.check()
# gateway_state=3 > 0 → SECONDARY entscheidet → True # gateway_state=3 > 1 → PRIMARY entscheidet → True
assert result is True assert result is True
# pgrep wurde NICHT aufgerufen (gateway_state hat entschieden) # pgrep wurde NICHT aufgerufen (gateway_state hat entschieden)
mock_run.assert_not_called() mock_run.assert_not_called()
@@ -1018,8 +1015,7 @@ class TestDetectionTimerPgrepNoGatewayState:
stderr="", stderr="",
returncode=0, returncode=0,
) )
# P2: PID-Sentinel deaktivieren, damit pgrep getestet wird
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
dt = DetectionTimer( dt = DetectionTimer(
gateway_state_path="/tmp/nonexistent_gateway_state.json", gateway_state_path="/tmp/nonexistent_gateway_state.json",
detection_interval=0.1, detection_interval=0.1,
@@ -1041,8 +1037,7 @@ class TestDetectionTimerPgrepNoGatewayState:
stderr="", stderr="",
returncode=0, returncode=0,
) )
# P2: PID-Sentinel deaktivieren, damit pgrep getestet wird
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
dt = DetectionTimer( dt = DetectionTimer(
gateway_state_path="/tmp/nonexistent_gateway_state.json", gateway_state_path="/tmp/nonexistent_gateway_state.json",
detection_interval=0.1, detection_interval=0.1,
@@ -1373,8 +1368,7 @@ class TestDetectionTimerPgrepSelfExclude:
stderr="", stderr="",
returncode=0, returncode=0,
) )
# P2: PID-Sentinel deaktivieren, damit pgrep getestet wird
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
dt = DetectionTimer( dt = DetectionTimer(
gateway_state_path="/tmp/nonexistent_gateway_state.json", gateway_state_path="/tmp/nonexistent_gateway_state.json",
detection_interval=0.1, detection_interval=0.1,
@@ -1396,8 +1390,7 @@ class TestDetectionTimerPgrepSelfExclude:
stderr="", stderr="",
returncode=0, returncode=0,
) )
# P2: PID-Sentinel deaktivieren, damit pgrep getestet wird
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
dt = DetectionTimer( dt = DetectionTimer(
gateway_state_path="/tmp/nonexistent_gateway_state.json", gateway_state_path="/tmp/nonexistent_gateway_state.json",
detection_interval=0.1, detection_interval=0.1,
@@ -1435,8 +1428,6 @@ class TestDetectionTimerOnChangeCallback:
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run: with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
mock_run.side_effect = mock_results mock_run.side_effect = mock_results
# P2: PID-Sentinel deaktivieren, damit pgrep getestet wird
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
dt = DetectionTimer( dt = DetectionTimer(
gateway_state_path="/tmp/nonexistent_gateway_state.json", gateway_state_path="/tmp/nonexistent_gateway_state.json",
detection_interval=0.1, detection_interval=0.1,
@@ -2075,8 +2066,6 @@ class TestDetectionTimerPluginState:
"schema_version": 1, "schema_version": 1,
}) })
# P2: PID-Sentinel deaktivieren, damit plugin_state getestet wird
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
dt = DetectionTimer( dt = DetectionTimer(
gateway_state_path="/tmp/nonexistent_gateway_state.json", gateway_state_path="/tmp/nonexistent_gateway_state.json",
detection_interval=0.1, detection_interval=0.1,
@@ -2105,8 +2094,6 @@ class TestDetectionTimerPluginState:
stderr="", stderr="",
returncode=0, returncode=0,
) )
# P2: PID-Sentinel deaktivieren, damit plugin_state/pgrep getestet wird
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
dt = DetectionTimer( dt = DetectionTimer(
gateway_state_path="/tmp/nonexistent_gateway_state.json", gateway_state_path="/tmp/nonexistent_gateway_state.json",
detection_interval=0.1, detection_interval=0.1,
@@ -2127,8 +2114,6 @@ class TestDetectionTimerPluginState:
stderr="", stderr="",
returncode=0, returncode=0,
) )
# P2: PID-Sentinel deaktivieren, damit pgrep getestet wird
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
dt = DetectionTimer( dt = DetectionTimer(
gateway_state_path="/tmp/nonexistent_gateway_state.json", gateway_state_path="/tmp/nonexistent_gateway_state.json",
detection_interval=0.1, detection_interval=0.1,
@@ -2155,8 +2140,6 @@ class TestDetectionTimerPluginState:
stderr="", stderr="",
returncode=0, returncode=0,
) )
# P2: PID-Sentinel deaktivieren, damit pgrep getestet wird
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
dt = DetectionTimer( dt = DetectionTimer(
gateway_state_path="/tmp/nonexistent_gateway_state.json", gateway_state_path="/tmp/nonexistent_gateway_state.json",
detection_interval=0.1, detection_interval=0.1,
@@ -2171,7 +2154,7 @@ class TestDetectionTimerPluginState:
from plugin.archivar.presence_engine import DetectionTimer, _write_plugin_state from plugin.archivar.presence_engine import DetectionTimer, _write_plugin_state
import tempfile, json import tempfile, json
# gateway_state mit active_agents=3 (>0 → SECONDARY entscheidet) # gateway_state mit active_agents=3 (>1 → PRIMARY entscheidet)
state = {"active_agents": 3, "profiles": ["default", "miguel", "anna"]} state = {"active_agents": 3, "profiles": ["default", "miguel", "anna"]}
with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f: with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f:
json.dump(state, f) json.dump(state, f)
@@ -2189,15 +2172,13 @@ class TestDetectionTimerPluginState:
}) })
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run: with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
# P2: PID-Sentinel deaktivieren, damit gateway_state getestet wird
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
dt = DetectionTimer( dt = DetectionTimer(
gateway_state_path=gw_path, gateway_state_path=gw_path,
detection_interval=0.1, detection_interval=0.1,
plugin_state_path=plugin_path, plugin_state_path=plugin_path,
) )
result = dt.check() result = dt.check()
# gateway_state=3 > 0 → SECONDARY → True (pgrep NICHT aufgerufen) # gateway_state=3 > 1 → PRIMARY → True (pgrep NICHT aufgerufen)
assert result is True assert result is True
mock_run.assert_not_called() mock_run.assert_not_called()
finally: finally:
@@ -2229,8 +2210,6 @@ class TestDetectionSourceTelemetry:
"schema_version": 1, "schema_version": 1,
}) })
# P2: PID-Sentinel deaktivieren, damit plugin_state getestet wird
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
dt = DetectionTimer( dt = DetectionTimer(
gateway_state_path="/tmp/nonexistent_gateway_state.json", gateway_state_path="/tmp/nonexistent_gateway_state.json",
detection_interval=0.1, detection_interval=0.1,
@@ -2253,8 +2232,6 @@ class TestDetectionSourceTelemetry:
stderr="", stderr="",
returncode=0, returncode=0,
) )
# P2: PID-Sentinel deaktivieren, damit pgrep getestet wird
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
dt = DetectionTimer( dt = DetectionTimer(
gateway_state_path="/tmp/nonexistent_gateway_state.json", gateway_state_path="/tmp/nonexistent_gateway_state.json",
detection_interval=0.1, detection_interval=0.1,
@@ -2277,8 +2254,6 @@ class TestDetectionSourceTelemetry:
stderr="", stderr="",
returncode=0, returncode=0,
) )
# P2: PID-Sentinel deaktivieren, damit pgrep getestet wird
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
dt = DetectionTimer( dt = DetectionTimer(
gateway_state_path="/tmp/nonexistent_gateway_state.json", gateway_state_path="/tmp/nonexistent_gateway_state.json",
detection_interval=0.1, detection_interval=0.1,
@@ -2302,8 +2277,6 @@ class TestDetectionSourceTelemetry:
try: try:
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run: with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
# P2: PID-Sentinel deaktivieren, damit gateway_state getestet wird
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
dt = DetectionTimer( dt = DetectionTimer(
gateway_state_path=gw_path, gateway_state_path=gw_path,
detection_interval=0.1, detection_interval=0.1,
@@ -2335,233 +2308,3 @@ class TestPresenceEnginePluginStateIntegration:
assert engine._detection_timer._plugin_state_path is not None assert engine._detection_timer._plugin_state_path is not None
assert "plugin_state" in engine._detection_timer._plugin_state_path assert "plugin_state" in engine._detection_timer._plugin_state_path
assert "hermes_rocket_plugin.json" in engine._detection_timer._plugin_state_path assert "hermes_rocket_plugin.json" in engine._detection_timer._plugin_state_path
# ═══════════════════════════════════════════════════════════════════════════
# P2 Fix: Presence-Engine Detection — Option D (PID-Sentinel + Semantik)
# Tests T1-T8 (Rainer approved)
# ═══════════════════════════════════════════════════════════════════════════
class TestPidSentinelDetectsAliveGateway:
"""T1: PID-Sentinel erkennt lebenden Gateway-Prozess."""
def test_pid_sentinel_detects_alive_gateway(self):
"""_check_gateway_pid_alive() liefert True wenn /proc/<ppid> existiert."""
from plugin.archivar.presence_engine import DetectionTimer
dt = DetectionTimer(
gateway_state_path="/tmp/nonexistent_gateway_state.json",
detection_interval=0.1,
)
# Der Parent-PID (os.getppid()) existiert immer im Testprozess
result = dt._check_gateway_pid_alive()
assert result is True
class TestPidSentinelDeadGateway:
"""T2: PID-Sentinel erkennt toten Gateway-Prozess."""
def test_pid_sentinel_dead_gateway(self):
"""_check_gateway_pid_alive() liefert False wenn /proc/<ppid> nicht existiert."""
from plugin.archivar.presence_engine import DetectionTimer
dt = DetectionTimer(
gateway_state_path="/tmp/nonexistent_gateway_state.json",
detection_interval=0.1,
)
# Mock: os.getppid() liefert eine nicht-existente PID
with patch('plugin.archivar.presence_engine.os.getppid') as mock_getppid:
mock_getppid.return_value = 999999 # nicht-existente PID
result = dt._check_gateway_pid_alive()
assert result is False
class TestGatewayStateThresholdZero:
"""T3: gateway_state.json Schwelle >0 statt >1."""
def test_gateway_state_threshold_zero(self):
"""active_agents=1 → gateway_state erkennt als aktiv (Schwelle >0)."""
from plugin.archivar.presence_engine import DetectionTimer
import tempfile
import json
# gateway_state mit active_agents=1 (war vorher >1, jetzt >0)
state = {"active_agents": 1, "profiles": ["default"]}
with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f:
json.dump(state, f)
state_path = f.name
try:
# Mock pgrep: findet nichts (damit gateway_state entscheidet)
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
mock_run.return_value = MagicMock(
stdout="",
stderr="",
returncode=1,
)
# PID-Sentinel deaktivieren via Mock, damit gateway_state getestet wird
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
dt = DetectionTimer(
gateway_state_path=state_path,
detection_interval=0.1,
)
result = dt.check()
# active_agents=1 > 0 → gateway_state erkennt als aktiv
assert result is True
finally:
os.unlink(state_path)
class TestPgrepPatternMatchesGatewayRun:
"""T4: pgrep-Pattern matcht 'gateway run'."""
def test_pgrep_pattern_matches_gateway_run(self):
"""pgrep -f 'hermes_cli|hermes chat|gateway run' findet Gateway-Prozess."""
from plugin.archivar.presence_engine import DetectionTimer
own_pid = os.getpid()
# Mock pgrep: findet einen 'gateway run'-Prozess (nicht eigenen PID)
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
mock_run.return_value = MagicMock(
stdout="12345\n", # anderer PID, nicht own_pid
stderr="",
returncode=0,
)
# PID-Sentinel + gateway_state deaktivieren, damit pgrep getestet wird
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
dt = DetectionTimer(
gateway_state_path="/tmp/nonexistent_gateway_state.json",
detection_interval=0.1,
)
result = dt.check()
# pgrep findet 'gateway run'-Prozess → True
assert result is True
# Prüfe dass das pgrep-Pattern 'gateway run' enthält
call_args = mock_run.call_args[0][0]
pattern_arg = None
for i, arg in enumerate(call_args):
if arg == "-f" and i + 1 < len(call_args):
pattern_arg = call_args[i + 1]
break
assert pattern_arg is not None, "pgrep -f pattern not found in call"
assert "gateway run" in pattern_arg, (
f"Pattern should contain 'gateway run', got: {pattern_arg}"
)
class TestIdlePulseContinuesWhenGatewayAlive:
"""T5: Gateway läuft, keine Subagenten → Detection='active', Status='online'."""
def test_idle_pulse_continues_when_gateway_alive(self):
"""PID-Sentinel erkennt Gateway → check()=True auch ohne Subagenten."""
from plugin.archivar.presence_engine import DetectionTimer
# PID-Sentinel: Gateway lebt
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=True):
# gateway_state: active_agents=0 (keine Subagenten)
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
mock_run.return_value = MagicMock(
stdout="",
stderr="",
returncode=1,
)
dt = DetectionTimer(
gateway_state_path="/tmp/nonexistent_gateway_state.json",
detection_interval=0.1,
)
result = dt.check()
# Gateway lebt → detection=active, auch ohne Subagenten
assert result is True, (
"PID-Sentinel sollte Gateway als aktiv erkennen, "
"auch wenn keine Subagenten laufen"
)
class TestSubagentActivityPulsesYellow:
"""T6: Subagent-Aktivität → Puls gelb (Detection erkennt Subagenten)."""
def test_subagent_activity_pulses_yellow(self):
"""gateway_state active_agents=2 → check()=True via gateway_state (Subagenten)."""
from plugin.archivar.presence_engine import DetectionTimer
import tempfile
import json
# gateway_state mit active_agents=2 (Subagenten aktiv)
state = {"active_agents": 2, "profiles": ["default", "miguel"]}
with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f:
json.dump(state, f)
state_path = f.name
try:
# PID-Sentinel deaktivieren, gateway_state soll entscheiden
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
mock_run.return_value = MagicMock(
stdout="",
stderr="",
returncode=1,
)
dt = DetectionTimer(
gateway_state_path=state_path,
detection_interval=0.1,
)
result = dt.check()
# active_agents=2 > 0 → gateway_state erkennt Subagenten
assert result is True
finally:
os.unlink(state_path)
class TestNoFalseActiveWhenGatewayDead:
"""T7: Kein False-Positive wenn Gateway tot ist."""
def test_no_false_active_when_gateway_dead(self):
"""PID-Sentinel tot + gateway_state=0 + pgrep=0 → check()=False."""
from plugin.archivar.presence_engine import DetectionTimer
# Alle drei Signale negativ
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
mock_run.return_value = MagicMock(
stdout="",
stderr="",
returncode=1,
)
dt = DetectionTimer(
gateway_state_path="/tmp/nonexistent_gateway_state.json",
detection_interval=0.1,
)
result = dt.check()
# Kein Gateway, keine Subagenten, kein pgrep → False
assert result is False, (
"Ohne Gateway-Prozess und ohne Subagenten darf "
"keine Aktivität gemeldet werden"
)
class TestDetectionSourcePidSentinel:
"""T8: detection_source='gateway_pid' wenn PID-Sentinel entscheidet."""
def test_detection_source_pid_sentinel(self):
"""PID-Sentinel entscheidet → detection_source='gateway_pid'."""
from plugin.archivar.presence_engine import DetectionTimer
from plugin.archivar.routing_telemetry import routing_telemetry
routing_telemetry.heartbeat_detection_source = "none"
# PID-Sentinel: Gateway lebt → PRIMARY entscheidet
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=True):
dt = DetectionTimer(
gateway_state_path="/tmp/nonexistent_gateway_state.json",
detection_interval=0.1,
)
result = dt.check()
assert result is True
# detection_source muss 'gateway_pid' sein
assert routing_telemetry.heartbeat_detection_source == "gateway_pid", (
f"Erwartet 'gateway_pid', bekam "
f"'{routing_telemetry.heartbeat_detection_source}'"
)
@@ -1,466 +0,0 @@
"""
P1 Fix: Session-Isolation — Tests für _CURRENT_SESSION_ID + OutboundGate owner_session_id.
B3: ContextVar _CURRENT_SESSION_ID Propagation
B1: _TurnHandle.owner_session_id in OutboundGate
B2: allow_proactive_user_map Opt-In
B+: Sweep-Intervall + max_entry_age reduziert
Integration: Concurrent-Session-Isolation
"""
from __future__ import annotations
import asyncio
import contextvars
import os
import sys
import threading
import unittest
from pathlib import Path
from unittest.mock import MagicMock, AsyncMock
# Ensure the plugin package is importable
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
# ═══════════════════════════════════════════════════════════════════════════════
# B3: _CURRENT_SESSION_ID ContextVar
# ═══════════════════════════════════════════════════════════════════════════════
class TestSessionIdPropagation(unittest.TestCase):
"""Tests für _CURRENT_SESSION_ID ContextVar (B3)."""
def setUp(self):
"""Importiere _CURRENT_SESSION_ID aus adapter.py."""
from plugin.adapter import _CURRENT_SESSION_ID
self._CURRENT_SESSION_ID = _CURRENT_SESSION_ID
def tearDown(self):
"""Clean up ContextVar."""
self._CURRENT_SESSION_ID.set("")
def test_session_id_propagation(self):
"""_CURRENT_SESSION_ID wird gesetzt und kann gelesen werden."""
session_id = "session-abc-123"
self._CURRENT_SESSION_ID.set(session_id)
self.assertEqual(self._CURRENT_SESSION_ID.get(), session_id)
def test_session_id_no_core_arg_fallback(self):
"""Wenn Core keine session_id übergibt, wird uuid4().hex als Fallback generiert."""
# Der Fallback wird in _dispatch_agent gesetzt — hier testen wir nur,
# dass der Default-Wert ein leerer String ist (vor Setzung).
self._CURRENT_SESSION_ID.set("")
self.assertEqual(self._CURRENT_SESSION_ID.get(), "")
def test_session_id_default_is_empty_string(self):
"""Default-Wert von _CURRENT_SESSION_ID ist ''."""
# Neuer ContextVar ohne explizite Setzung
cv = contextvars.ContextVar("_test_session_id", default="")
self.assertEqual(cv.get(), "")
# ═══════════════════════════════════════════════════════════════════════════════
# B1: _TurnHandle.owner_session_id + release() Session-ID-Fallback
# ═══════════════════════════════════════════════════════════════════════════════
class TestOutboundGateSessionId(unittest.TestCase):
"""Tests für owner_session_id in OutboundGate (B1)."""
def setUp(self):
from plugin.archivar.outbound_gate import OutboundGate, _TurnHandle
self.OutboundGate = OutboundGate
self._TurnHandle = _TurnHandle
def test_turn_handle_has_owner_session_id_field(self):
"""_TurnHandle hat owner_session_id Feld mit Default ''."""
handle = self._TurnHandle(
task_token="token-1",
started_at=12345.0,
real_room_id="room-a",
)
self.assertEqual(handle.owner_session_id, "")
def test_try_acquire_records_owner_session_id(self):
"""try_acquire speichert owner_session_id im _TurnHandle."""
gate = self.OutboundGate()
async def _run():
return await gate.try_acquire("room-a", "token-a", owner_session_id="session-1")
decision = asyncio.run(_run())
self.assertTrue(decision.allow)
self.assertEqual(decision.reason, "gate_clear")
# Verify: _TurnHandle hat owner_session_id
handle = gate._in_flight["room-a"]
self.assertEqual(handle.owner_session_id, "session-1")
def test_release_respects_owner_session_id(self):
"""release() mit Token-Mismatch aber Session-ID-Match → release OK."""
gate = self.OutboundGate()
async def _run():
await gate.try_acquire("room-a", "token-a", owner_session_id="session-1")
asyncio.run(_run())
# Release mit falschem Token, aber korrekter Session-ID
# (Simuliert: Stream-Completion in anderem asyncio-Task,
# _CURRENT_TASK_TOKEN ist leer, aber _CURRENT_SESSION_ID matcht)
gate.release("room-a", "") # task_token="" (leer, wie bei Stream-Retry)
# Der Eintrag sollte entfernt worden sein (Session-ID-Match)
self.assertNotIn("room-a", gate._in_flight)
self.assertEqual(gate.stats.released_total, 1)
def test_release_token_mismatch_no_session_match_skips(self):
"""release() mit Token-Mismatch UND Session-ID-Mismatch → skip."""
gate = self.OutboundGate()
async def _run():
await gate.try_acquire("room-a", "token-a", owner_session_id="session-1")
asyncio.run(_run())
# Release mit falschem Token UND keiner Session-ID (default "")
# → sollte skippen
gate.release("room-a", "wrong-token")
# Der Eintrag sollte NICHT entfernt worden sein
self.assertIn("room-a", gate._in_flight)
self.assertEqual(gate.stats.released_total, 0)
def test_release_token_match_no_session_needed(self):
"""release() mit korrektem Token → release OK (Session-ID nicht benötigt)."""
gate = self.OutboundGate()
async def _run():
await gate.try_acquire("room-a", "token-a", owner_session_id="session-1")
asyncio.run(_run())
# Release mit korrektem Token
gate.release("room-a", "token-a")
self.assertNotIn("room-a", gate._in_flight)
self.assertEqual(gate.stats.released_total, 1)
# ═══════════════════════════════════════════════════════════════════════════════
# B2: allow_proactive_user_map Opt-In
# ═══════════════════════════════════════════════════════════════════════════════
class TestAllowProactiveUserMap(unittest.TestCase):
"""Tests für allow_proactive_user_map Opt-In (B2)."""
def setUp(self):
"""Build a minimal mock adapter for send() testing."""
import threading
from unittest.mock import MagicMock, AsyncMock
os.environ["MULTIROOM_AGENT"] = "true"
os.environ["ROCKETCHAT_BASE_URL"] = "https://rocket.example.com"
os.environ["ROCKETCHAT_USER"] = "testbot"
os.environ["ROCKETCHAT_PASSWORD"] = "testpass"
from plugin.adapter import RocketChatAdapter, RocketChatREST
self.adapter = RocketChatAdapter.__new__(RocketChatAdapter)
self.adapter.config = MagicMock()
self.adapter.config.extra = {}
self.adapter.platform = "rocketchat"
self.adapter.base_url = "https://rocket.example.com"
self.adapter.user = "testbot"
self.adapter.password = "testpass"
self.adapter.rest = MagicMock(spec=RocketChatREST)
self.adapter.rest.auth_token = "fake-token"
self.adapter.rest.user_id = "fake-user-id"
self.adapter.rest.post_message = MagicMock(return_value="msg_12345")
self.adapter.ddp = None
self.adapter._auth_token = None
self.adapter._user_id = None
self.adapter._rooms = []
self.adapter._subscribed_rooms = set()
self.adapter._listen_task = None
self.adapter._status_timer = None
self.adapter._last_activity = 0.0
self.adapter._shutdown_event = threading.Event()
self.adapter._room_info = {}
self.adapter._pending_clarifies = {}
self.adapter._user_rooms = {}
self.adapter._rooms_with_pending_questions = set()
self.adapter._excluded_room_ids = set()
self.adapter._last_server_activity = 0.0
self.adapter._health_check_timer = None
self.adapter._last_ddp_ping_ok = False
self.adapter._running = False
self.adapter._pending_move_requests = {}
self.adapter._session_room_preferences = {}
self.adapter._recent_auto_routes = {}
self.adapter._explicit_switch_sticky = {}
self.adapter._clarify_state = {}
self.adapter._pending_clarify_dispatch = {}
self.adapter._onboarding_state = {}
self.adapter._room_map_summary = ""
self.adapter._post_message_with_retry = AsyncMock(return_value=True)
self.adapter._find_fallback_room_for_user = MagicMock(return_value=None)
self.adapter._replace_slash_with_double_colon = MagicMock(
side_effect=lambda x: x
)
self.adapter._conversation_history = None
self.adapter._multiroom_context = None
self.adapter.archivar = None
# OutboundGate mock
from plugin.archivar.outbound_gate import OutboundGate
self.adapter._outbound_gate = OutboundGate()
# Import module-level state
from plugin.adapter import (
_CURRENT_ORIGIN_ROOM,
_THEMATIC_TARGET_ROOM,
_CURRENT_TASK_TOKEN,
_CURRENT_SESSION_ID,
_room_context,
_room_context_lock,
_RED_FLAG_PENDING,
)
self._CURRENT_ORIGIN_ROOM = _CURRENT_ORIGIN_ROOM
self._THEMATIC_TARGET_ROOM = _THEMATIC_TARGET_ROOM
self._CURRENT_TASK_TOKEN = _CURRENT_TASK_TOKEN
self._CURRENT_SESSION_ID = _CURRENT_SESSION_ID
self._room_context = _room_context
self._room_context_lock = _room_context_lock
self._RED_FLAG_PENDING = _RED_FLAG_PENDING
def tearDown(self):
"""Clean up module-level state between tests."""
self._CURRENT_ORIGIN_ROOM.set("")
self._THEMATIC_TARGET_ROOM.set("")
self._CURRENT_TASK_TOKEN.set("")
self._CURRENT_SESSION_ID.set("")
self._RED_FLAG_PENDING.set({})
with self._room_context_lock:
self._room_context.clear()
def test_user_map_blocked_by_default(self):
"""Ohne allow_proactive_user_map=True → Priority 2 (_user_rooms[-1]) wird NICHT genutzt."""
chat_id = "user:alice"
wrong_room = "room_wrong_general"
# ContextVars sind LEER (kein _CURRENT_ORIGIN_ROOM, kein _room_context)
self._CURRENT_ORIGIN_ROOM.set("")
self._THEMATIC_TARGET_ROOM.set("")
self._CURRENT_TASK_TOKEN.set("")
# _user_rooms hat einen Raum (Priority 2)
self.adapter._user_rooms = {chat_id: [wrong_room]}
# _find_fallback_room_for_user gibt None zurück
self.adapter._find_fallback_room_for_user = MagicMock(return_value=None)
# Config: allow_proactive_user_map = False (default)
self.adapter.config.extra = {}
result = asyncio.run(
self.adapter.send(chat_id=chat_id, content="Test response")
)
# Verify: send() hat einen Fehler zurückgegeben (kein Raum gefunden)
# SendResult kann dict (Fallback) oder SendResult-Objekt sein
_success = result.success if hasattr(result, 'success') else result.get('success', True)
_error = result.error if hasattr(result, 'error') else result.get('error', '')
self.assertFalse(_success)
self.assertIn("No resolved room", _error)
def test_user_map_allowed_with_optin(self):
"""Mit allow_proactive_user_map=True → Priority 2 (_user_rooms[-1]) wird genutzt."""
chat_id = "user:alice"
correct_room = "room_correct_dm"
# ContextVars sind LEER
self._CURRENT_ORIGIN_ROOM.set("")
self._THEMATIC_TARGET_ROOM.set("")
self._CURRENT_TASK_TOKEN.set("")
# _user_rooms hat einen Raum
self.adapter._user_rooms = {chat_id: [correct_room]}
# Config: allow_proactive_user_map = True
self.adapter.config.extra = {"allow_proactive_user_map": True}
result = asyncio.run(
self.adapter.send(chat_id=chat_id, content="Test response")
)
# Verify: send() hat _post_message_with_retry mit dem korrekten Raum aufgerufen
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)
def test_fallback_room_respects_optin(self):
"""_find_fallback_room_for_user wird NUR genutzt wenn allow_proactive_user_map=True."""
chat_id = "user:alice"
fallback_room = "room_fallback_123"
# ContextVars sind LEER
self._CURRENT_ORIGIN_ROOM.set("")
self._THEMATIC_TARGET_ROOM.set("")
self._CURRENT_TASK_TOKEN.set("")
# _user_rooms ist LEER (kein Priority 2)
self.adapter._user_rooms = {}
# _find_fallback_room_for_user gibt einen Raum zurück
self.adapter._find_fallback_room_for_user = MagicMock(return_value=fallback_room)
# Config: allow_proactive_user_map = False (default)
self.adapter.config.extra = {}
result = asyncio.run(
self.adapter.send(chat_id=chat_id, content="Test response")
)
# Verify: send() hat einen Fehler zurückgegeben (Fallback nicht genutzt)
_success = result.success if hasattr(result, 'success') else result.get('success', True)
_error = result.error if hasattr(result, 'error') else result.get('error', '')
self.assertFalse(_success)
self.assertIn("No resolved room", _error)
def test_allow_proactive_metadata_override(self):
"""metadata['allow_proactive'] = True überschreibt Config-Wert pro-Aufruf."""
chat_id = "user:alice"
correct_room = "room_proactive_override"
# ContextVars sind LEER
self._CURRENT_ORIGIN_ROOM.set("")
self._THEMATIC_TARGET_ROOM.set("")
self._CURRENT_TASK_TOKEN.set("")
# _user_rooms hat einen Raum
self.adapter._user_rooms = {chat_id: [correct_room]}
# Config: allow_proactive_user_map = False (default)
self.adapter.config.extra = {}
# metadata['allow_proactive'] = True überschreibt
result = asyncio.run(
self.adapter.send(
chat_id=chat_id,
content="Test response",
metadata={"allow_proactive": True},
)
)
# Verify: send() hat _post_message_with_retry mit dem korrekten Raum aufgerufen
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)
# ═══════════════════════════════════════════════════════════════════════════════
# B+: Sweep-Intervall + max_entry_age reduziert
# ═══════════════════════════════════════════════════════════════════════════════
class TestSweepIntervalReduced(unittest.TestCase):
"""Tests für reduziertes Sweep-Intervall und max_entry_age (B+)."""
def test_max_entry_age_default_is_10s(self):
"""OutboundGate default max_entry_age_s ist 10.0 (war 60.0)."""
from plugin.archivar.outbound_gate import OutboundGate
gate = OutboundGate()
self.assertEqual(gate.max_entry_age_s, 10.0)
def test_sweep_removes_stale_after_10s(self):
"""Stale Einträge werden nach 10s entfernt (nicht erst nach 60s)."""
from plugin.archivar.outbound_gate import OutboundGate
gate = OutboundGate(max_entry_age_s=0.05) # 50ms für schnellen Test
async def _run():
await gate.try_acquire("room-a", "token-a")
self.assertIn("room-a", gate._in_flight)
await asyncio.sleep(0.1) # 100ms > 50ms TTL
swept = gate._sweep_stale_entries()
self.assertGreaterEqual(swept, 1)
self.assertNotIn("room-a", gate._in_flight)
asyncio.run(_run())
# ═══════════════════════════════════════════════════════════════════════════════
# Integration: Concurrent-Session-Isolation
# ═══════════════════════════════════════════════════════════════════════════════
class TestSessionIdIsolatesConcurrentSessions(unittest.TestCase):
"""Integrationstest: Zwei parallele Dispatches mit verschiedenen session_ids
dürfen sich nicht gegenseitig die Gate-Slots streitig machen."""
def test_session_id_isolates_concurrent_sessions(self):
"""Zwei Sessions mit verschiedenen session_ids können parallel senden."""
from plugin.archivar.outbound_gate import OutboundGate
gate = OutboundGate()
async def _run():
# Session 1: Raum A, Token A, Session-ID "session-1"
decision_1 = await gate.try_acquire(
"room-a", "token-a", owner_session_id="session-1"
)
self.assertTrue(decision_1.allow)
self.assertEqual(decision_1.reason, "gate_clear")
# Session 2: Raum B, Token B, Session-ID "session-2"
# Sollte blockiert sein (anderer Raum busy)
decision_2 = await gate.try_acquire(
"room-b", "token-b", owner_session_id="session-2"
)
self.assertFalse(decision_2.allow)
self.assertEqual(decision_2.reason, "different_room_busy")
# Session 1 released (Token ist leer wegen Stream-Retry in anderem Task)
# ABER: owner_session_id matcht → release OK
gate.release("room-a", "") # task_token="" (leer)
# Jetzt sollte Session 2 senden können
decision_2_retry = await gate.try_acquire(
"room-b", "token-b", owner_session_id="session-2"
)
self.assertTrue(decision_2_retry.allow)
self.assertEqual(decision_2_retry.reason, "gate_clear")
# Cleanup
gate.release("room-b", "token-b")
asyncio.run(_run())
def test_same_session_multi_turn_allowed(self):
"""Gleiche Session, gleicher Raum, gleicher Token → Multi-Turn allowed."""
from plugin.archivar.outbound_gate import OutboundGate
gate = OutboundGate()
async def _run():
# Erster Turn
d1 = await gate.try_acquire(
"room-a", "token-a", owner_session_id="session-1"
)
self.assertTrue(d1.allow)
self.assertEqual(d1.reason, "gate_clear")
# Zweiter Turn (gleiche Session, gleicher Raum, gleicher Token)
d2 = await gate.try_acquire(
"room-a", "token-a", owner_session_id="session-1"
)
self.assertTrue(d2.allow)
self.assertEqual(d2.reason, "same_room_same_token")
# Release
gate.release("room-a", "token-a")
asyncio.run(_run())
if __name__ == "__main__":
unittest.main()
@@ -836,8 +836,6 @@ class TestRoomContextCrossContamination(unittest.TestCase):
# _user_rooms hat einen Fallback-Raum (nächste Priorität nach _room_context) # _user_rooms hat einen Fallback-Raum (nächste Priorität nach _room_context)
self.adapter._user_rooms = {chat_id: [fallback_room]} self.adapter._user_rooms = {chat_id: [fallback_room]}
self.adapter._find_fallback_room_for_user = MagicMock(return_value=None) self.adapter._find_fallback_room_for_user = MagicMock(return_value=None)
# B2: allow_proactive_user_map=True für _user_rooms-Fallback
self.adapter.config.extra = {"allow_proactive_user_map": True}
result = asyncio.run( result = asyncio.run(
self.adapter.send(chat_id=chat_id, content="Test response for Dispatch A") self.adapter.send(chat_id=chat_id, content="Test response for Dispatch A")
@@ -958,8 +956,6 @@ class TestRoomContextCrossContamination(unittest.TestCase):
# _user_rooms hat einen Fallback-Raum # _user_rooms hat einen Fallback-Raum
self.adapter._user_rooms = {chat_id: [user_rooms_room]} self.adapter._user_rooms = {chat_id: [user_rooms_room]}
self.adapter._find_fallback_room_for_user = MagicMock(return_value=None) self.adapter._find_fallback_room_for_user = MagicMock(return_value=None)
# B2: allow_proactive_user_map=True für _user_rooms-Fallback
self.adapter.config.extra = {"allow_proactive_user_map": True}
result = asyncio.run( result = asyncio.run(
self.adapter.send(chat_id=chat_id, content="Test response") self.adapter.send(chat_id=chat_id, content="Test response")
+3 -3
View File
@@ -94,10 +94,10 @@ class RateLimiter:
"""Simple token-bucket rate limiter. """Simple token-bucket rate limiter.
Allows max_tokens calls per window_seconds. Thread-safe via lock. Allows max_tokens calls per window_seconds. Thread-safe via lock.
Default: 15 calls/minute (was 30 — RC triggers 429 aggressively). Default: 30 calls/minute (was 60 — RC triggers 429 at 3-4 calls in <10s).
""" """
def __init__(self, max_tokens: int = 15, window_seconds: float = 60.0): def __init__(self, max_tokens: int = 30, window_seconds: float = 60.0):
self.max_tokens = max_tokens self.max_tokens = max_tokens
self.window_seconds = window_seconds self.window_seconds = window_seconds
self.tokens = float(max_tokens) self.tokens = float(max_tokens)
@@ -138,7 +138,7 @@ _rate_limiter: RateLimiter | None = None
def _get_rate_limiter() -> RateLimiter: def _get_rate_limiter() -> RateLimiter:
global _rate_limiter global _rate_limiter
if _rate_limiter is None: if _rate_limiter is None:
_rate_limiter = RateLimiter(max_tokens=15, window_seconds=60.0) _rate_limiter = RateLimiter(max_tokens=30, window_seconds=60.0)
return _rate_limiter return _rate_limiter
+10 -10
View File
@@ -24,13 +24,13 @@ from .rc_rest import RCRestClient
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
# Progressive backoff intervals in seconds (rate-limiter-friendly). # Progressive backoff intervals in seconds (rate-limiter-friendly).
# Default: 5s -> 8s -> 12s -> 20s (max 45s total). # Default: 2s -> 3s -> 5s -> 8s (max 18s total).
# Callers can override the first interval via initial_interval. # Callers can override the first interval via initial_interval.
_DEFAULT_BACKOFF_INTERVALS = [5.0, 8.0, 12.0, 20.0] _DEFAULT_BACKOFF_INTERVALS = [2.0, 3.0, 5.0, 8.0]
_MAX_TOTAL_WAIT = 45.0 # seconds _MAX_TOTAL_WAIT = 18.0 # seconds
# 429 exponential backoff: 5s -> 10s -> 20s -> 40s (max) # 429 exponential backoff: 3s -> 6s -> 12s -> 20s -> 30s (max)
_MAX_429_BACKOFF = 40.0 _MAX_429_BACKOFF = 30.0
# After 5 consecutive 429s, abort with SKIP instead of retrying forever # After 5 consecutive 429s, abort with SKIP instead of retrying forever
_MAX_CONSECUTIVE_429 = 5 _MAX_CONSECUTIVE_429 = 5
@@ -89,7 +89,7 @@ def wait_for_bot_message(
cached_messages: list = [] # Cursor caching: reuse fetched batch cached_messages: list = [] # Cursor caching: reuse fetched batch
# Build backoff intervals with caller's initial_interval # Build backoff intervals with caller's initial_interval
backoff_intervals = [initial_interval, 8.0, 12.0, 20.0] backoff_intervals = [initial_interval, 3.0, 5.0, 8.0]
while time.monotonic() < deadline: while time.monotonic() < deadline:
# Cursor caching: if we already have messages, scan them first # Cursor caching: if we already have messages, scan them first
@@ -137,8 +137,8 @@ def wait_for_bot_message(
"aggressive. Consider increasing poll intervals or " "aggressive. Consider increasing poll intervals or "
"reducing concurrent test load." "reducing concurrent test load."
) )
# Exponential backoff on rate-limit errors: 5s -> 10s -> 20s -> 40s # Exponential backoff on rate-limit errors: 3s -> 6s -> 12s -> 20s -> 30s
backoff = min(5.0 * (2 ** (consecutive_429 - 1)), _MAX_429_BACKOFF) backoff = min(3.0 * (2 ** (consecutive_429 - 1)), _MAX_429_BACKOFF)
logger.warning( logger.warning(
"Poll: HTTP 429 (consecutive=%d/%d) -- backing off %ds", "Poll: HTTP 429 (consecutive=%d/%d) -- backing off %ds",
consecutive_429, _MAX_CONSECUTIVE_429, backoff, consecutive_429, _MAX_CONSECUTIVE_429, backoff,
@@ -170,12 +170,12 @@ def wait_for_bot_message(
) )
return msg return msg
# Progressive backoff: initial_interval -> 8s -> 12s -> 20s # Progressive backoff: initial_interval -> 3s -> 5s -> 8s
if interval_idx < len(backoff_intervals): if interval_idx < len(backoff_intervals):
delay = backoff_intervals[interval_idx] delay = backoff_intervals[interval_idx]
interval_idx += 1 interval_idx += 1
else: else:
delay = 20.0 delay = 8.0
remaining = deadline - time.monotonic() remaining = deadline - time.monotonic()
if remaining <= 0: if remaining <= 0:
+3 -3
View File
@@ -77,9 +77,9 @@ class RCRestClient:
req = urllib.request.Request(url, data=body, headers=headers, method=method) req = urllib.request.Request(url, data=body, headers=headers, method=method)
# 429 retry with exponential backoff: 5s → 10s → 20s → 40s (max 4 retries) # 429 retry with exponential backoff: 3s → 6s → 12s → 20s → 30s (max 5 retries)
# Total possible wait: 75s — gives RC enough time to reset its rate-limit window. # Total possible wait: 71s — gives RC enough time to reset its rate-limit window.
_429_BACKOFFS = [5.0, 10.0, 20.0, 40.0] _429_BACKOFFS = [3.0, 6.0, 12.0, 20.0, 30.0]
max_429_retries = len(_429_BACKOFFS) max_429_retries = len(_429_BACKOFFS)
for attempt in range(max_429_retries + 1): for attempt in range(max_429_retries + 1):
# Rate-limit before every API call (protects post, history, delete, etc.) # Rate-limit before every API call (protects post, history, delete, etc.)