Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 8fba9a4a39 | |||
| 0310bd5fd5 | |||
| 9f3cc02148 | |||
| 6aaadcdb88 |
+64
-8
@@ -51,6 +51,13 @@ _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.
|
||||||
@@ -1177,7 +1184,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=60.0)
|
self._outbound_gate = OutboundGate(default_timeout_s=30.0, max_entry_age_s=10.0) # B+: 10s statt 60s
|
||||||
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
|
||||||
@@ -4703,6 +4710,11 @@ 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
|
||||||
@@ -6659,7 +6671,8 @@ 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
|
||||||
decision = await self._outbound_gate.try_acquire(_gate_room_id, task_token)
|
_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, 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
|
||||||
@@ -6669,7 +6682,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)
|
decision = await self._outbound_gate.try_acquire(_gate_room_id, task_token, owner_session_id=_session_id)
|
||||||
except asyncio.TimeoutError:
|
except asyncio.TimeoutError:
|
||||||
decision = GateDecision(allow=False, reason="timeout")
|
decision = GateDecision(allow=False, reason="timeout")
|
||||||
|
|
||||||
@@ -6748,6 +6761,27 @@ 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:
|
||||||
@@ -7111,7 +7145,8 @@ 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
|
||||||
decision = await self._outbound_gate.try_acquire(_gate_room_id, task_token)
|
_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, 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:
|
||||||
@@ -7119,7 +7154,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)
|
decision = await self._outbound_gate.try_acquire(_gate_room_id, task_token, owner_session_id=_session_id)
|
||||||
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:
|
||||||
@@ -7190,6 +7225,27 @@ 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:
|
||||||
@@ -7357,12 +7413,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).
|
||||||
Sweept alle 30s — entfernt Einträge die älter als
|
B+: Sweept alle 5s (war 30s) — entfernt Einträge die älter als
|
||||||
max_entry_age_s (60s) sind.
|
max_entry_age_s (10s, war 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(30.0)
|
await asyncio.sleep(5.0) # B+: 5s statt 30s
|
||||||
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:
|
||||||
|
|||||||
@@ -51,6 +51,8 @@ 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
|
||||||
@@ -59,6 +61,7 @@ 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 ───────────────────────────────────
|
||||||
@@ -123,13 +126,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 = 60.0,
|
max_entry_age_s: float = 10.0, # B+: 10s statt 60s
|
||||||
):
|
):
|
||||||
"""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 (60s).
|
max_entry_age_s: Maximales Alter eines Eintrags bevor er als stale gilt (10s, B+).
|
||||||
"""
|
"""
|
||||||
self._in_flight: Dict[str, _TurnHandle] = {}
|
self._in_flight: Dict[str, _TurnHandle] = {}
|
||||||
self._lock = asyncio.Lock()
|
self._lock = asyncio.Lock()
|
||||||
@@ -150,7 +153,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) -> GateDecision:
|
async def try_acquire(self, room_id: str, task_token: str, owner_session_id: 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.
|
||||||
@@ -166,6 +169,8 @@ 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.
|
||||||
@@ -218,6 +223,7 @@ 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
|
||||||
@@ -270,13 +276,17 @@ 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(
|
||||||
@@ -287,12 +297,22 @@ 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:
|
||||||
logger.warning(
|
# B1: Session-ID-Fallback — task_token ist leer (Stream-Retry
|
||||||
"[outbound_gate] Release token mismatch: "
|
# in anderem asyncio-Task), aber owner_session_id existiert.
|
||||||
"room=%s expected=%s got=%s — skipping",
|
if not task_token and existing.owner_session_id:
|
||||||
room_id[:8], existing.task_token[:8], task_token[:8],
|
logger.info(
|
||||||
)
|
"[outbound_gate] Release via session-id fallback: "
|
||||||
return
|
"room=%s token empty, session=%s",
|
||||||
|
room_id[:8], existing.owner_session_id[:8],
|
||||||
|
)
|
||||||
|
# Fall through to release
|
||||||
|
else:
|
||||||
|
logger.warning(
|
||||||
|
"[outbound_gate] Release token mismatch: "
|
||||||
|
"room=%s expected=%s got=%s — skipping",
|
||||||
|
room_id[:8], existing.task_token[:8], task_token[:8],
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
del self._in_flight[room_id]
|
del self._in_flight[room_id]
|
||||||
self.stats.released_total += 1
|
self.stats.released_total += 1
|
||||||
|
|||||||
@@ -1061,13 +1061,17 @@ class PulseController:
|
|||||||
class DetectionTimer:
|
class DetectionTimer:
|
||||||
"""Detects whether background agents are active.
|
"""Detects whether background agents are active.
|
||||||
|
|
||||||
P1b: gateway_state.json is PRIMARY — active_agents > 1 means active.
|
P2 Fix Option D: PID-Sentinel ist PRIMARY — prüft ob Gateway-Prozess lebt.
|
||||||
P1-2: plugin_state.json is SECONDARY — background_tasks > 0 means active.
|
gateway_state.json ist SECONDARY — active_agents > 0 bedeutet Subagenten aktiv.
|
||||||
pgrep is TERTIARY/CONFIRM — used as fallback when gateway_state and
|
plugin_state.json ist TERTIARY — background_tasks > 0 bedeutet aktiv.
|
||||||
plugin_state are unavailable or return 0/1 (ambiguous).
|
pgrep ist QUATERNARY/FALLBACK — 'hermes_cli|hermes chat|gateway run'.
|
||||||
|
|
||||||
pgrep pattern: 'hermes_cli|hermes chat' (catches subagents AND gateway
|
pgrep pattern: 'hermes_cli|hermes chat|gateway run' (fängt Subagenten
|
||||||
subprocesses). Self-pid exclude is preserved.
|
UND Gateway-Prozess). Self-pid exclude bleibt erhalten.
|
||||||
|
|
||||||
|
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.
|
||||||
"""
|
"""
|
||||||
@@ -1132,17 +1136,37 @@ 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.
|
||||||
|
|
||||||
P1b: gateway_state.json is PRIMARY — active_agents > 1 means active.
|
P2 Fix Option D: PID-Sentinel ist PRIMARY — prüft ob Gateway-Prozess lebt.
|
||||||
P1-2: plugin_state.json is SECONDARY — background_tasks > 0 means active.
|
gateway_state.json ist SECONDARY — active_agents > 0 bedeutet Subagenten aktiv.
|
||||||
pgrep is TERTIARY/CONFIRM — used as fallback when gateway_state and
|
plugin_state.json ist TERTIARY — background_tasks > 0 bedeutet aktiv.
|
||||||
plugin_state are unavailable or return 0/1 (ambiguous).
|
pgrep ist QUATERNARY/FALLBACK — 'hermes_cli|hermes chat|gateway run'.
|
||||||
|
|
||||||
pgrep pattern expanded from 'hermes chat --profile' to
|
pgrep pattern: 'hermes_cli|hermes chat|gateway run' (fängt Subagenten
|
||||||
'hermes_cli|hermes chat' to catch subagents AND gateway subprocesses.
|
UND Gateway-Prozess). Self-pid exclude bleibt erhalten.
|
||||||
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.
|
||||||
@@ -1153,27 +1177,36 @@ 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
|
||||||
|
|
||||||
# ── PRIMARY: gateway_state.json ────────────────────────────────────
|
# ── P2 PRIMARY: PID-Sentinel — prüft ob Gateway-Prozess lebt ────────
|
||||||
try:
|
if self._check_gateway_pid_alive():
|
||||||
if os.path.exists(self._gateway_state_path):
|
result = True
|
||||||
with open(self._gateway_state_path, 'r') as f:
|
pid_used = True
|
||||||
state = json.load(f)
|
detection_source = "gateway_pid"
|
||||||
gateway_active = state.get("active_agents", 0)
|
|
||||||
if gateway_active > 1:
|
|
||||||
result = True
|
|
||||||
gateway_used = True
|
|
||||||
detection_source = "gateway"
|
|
||||||
except (json.JSONDecodeError, IOError, OSError) as e:
|
|
||||||
logger.debug("[detection] gateway_state.json read failed: %s", e)
|
|
||||||
# Fall through to plugin_state
|
|
||||||
|
|
||||||
# ── P1-2: SECONDARY: plugin_state.json ─────────────────────────────
|
# ── P2 SECONDARY: gateway_state.json (Schwelle >0, war >1) ──────────
|
||||||
if not gateway_used:
|
if not pid_used:
|
||||||
|
try:
|
||||||
|
if os.path.exists(self._gateway_state_path):
|
||||||
|
with open(self._gateway_state_path, 'r') as f:
|
||||||
|
state = json.load(f)
|
||||||
|
gateway_active = state.get("active_agents", 0)
|
||||||
|
# P2 Fix: Schwelle >0 statt >1
|
||||||
|
if gateway_active > 0:
|
||||||
|
result = True
|
||||||
|
gateway_used = True
|
||||||
|
detection_source = "gateway"
|
||||||
|
except (json.JSONDecodeError, IOError, OSError) as e:
|
||||||
|
logger.debug("[detection] gateway_state.json read failed: %s", e)
|
||||||
|
# Fall through to plugin_state
|
||||||
|
|
||||||
|
# ── P1-2: TERTIARY: plugin_state.json ────────────────────────────────
|
||||||
|
if not pid_used and 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:
|
||||||
@@ -1181,13 +1214,13 @@ class DetectionTimer:
|
|||||||
plugin_used = True
|
plugin_used = True
|
||||||
detection_source = "plugin_state"
|
detection_source = "plugin_state"
|
||||||
|
|
||||||
# ── TERTIARY: pgrep — run when neither gateway nor plugin decided ──
|
# ── P2 QUATERNARY: pgrep — erweitertes Pattern 'gateway run' ────────
|
||||||
if not gateway_used and not plugin_used:
|
if not pid_used and not gateway_used and not plugin_used:
|
||||||
try:
|
try:
|
||||||
own_pid = os.getpid()
|
own_pid = os.getpid()
|
||||||
# P1b: Expanded pattern catches subagents AND gateway subprocesses
|
# P2 Fix: Pattern um 'gateway run' erweitert
|
||||||
proc = subprocess.run(
|
proc = subprocess.run(
|
||||||
["pgrep", "-f", "hermes_cli|hermes chat"],
|
["pgrep", "-f", "hermes_cli|hermes chat|gateway run"],
|
||||||
capture_output=True,
|
capture_output=True,
|
||||||
text=True,
|
text=True,
|
||||||
timeout=5,
|
timeout=5,
|
||||||
@@ -1208,10 +1241,12 @@ 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: gateway_state=%d (primary=%s), "
|
"[detection] check #%d: pid_sentinel=%s, 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, gateway_active,
|
self._check_count,
|
||||||
|
"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,
|
||||||
|
|||||||
@@ -960,24 +960,25 @@ class TestDetectionTimerPgrepPrimary:
|
|||||||
stderr="",
|
stderr="",
|
||||||
returncode=0,
|
returncode=0,
|
||||||
)
|
)
|
||||||
|
# P2: PID-Sentinel deaktivieren, damit gateway_state/pgrep getestet wird
|
||||||
dt = DetectionTimer(
|
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||||
gateway_state_path=state_path,
|
dt = DetectionTimer(
|
||||||
detection_interval=0.1,
|
gateway_state_path=state_path,
|
||||||
)
|
detection_interval=0.1,
|
||||||
result = dt.check()
|
)
|
||||||
# gateway_state=1 → pgrep-Fallback findet anderen Prozess → True
|
result = dt.check()
|
||||||
assert result is True
|
# gateway_state=1 > 0 → SECONDARY entscheidet → 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 (>1) → PRIMARY entscheidet → result=True, pgrep NICHT aufgerufen."""
|
"""P1b: gateway_state active_agents=3 (>0) → SECONDARY 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 (>1 → PRIMARY entscheidet)
|
# gateway_state mit active_agents=3 (>0 → SECONDARY 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)
|
||||||
@@ -986,15 +987,17 @@ 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:
|
||||||
dt = DetectionTimer(
|
# P2: PID-Sentinel deaktivieren, damit gateway_state getestet wird
|
||||||
gateway_state_path=state_path,
|
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||||
detection_interval=0.1,
|
dt = DetectionTimer(
|
||||||
)
|
gateway_state_path=state_path,
|
||||||
result = dt.check()
|
detection_interval=0.1,
|
||||||
# gateway_state=3 > 1 → PRIMARY entscheidet → True
|
)
|
||||||
assert result is True
|
result = dt.check()
|
||||||
# pgrep wurde NICHT aufgerufen (gateway_state hat entschieden)
|
# gateway_state=3 > 0 → SECONDARY entscheidet → True
|
||||||
mock_run.assert_not_called()
|
assert result is True
|
||||||
|
# pgrep wurde NICHT aufgerufen (gateway_state hat entschieden)
|
||||||
|
mock_run.assert_not_called()
|
||||||
finally:
|
finally:
|
||||||
os.unlink(state_path)
|
os.unlink(state_path)
|
||||||
|
|
||||||
@@ -1015,14 +1018,15 @@ class TestDetectionTimerPgrepNoGatewayState:
|
|||||||
stderr="",
|
stderr="",
|
||||||
returncode=0,
|
returncode=0,
|
||||||
)
|
)
|
||||||
|
# P2: PID-Sentinel deaktivieren, damit pgrep getestet wird
|
||||||
dt = DetectionTimer(
|
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
dt = DetectionTimer(
|
||||||
detection_interval=0.1,
|
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||||
)
|
detection_interval=0.1,
|
||||||
result = dt.check()
|
)
|
||||||
# pgrep findet anderen Prozess → True
|
result = dt.check()
|
||||||
assert result is True
|
# pgrep findet anderen Prozess → True
|
||||||
|
assert result is True
|
||||||
|
|
||||||
def test_pgrep_returns_bool(self):
|
def test_pgrep_returns_bool(self):
|
||||||
"""pgrep liefert immer bool zurück."""
|
"""pgrep liefert immer bool zurück."""
|
||||||
@@ -1037,13 +1041,14 @@ class TestDetectionTimerPgrepNoGatewayState:
|
|||||||
stderr="",
|
stderr="",
|
||||||
returncode=0,
|
returncode=0,
|
||||||
)
|
)
|
||||||
|
# P2: PID-Sentinel deaktivieren, damit pgrep getestet wird
|
||||||
dt = DetectionTimer(
|
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
dt = DetectionTimer(
|
||||||
detection_interval=0.1,
|
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||||
)
|
detection_interval=0.1,
|
||||||
result = dt.check()
|
)
|
||||||
assert result is True or result is False
|
result = dt.check()
|
||||||
|
assert result is True or result is False
|
||||||
|
|
||||||
|
|
||||||
class TestDetectionTimerIntegration:
|
class TestDetectionTimerIntegration:
|
||||||
@@ -1368,14 +1373,15 @@ class TestDetectionTimerPgrepSelfExclude:
|
|||||||
stderr="",
|
stderr="",
|
||||||
returncode=0,
|
returncode=0,
|
||||||
)
|
)
|
||||||
|
# P2: PID-Sentinel deaktivieren, damit pgrep getestet wird
|
||||||
dt = DetectionTimer(
|
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
dt = DetectionTimer(
|
||||||
detection_interval=0.1,
|
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||||
)
|
detection_interval=0.1,
|
||||||
result = dt.check()
|
)
|
||||||
# Own PID should be excluded → no background agents → False
|
result = dt.check()
|
||||||
assert result is False
|
# Own PID should be excluded → no background agents → False
|
||||||
|
assert result is False
|
||||||
|
|
||||||
def test_pgrep_self_exclude_with_other_pids(self):
|
def test_pgrep_self_exclude_with_other_pids(self):
|
||||||
"""pgrep findet eigenen + fremden Prozess → check() returns True."""
|
"""pgrep findet eigenen + fremden Prozess → check() returns True."""
|
||||||
@@ -1390,14 +1396,15 @@ class TestDetectionTimerPgrepSelfExclude:
|
|||||||
stderr="",
|
stderr="",
|
||||||
returncode=0,
|
returncode=0,
|
||||||
)
|
)
|
||||||
|
# P2: PID-Sentinel deaktivieren, damit pgrep getestet wird
|
||||||
dt = DetectionTimer(
|
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
dt = DetectionTimer(
|
||||||
detection_interval=0.1,
|
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||||
)
|
detection_interval=0.1,
|
||||||
result = dt.check()
|
)
|
||||||
# After excluding own PID, one other PID remains → True
|
result = dt.check()
|
||||||
assert result is True
|
# After excluding own PID, one other PID remains → True
|
||||||
|
assert result is True
|
||||||
|
|
||||||
|
|
||||||
class TestDetectionTimerOnChangeCallback:
|
class TestDetectionTimerOnChangeCallback:
|
||||||
@@ -1428,33 +1435,35 @@ 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
|
||||||
|
|
||||||
dt = DetectionTimer(
|
# P2: PID-Sentinel deaktivieren, damit pgrep getestet wird
|
||||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||||
detection_interval=0.1,
|
dt = DetectionTimer(
|
||||||
on_change=on_change,
|
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||||
)
|
detection_interval=0.1,
|
||||||
|
on_change=on_change,
|
||||||
|
)
|
||||||
|
|
||||||
# Check 1: nur eigener Prozess → False (kein Callback, _last_result startet False)
|
# Check 1: nur eigener Prozess → False (kein Callback, _last_result startet False)
|
||||||
result1 = dt.check()
|
result1 = dt.check()
|
||||||
assert result1 is False
|
assert result1 is False
|
||||||
assert len(callback_results) == 0
|
assert len(callback_results) == 0
|
||||||
|
|
||||||
# Check 2: anderer Prozess erscheint → True (Callback: False→True)
|
# Check 2: anderer Prozess erscheint → True (Callback: False→True)
|
||||||
result2 = dt.check()
|
result2 = dt.check()
|
||||||
assert result2 is True
|
assert result2 is True
|
||||||
assert len(callback_results) == 1
|
assert len(callback_results) == 1
|
||||||
assert callback_results[0] is True
|
assert callback_results[0] is True
|
||||||
|
|
||||||
# Check 3: immer noch da → True (kein Callback, kein Wechsel)
|
# Check 3: immer noch da → True (kein Callback, kein Wechsel)
|
||||||
result3 = dt.check()
|
result3 = dt.check()
|
||||||
assert result3 is True
|
assert result3 is True
|
||||||
assert len(callback_results) == 1
|
assert len(callback_results) == 1
|
||||||
|
|
||||||
# Check 4: verschwindet → False (Callback: True→False)
|
# Check 4: verschwindet → False (Callback: True→False)
|
||||||
result4 = dt.check()
|
result4 = dt.check()
|
||||||
assert result4 is False
|
assert result4 is False
|
||||||
assert len(callback_results) == 2
|
assert len(callback_results) == 2
|
||||||
assert callback_results[1] is False
|
assert callback_results[1] is False
|
||||||
|
|
||||||
|
|
||||||
class TestPulseControllerStartWithoutDdp:
|
class TestPulseControllerStartWithoutDdp:
|
||||||
@@ -2066,13 +2075,15 @@ class TestDetectionTimerPluginState:
|
|||||||
"schema_version": 1,
|
"schema_version": 1,
|
||||||
})
|
})
|
||||||
|
|
||||||
dt = DetectionTimer(
|
# P2: PID-Sentinel deaktivieren, damit plugin_state getestet wird
|
||||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||||
detection_interval=0.1,
|
dt = DetectionTimer(
|
||||||
plugin_state_path=state_path,
|
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||||
)
|
detection_interval=0.1,
|
||||||
result = dt.check()
|
plugin_state_path=state_path,
|
||||||
assert result is True
|
)
|
||||||
|
result = dt.check()
|
||||||
|
assert result is True
|
||||||
|
|
||||||
def test_plugin_state_background_tasks_zero_not_detected(self, tmp_path):
|
def test_plugin_state_background_tasks_zero_not_detected(self, tmp_path):
|
||||||
"""Plugin-State mit background_tasks=0 → check() fällt auf pgrep zurück."""
|
"""Plugin-State mit background_tasks=0 → check() fällt auf pgrep zurück."""
|
||||||
@@ -2094,13 +2105,15 @@ class TestDetectionTimerPluginState:
|
|||||||
stderr="",
|
stderr="",
|
||||||
returncode=0,
|
returncode=0,
|
||||||
)
|
)
|
||||||
dt = DetectionTimer(
|
# P2: PID-Sentinel deaktivieren, damit plugin_state/pgrep getestet wird
|
||||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||||
detection_interval=0.1,
|
dt = DetectionTimer(
|
||||||
plugin_state_path=state_path,
|
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||||
)
|
detection_interval=0.1,
|
||||||
result = dt.check()
|
plugin_state_path=state_path,
|
||||||
# background_tasks=0, gateway_state fehlt, pgrep nur self → False
|
)
|
||||||
|
result = dt.check()
|
||||||
|
# background_tasks=0, gateway_state fehlt, pgrep nur self → False
|
||||||
assert result is False
|
assert result is False
|
||||||
|
|
||||||
def test_plugin_state_missing_file_no_error(self):
|
def test_plugin_state_missing_file_no_error(self):
|
||||||
@@ -2114,14 +2127,16 @@ class TestDetectionTimerPluginState:
|
|||||||
stderr="",
|
stderr="",
|
||||||
returncode=0,
|
returncode=0,
|
||||||
)
|
)
|
||||||
dt = DetectionTimer(
|
# P2: PID-Sentinel deaktivieren, damit pgrep getestet wird
|
||||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||||
detection_interval=0.1,
|
dt = DetectionTimer(
|
||||||
plugin_state_path="/tmp/nonexistent_plugin_state.json",
|
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||||
)
|
detection_interval=0.1,
|
||||||
result = dt.check()
|
plugin_state_path="/tmp/nonexistent_plugin_state.json",
|
||||||
# pgrep findet anderen Prozess → True
|
)
|
||||||
assert result is True
|
result = dt.check()
|
||||||
|
# pgrep findet anderen Prozess → True
|
||||||
|
assert result is True
|
||||||
|
|
||||||
def test_plugin_state_corrupt_json_no_crash(self, tmp_path):
|
def test_plugin_state_corrupt_json_no_crash(self, tmp_path):
|
||||||
"""Korrupte Plugin-State-Datei → kein Crash, graceful fallback."""
|
"""Korrupte Plugin-State-Datei → kein Crash, graceful fallback."""
|
||||||
@@ -2140,12 +2155,14 @@ class TestDetectionTimerPluginState:
|
|||||||
stderr="",
|
stderr="",
|
||||||
returncode=0,
|
returncode=0,
|
||||||
)
|
)
|
||||||
dt = DetectionTimer(
|
# P2: PID-Sentinel deaktivieren, damit pgrep getestet wird
|
||||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||||
detection_interval=0.1,
|
dt = DetectionTimer(
|
||||||
plugin_state_path=state_path,
|
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||||
)
|
detection_interval=0.1,
|
||||||
result = dt.check()
|
plugin_state_path=state_path,
|
||||||
|
)
|
||||||
|
result = dt.check()
|
||||||
# Sollte nicht crashen, pgrep findet anderen Prozess → True
|
# Sollte nicht crashen, pgrep findet anderen Prozess → True
|
||||||
assert result is True
|
assert result is True
|
||||||
|
|
||||||
@@ -2154,7 +2171,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 (>1 → PRIMARY entscheidet)
|
# gateway_state mit active_agents=3 (>0 → SECONDARY 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)
|
||||||
@@ -2172,15 +2189,17 @@ class TestDetectionTimerPluginState:
|
|||||||
})
|
})
|
||||||
|
|
||||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||||
dt = DetectionTimer(
|
# P2: PID-Sentinel deaktivieren, damit gateway_state getestet wird
|
||||||
gateway_state_path=gw_path,
|
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||||
detection_interval=0.1,
|
dt = DetectionTimer(
|
||||||
plugin_state_path=plugin_path,
|
gateway_state_path=gw_path,
|
||||||
)
|
detection_interval=0.1,
|
||||||
result = dt.check()
|
plugin_state_path=plugin_path,
|
||||||
# gateway_state=3 > 1 → PRIMARY → True (pgrep NICHT aufgerufen)
|
)
|
||||||
assert result is True
|
result = dt.check()
|
||||||
mock_run.assert_not_called()
|
# gateway_state=3 > 0 → SECONDARY → True (pgrep NICHT aufgerufen)
|
||||||
|
assert result is True
|
||||||
|
mock_run.assert_not_called()
|
||||||
finally:
|
finally:
|
||||||
os.unlink(gw_path)
|
os.unlink(gw_path)
|
||||||
|
|
||||||
@@ -2210,12 +2229,14 @@ class TestDetectionSourceTelemetry:
|
|||||||
"schema_version": 1,
|
"schema_version": 1,
|
||||||
})
|
})
|
||||||
|
|
||||||
dt = DetectionTimer(
|
# P2: PID-Sentinel deaktivieren, damit plugin_state getestet wird
|
||||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||||
detection_interval=0.1,
|
dt = DetectionTimer(
|
||||||
plugin_state_path=state_path,
|
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||||
)
|
detection_interval=0.1,
|
||||||
dt.check()
|
plugin_state_path=state_path,
|
||||||
|
)
|
||||||
|
dt.check()
|
||||||
assert routing_telemetry.heartbeat_detection_source == "plugin_state"
|
assert routing_telemetry.heartbeat_detection_source == "plugin_state"
|
||||||
|
|
||||||
def test_detection_source_none_when_inactive(self):
|
def test_detection_source_none_when_inactive(self):
|
||||||
@@ -2232,13 +2253,15 @@ class TestDetectionSourceTelemetry:
|
|||||||
stderr="",
|
stderr="",
|
||||||
returncode=0,
|
returncode=0,
|
||||||
)
|
)
|
||||||
dt = DetectionTimer(
|
# P2: PID-Sentinel deaktivieren, damit pgrep getestet wird
|
||||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||||
detection_interval=0.1,
|
dt = DetectionTimer(
|
||||||
plugin_state_path="/tmp/nonexistent_plugin_state.json",
|
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||||
)
|
detection_interval=0.1,
|
||||||
dt.check()
|
plugin_state_path="/tmp/nonexistent_plugin_state.json",
|
||||||
assert routing_telemetry.heartbeat_detection_source == "none"
|
)
|
||||||
|
dt.check()
|
||||||
|
assert routing_telemetry.heartbeat_detection_source == "none"
|
||||||
|
|
||||||
def test_detection_source_pgrep(self):
|
def test_detection_source_pgrep(self):
|
||||||
"""pgrep findet Agenten → source='pgrep'."""
|
"""pgrep findet Agenten → source='pgrep'."""
|
||||||
@@ -2254,13 +2277,15 @@ class TestDetectionSourceTelemetry:
|
|||||||
stderr="",
|
stderr="",
|
||||||
returncode=0,
|
returncode=0,
|
||||||
)
|
)
|
||||||
dt = DetectionTimer(
|
# P2: PID-Sentinel deaktivieren, damit pgrep getestet wird
|
||||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||||
detection_interval=0.1,
|
dt = DetectionTimer(
|
||||||
plugin_state_path="/tmp/nonexistent_plugin_state.json",
|
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||||
)
|
detection_interval=0.1,
|
||||||
dt.check()
|
plugin_state_path="/tmp/nonexistent_plugin_state.json",
|
||||||
assert routing_telemetry.heartbeat_detection_source == "pgrep"
|
)
|
||||||
|
dt.check()
|
||||||
|
assert routing_telemetry.heartbeat_detection_source == "pgrep"
|
||||||
|
|
||||||
def test_detection_source_gateway(self, tmp_path):
|
def test_detection_source_gateway(self, tmp_path):
|
||||||
"""gateway_state entscheidet → source='gateway'."""
|
"""gateway_state entscheidet → source='gateway'."""
|
||||||
@@ -2277,13 +2302,15 @@ 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:
|
||||||
dt = DetectionTimer(
|
# P2: PID-Sentinel deaktivieren, damit gateway_state getestet wird
|
||||||
gateway_state_path=gw_path,
|
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||||
detection_interval=0.1,
|
dt = DetectionTimer(
|
||||||
)
|
gateway_state_path=gw_path,
|
||||||
dt.check()
|
detection_interval=0.1,
|
||||||
assert routing_telemetry.heartbeat_detection_source == "gateway"
|
)
|
||||||
mock_run.assert_not_called()
|
dt.check()
|
||||||
|
assert routing_telemetry.heartbeat_detection_source == "gateway"
|
||||||
|
mock_run.assert_not_called()
|
||||||
finally:
|
finally:
|
||||||
os.unlink(gw_path)
|
os.unlink(gw_path)
|
||||||
|
|
||||||
@@ -2308,3 +2335,233 @@ 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}'"
|
||||||
|
)
|
||||||
|
|||||||
@@ -0,0 +1,466 @@
|
|||||||
|
"""
|
||||||
|
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,6 +836,8 @@ 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")
|
||||||
@@ -956,6 +958,8 @@ 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")
|
||||||
|
|||||||
@@ -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: 30 calls/minute (was 60 — RC triggers 429 at 3-4 calls in <10s).
|
Default: 15 calls/minute (was 30 — RC triggers 429 aggressively).
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, max_tokens: int = 30, window_seconds: float = 60.0):
|
def __init__(self, max_tokens: int = 15, 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=30, window_seconds=60.0)
|
_rate_limiter = RateLimiter(max_tokens=15, window_seconds=60.0)
|
||||||
return _rate_limiter
|
return _rate_limiter
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -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: 2s -> 3s -> 5s -> 8s (max 18s total).
|
# Default: 5s -> 8s -> 12s -> 20s (max 45s total).
|
||||||
# Callers can override the first interval via initial_interval.
|
# Callers can override the first interval via initial_interval.
|
||||||
_DEFAULT_BACKOFF_INTERVALS = [2.0, 3.0, 5.0, 8.0]
|
_DEFAULT_BACKOFF_INTERVALS = [5.0, 8.0, 12.0, 20.0]
|
||||||
_MAX_TOTAL_WAIT = 18.0 # seconds
|
_MAX_TOTAL_WAIT = 45.0 # seconds
|
||||||
|
|
||||||
# 429 exponential backoff: 3s -> 6s -> 12s -> 20s -> 30s (max)
|
# 429 exponential backoff: 5s -> 10s -> 20s -> 40s (max)
|
||||||
_MAX_429_BACKOFF = 30.0
|
_MAX_429_BACKOFF = 40.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, 3.0, 5.0, 8.0]
|
backoff_intervals = [initial_interval, 8.0, 12.0, 20.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: 3s -> 6s -> 12s -> 20s -> 30s
|
# Exponential backoff on rate-limit errors: 5s -> 10s -> 20s -> 40s
|
||||||
backoff = min(3.0 * (2 ** (consecutive_429 - 1)), _MAX_429_BACKOFF)
|
backoff = min(5.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 -> 3s -> 5s -> 8s
|
# Progressive backoff: initial_interval -> 8s -> 12s -> 20s
|
||||||
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 = 8.0
|
delay = 20.0
|
||||||
|
|
||||||
remaining = deadline - time.monotonic()
|
remaining = deadline - time.monotonic()
|
||||||
if remaining <= 0:
|
if remaining <= 0:
|
||||||
|
|||||||
@@ -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: 3s → 6s → 12s → 20s → 30s (max 5 retries)
|
# 429 retry with exponential backoff: 5s → 10s → 20s → 40s (max 4 retries)
|
||||||
# Total possible wait: 71s — gives RC enough time to reset its rate-limit window.
|
# Total possible wait: 75s — gives RC enough time to reset its rate-limit window.
|
||||||
_429_BACKOFFS = [3.0, 6.0, 12.0, 20.0, 30.0]
|
_429_BACKOFFS = [5.0, 10.0, 20.0, 40.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.)
|
||||||
|
|||||||
Reference in New Issue
Block a user