Compare commits
14 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e9027d6681 | |||
| a8d920736d | |||
| 309b0ddc85 | |||
| b5fa6e22f5 | |||
| 7f2b57b436 | |||
| 73638fd565 | |||
| 2a7fade341 | |||
| 2ef44fec9c | |||
| 5d59024522 | |||
| d6674a3dd2 | |||
| 8fba9a4a39 | |||
| 0310bd5fd5 | |||
| 9f3cc02148 | |||
| 6aaadcdb88 |
@@ -0,0 +1,58 @@
|
||||
# Contributing to Hermes Rocket.Chat Plugin
|
||||
|
||||
## Commit-Message-Convention
|
||||
|
||||
Alle Commits folgen dem Conventional-Commits-Format mit einem
|
||||
**Production-Impact-Footer**.
|
||||
|
||||
### Format
|
||||
|
||||
```
|
||||
<type>(<scope>): <kurze Beschreibung>
|
||||
|
||||
<ausführliche Beschreibung>
|
||||
|
||||
Production-Impact: <none|low|medium|high|critical>
|
||||
```
|
||||
|
||||
### Types
|
||||
|
||||
- `feat`: Neue Funktionalität
|
||||
- `fix`: Bugfix
|
||||
- `docs`: Dokumentation
|
||||
- `refactor`: Code-Umbau ohne Funktionsänderung
|
||||
- `test`: Tests
|
||||
- `chore`: Build/Tooling
|
||||
|
||||
### Scopes
|
||||
|
||||
- `adapter`: Gateway-Adapter (REST, DDP, WebSocket)
|
||||
- `presence`: PresenceEngine, PulseController, DetectionTimer
|
||||
- `archivar`: Archivar-Logik (Routing, Room-Map, History)
|
||||
- `gateway`: Gateway-Integration
|
||||
|
||||
### Production-Impact-Footer
|
||||
|
||||
Jeder Commit MUSS einen `Production-Impact`-Footer haben:
|
||||
|
||||
| Level | Bedeutung |
|
||||
|----------|-----------|
|
||||
| `none` | Kein Einfluss auf Produktion (Doku, Tests, Chores) |
|
||||
| `low` | Kosmetische Änderung, kein Verhaltenswechsel |
|
||||
| `medium` | Verhaltensänderung mit geringem Risiko |
|
||||
| `high` | Signifikante Verhaltensänderung (Circuit-Breaker, Rate-Limiting) |
|
||||
| `critical` | Hotfix für Produktionsausfall |
|
||||
|
||||
### Beispiele
|
||||
|
||||
```
|
||||
feat(adapter): http_timeout als konfigurierbarer Parameter
|
||||
|
||||
Production-Impact: none
|
||||
```
|
||||
|
||||
```
|
||||
fix(P1): users.setStatus 429 Circuit-Breaker — verhindert Gateway-Hang
|
||||
|
||||
Production-Impact: HIGH — verhindert Gateway-Hang durch 429-Endlosschleife
|
||||
```
|
||||
+162
-35
@@ -51,6 +51,13 @@ _CURRENT_TASK_TOKEN: contextvars.ContextVar[str] = contextvars.ContextVar(
|
||||
"_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:
|
||||
"""Atomar _room_context[chat_id]["origin_room"] = room_id setzen.
|
||||
@@ -259,20 +266,22 @@ def _sanitize_file_path_component(value: str) -> str:
|
||||
|
||||
|
||||
class RocketChatREST:
|
||||
def __init__(self, base_url: str):
|
||||
def __init__(self, base_url: str, http_timeout: float = 30.0):
|
||||
self.base_url = base_url.rstrip("/")
|
||||
self.http_timeout = http_timeout
|
||||
self.auth_token: Optional[str] = None
|
||||
self.user_id: Optional[str] = None
|
||||
|
||||
def _request(self, method: str, endpoint: str, headers: Optional[dict] = None, data: Optional[dict] = None):
|
||||
def _request(self, method: str, endpoint: str, headers: Optional[dict] = None, data: Optional[dict] = None, timeout: Optional[float] = None):
|
||||
url = f"{self.base_url}{endpoint}"
|
||||
req_headers = dict(headers) if headers else {}
|
||||
body = json.dumps(data).encode("utf-8") if data else None
|
||||
if body:
|
||||
req_headers["Content-Type"] = "application/json"
|
||||
req = urllib.request.Request(url, data=body, headers=req_headers, method=method)
|
||||
_timeout = timeout if timeout is not None else self.http_timeout
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
with urllib.request.urlopen(req, timeout=_timeout) as resp:
|
||||
return json.loads(resp.read().decode("utf-8"))
|
||||
except urllib.error.HTTPError as e:
|
||||
if e.code == 429:
|
||||
@@ -1177,7 +1186,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
self._multiroom_context = None
|
||||
# P5 V9.x: OutboundGate — Parallel-Stream-Schutz
|
||||
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:
|
||||
self.archivar.bind_outbound_gate(self._outbound_gate)
|
||||
# User-Flow C: Move-Requests
|
||||
@@ -1242,6 +1251,18 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
)
|
||||
self._presence_engine = None # Graceful degradation -> alter Idle-Timer greift
|
||||
|
||||
# Phase 5: SubagentTracker — Subagent-Status für PresenceEngine
|
||||
try:
|
||||
from archivar.subagent_tracker import get_tracker
|
||||
self._subagent_tracker = get_tracker()
|
||||
logger.info("[rocketchat] Phase 5: SubagentTracker initialisiert")
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
"[rocketchat] Phase 5: SubagentTracker-Initialisierung FEHLGESCHLAGEN: %s",
|
||||
e,
|
||||
)
|
||||
self._subagent_tracker = None # Graceful degradation
|
||||
|
||||
def _build_room_map_summary(self) -> str:
|
||||
"""Baut eine menschenlesbare Raum-Map-Übersicht für den System-Prompt.
|
||||
|
||||
@@ -2215,6 +2236,14 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
self._presence_engine.increment_background_tasks()
|
||||
logger.info("[presence] mark_busy_started (room=%s)", room_name)
|
||||
|
||||
# Phase 5: SubagentTracker — register background task for subagent_status.json
|
||||
_has_tracker = hasattr(self, '_subagent_tracker') and self._subagent_tracker is not None
|
||||
if _has_tracker:
|
||||
try:
|
||||
self._subagent_tracker.register("background_task", room_name=room_name)
|
||||
except Exception as e:
|
||||
logger.debug("[subagent_tracker] register failed (non-critical): %s", e)
|
||||
|
||||
try:
|
||||
# ── R5: Inline-Command-Erkennung (VOR Onboarding + Hermes-Dispatch) ──
|
||||
# ::-Befehle und natürliche Hilfeseiten-Anfragen müssen VOR dem
|
||||
@@ -3548,13 +3577,24 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
finally:
|
||||
# ── V8.6 P1a: PresenceEngine — mark_busy_done (Honeymoon-Timer) ──
|
||||
# try/finally garantiert decrement auch bei Exceptions/Errors.
|
||||
# Phase 5: Reihenfolge getauscht — decrement_background_tasks VOR
|
||||
# mark_busy_done, damit mark_busy_done den aktuellen background_tasks
|
||||
# Stand sieht und entscheiden kann ob Subagent-Pulse nötig ist.
|
||||
if _has_presence:
|
||||
self._presence_engine.mark_busy_done()
|
||||
# B12: Background-Tasks decrement — Heartbeat-Message aktualisieren
|
||||
self._presence_engine.decrement_background_tasks()
|
||||
# P1a: mark_busy_done prüft jetzt intern background_tasks > 0
|
||||
self._presence_engine.mark_busy_done()
|
||||
# P1-2: current_room zurücksetzen nach Verarbeitung
|
||||
self._presence_engine.set_current_room("")
|
||||
logger.info("[presence] mark_busy_done (turn complete)")
|
||||
|
||||
# Phase 5: SubagentTracker — complete background task (symmetrisch zu register)
|
||||
if _has_tracker:
|
||||
try:
|
||||
self._subagent_tracker.complete("background_task")
|
||||
except Exception as e:
|
||||
logger.debug("[subagent_tracker] complete failed (non-critical): %s", e)
|
||||
# ── P5 V9.x: OutboundGate — release (symmetrisch zu mark_busy_done) ──
|
||||
# W2: release in try/except BaseException im finally-Block.
|
||||
try:
|
||||
@@ -4703,6 +4743,11 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
# _CURRENT_TASK_TOKEN. copy_context() friert es ein, sodass send()
|
||||
# später den Token-Match validieren kann.
|
||||
_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 ──────────
|
||||
ctx = contextvars.copy_context()
|
||||
# V8.1 P1 diagnostic: log dispatch context
|
||||
@@ -6537,6 +6582,53 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
self.ddp = None
|
||||
logger.info("[rocketchat] Disconnected")
|
||||
|
||||
# ── P1: Quick-Reply Dedup Helper ──────────────────────────────────
|
||||
# Zentraler Helper für Quick-Reply — verhindert 3x-Senden durch
|
||||
# Dedup-Flag im _TurnHandle und kontextabhängigen Text (same-room
|
||||
# vs cross-room).
|
||||
|
||||
async def _maybe_send_quick_reply(
|
||||
self, gate_room_id: str, active_room_id: Optional[str], active_room_name: str
|
||||
) -> Optional[SendResult]:
|
||||
"""Sendet Quick-Reply wenn noch keiner für diesen Raum gesendet wurde.
|
||||
|
||||
Dedup: quick_reply_already_sent prüft das Flag im _TurnHandle.
|
||||
Kontextabhängiger Text:
|
||||
- Same-Raum (active_room_id == gate_room_id): kein Raum-Name
|
||||
- Cross-Raum mit Name: „Ich antworte gerade in #RaumX — …"
|
||||
- Cross-Raum ohne Name: generischer Fallback
|
||||
|
||||
Returns:
|
||||
SendResult wenn Quick-Reply gesendet wurde, None wenn bereits
|
||||
gesendet (Dedup).
|
||||
"""
|
||||
if self._outbound_gate.quick_reply_already_sent(gate_room_id):
|
||||
return None
|
||||
|
||||
# Kontextabhängiger Text
|
||||
same_room = (active_room_id is not None and active_room_id == gate_room_id)
|
||||
if same_room:
|
||||
text = "Ich bin gerade beschäftigt — einen Moment bitte, ich bin gleich bei dir."
|
||||
elif active_room_name:
|
||||
text = (
|
||||
f"Ich antworte gerade in #{active_room_name} — "
|
||||
f"einen Moment bitte, ich bin gleich bei dir."
|
||||
)
|
||||
else:
|
||||
text = (
|
||||
"Ich antworte gerade in einem anderen Raum — "
|
||||
"einen Moment bitte, ich bin gleich bei dir."
|
||||
)
|
||||
|
||||
await self._post_message_unlocked(gate_room_id, text)
|
||||
self._outbound_gate.mark_quick_reply_sent(gate_room_id)
|
||||
self._outbound_gate.stats.quick_reply += 1
|
||||
logger.info(
|
||||
"[rocketchat] P5 V9.x: Quick-Reply sent to room=%s (blocked by %s)",
|
||||
gate_room_id[:8], active_room_name or "unknown",
|
||||
)
|
||||
return SendResult(success=True, message_id="quick_reply")
|
||||
|
||||
async def send(self, chat_id: str, content: str, reply_to: Optional[str] = None,
|
||||
metadata: Optional[Dict[str, Any]] = None) -> SendResult:
|
||||
if not self.rest.auth_token:
|
||||
@@ -6612,7 +6704,8 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
_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:
|
||||
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:
|
||||
# Blockiert — warte bis zu 30s (A4: blocking_room_id)
|
||||
blocking_room = decision.blocking_room_id
|
||||
@@ -6622,30 +6715,23 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
blocking_room_id=blocking_room, timeout_s=30.0
|
||||
)
|
||||
# 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:
|
||||
decision = GateDecision(allow=False, reason="timeout")
|
||||
|
||||
if not decision.allow:
|
||||
# Quick-Reply: anderer Raum blockiert immer noch
|
||||
# Quick-Reply via zentralem Helper (Dedup + kontextabhängiger Text)
|
||||
active_room = self._outbound_gate.active_room_id
|
||||
active_name = ""
|
||||
if active_room and active_room in self._room_info:
|
||||
active_name = self._room_info[active_room].get("name", active_room[:12] + "…")
|
||||
quick_reply_text = (
|
||||
f"Ich antworte gerade in #{active_name} — "
|
||||
f"einen Moment bitte, ich bin gleich bei dir."
|
||||
) if active_name else (
|
||||
"Ich antworte gerade in einem anderen Raum — "
|
||||
"einen Moment bitte, ich bin gleich bei dir."
|
||||
qr_result = await self._maybe_send_quick_reply(
|
||||
_gate_room_id, active_room, active_name
|
||||
)
|
||||
await self._post_message_unlocked(_gate_room_id, quick_reply_text)
|
||||
self._outbound_gate.stats.quick_reply += 1
|
||||
logger.info(
|
||||
"[rocketchat] P5 V9.x: Quick-Reply sent to room=%s (blocked by %s)",
|
||||
_gate_room_id[:8], active_name,
|
||||
)
|
||||
return SendResult(success=True, message_id="quick_reply")
|
||||
if qr_result is not None:
|
||||
return qr_result
|
||||
# Dedup: Quick-Reply bereits gesendet → trotzdem return
|
||||
return SendResult(success=True, message_id="quick_reply_dedup")
|
||||
# Fell through: decision.allow is True — track if WE created the entry
|
||||
# (gate_clear = we own it; same_room_same_token = someone else owns it)
|
||||
_gate_acquired = (decision.reason == "gate_clear")
|
||||
@@ -6708,6 +6794,27 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
real_room_id = thematic_target
|
||||
logger.debug("[rocketchat] send via Archivar target: %s → %s", chat_id, real_room_id)
|
||||
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
|
||||
rooms = self._user_rooms.get(chat_id, [])
|
||||
if rooms:
|
||||
@@ -7071,7 +7178,8 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
_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:
|
||||
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:
|
||||
blocking_room = decision.blocking_room_id
|
||||
if blocking_room:
|
||||
@@ -7079,24 +7187,22 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
await self._outbound_gate.wait_until_clear(
|
||||
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:
|
||||
decision = GateDecision(allow=False, reason="timeout")
|
||||
if not decision.allow:
|
||||
# Quick-Reply via zentralem Helper (Dedup + kontextabhängiger Text)
|
||||
active_room = self._outbound_gate.active_room_id
|
||||
active_name = ""
|
||||
if active_room and active_room in self._room_info:
|
||||
active_name = self._room_info[active_room].get("name", active_room[:12] + "…")
|
||||
quick_reply_text = (
|
||||
f"Ich antworte gerade in #{active_name} — "
|
||||
f"einen Moment bitte, ich bin gleich bei dir."
|
||||
) if active_name else (
|
||||
"Ich antworte gerade in einem anderen Raum — "
|
||||
"einen Moment bitte, ich bin gleich bei dir."
|
||||
qr_result = await self._maybe_send_quick_reply(
|
||||
_gate_room_id, active_room, active_name
|
||||
)
|
||||
await self._post_message_unlocked(_gate_room_id, quick_reply_text)
|
||||
self._outbound_gate.stats.quick_reply += 1
|
||||
return SendResult(success=True, message_id="quick_reply")
|
||||
if qr_result is not None:
|
||||
return qr_result
|
||||
# Dedup: Quick-Reply bereits gesendet → trotzdem return
|
||||
return SendResult(success=True, message_id="quick_reply_dedup")
|
||||
# Fell through: decision.allow is True — track if WE created the entry
|
||||
# (gate_clear = we own it; same_room_same_token = someone else owns it)
|
||||
_gate_acquired = (decision.reason == "gate_clear")
|
||||
@@ -7152,6 +7258,27 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
real_room_id = thematic_target
|
||||
logger.debug("[rocketchat] send_clarify via Archivar target: %s → %s", chat_id, real_room_id)
|
||||
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
|
||||
rooms = self._user_rooms.get(chat_id, [])
|
||||
if rooms:
|
||||
@@ -7319,12 +7446,12 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
"""P5 V9.x W2: Periodischer Sweep stale Gate-Einträge.
|
||||
|
||||
Läuft als asyncio.create_task (nicht threading.Timer).
|
||||
Sweept alle 30s — entfernt Einträge die älter als
|
||||
max_entry_age_s (60s) sind.
|
||||
B+: Sweept alle 5s (war 30s) — entfernt Einträge die älter als
|
||||
max_entry_age_s (10s, war 60s) sind.
|
||||
"""
|
||||
while self._running and not self._shutdown_event.is_set():
|
||||
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:
|
||||
swept = self._outbound_gate._sweep_stale_entries()
|
||||
if swept > 0:
|
||||
|
||||
@@ -51,6 +51,8 @@ class _TurnHandle:
|
||||
real_room_id: Rocket.Chat Raum-ID.
|
||||
task: asyncio.Task Referenz (für Cancel/Diagnose).
|
||||
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
|
||||
@@ -58,6 +60,8 @@ class _TurnHandle:
|
||||
real_room_id: str
|
||||
task: Optional[asyncio.Task] = None
|
||||
chat_id: str = ""
|
||||
quick_reply_sent: bool = False
|
||||
owner_session_id: str = "" # B1: Session-ID für release()-Fallback
|
||||
|
||||
|
||||
# ── GateStats: 9 Counter für Monitoring ───────────────────────────────────
|
||||
@@ -122,18 +126,20 @@ class OutboundGate:
|
||||
def __init__(
|
||||
self,
|
||||
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.
|
||||
|
||||
Args:
|
||||
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._lock = asyncio.Lock()
|
||||
# A4: Per-Raum Dict statt flat List — kein False-Wake-Bug
|
||||
self._waiters: Dict[str, List[asyncio.Event]] = {}
|
||||
# P1: Quick-Reply Dedup — separates Tracking fuer Trigger-Raeume
|
||||
self._quick_reply_sent: Dict[str, bool] = {}
|
||||
self.default_timeout_s = default_timeout_s
|
||||
self.max_entry_age_s = max_entry_age_s
|
||||
self.stats = GateStats()
|
||||
@@ -147,7 +153,7 @@ class OutboundGate:
|
||||
return next(iter(self._in_flight))
|
||||
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.
|
||||
|
||||
ASYNC — verwendet asyncio.Lock für Thread-Safety.
|
||||
@@ -163,6 +169,8 @@ class OutboundGate:
|
||||
Args:
|
||||
room_id: Rocket.Chat Raum-ID.
|
||||
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:
|
||||
GateDecision mit allow, reason, blocking_room_id.
|
||||
@@ -215,6 +223,7 @@ class OutboundGate:
|
||||
task_token=task_token,
|
||||
started_at=time.monotonic(),
|
||||
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.stats.acquired_total += 1
|
||||
@@ -227,6 +236,39 @@ class OutboundGate:
|
||||
reason="gate_clear",
|
||||
)
|
||||
|
||||
# ── Quick-Reply Dedup (P1) ──────────────────────────────────────────
|
||||
# Separates Tracking-Dict unabhaengig von _in_flight:
|
||||
# Quick-Reply wird fuer den TRIGGER-Raum gesendet, der NICHT in
|
||||
# _in_flight ist (dort ist nur der aktive/beschaeftigte Raum).
|
||||
|
||||
def mark_quick_reply_sent(self, room_id: str) -> bool:
|
||||
"""Markiert dass ein Quick-Reply fuer diesen Raum gesendet wurde.
|
||||
|
||||
Idempotent: returns True beim ersten Aufruf (Quick-Reply wurde
|
||||
tatsaechlich gesendet), False bei allen weiteren Aufrufen.
|
||||
|
||||
Args:
|
||||
room_id: Rocket.Chat Raum-ID (der Trigger-Raum, nicht der aktive).
|
||||
|
||||
Returns:
|
||||
True wenn dies das erste Markieren war, False wenn bereits markiert.
|
||||
"""
|
||||
if room_id not in self._quick_reply_sent:
|
||||
self._quick_reply_sent[room_id] = True
|
||||
return True
|
||||
return False
|
||||
|
||||
def quick_reply_already_sent(self, room_id: str) -> bool:
|
||||
"""Prueft ob bereits ein Quick-Reply fuer diesen Raum gesendet wurde.
|
||||
|
||||
Args:
|
||||
room_id: Rocket.Chat Raum-ID.
|
||||
|
||||
Returns:
|
||||
True wenn bereits ein Quick-Reply gesendet wurde.
|
||||
"""
|
||||
return room_id in self._quick_reply_sent
|
||||
|
||||
# ── release (idempotent) ──────────────────────────────────────────────
|
||||
|
||||
def release(self, room_id: str, task_token: str) -> None:
|
||||
@@ -234,13 +276,17 @@ class OutboundGate:
|
||||
|
||||
Idempotent: kein Fehler wenn der Raum nicht in _in_flight ist.
|
||||
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])
|
||||
damit blockierte Streams ihren wait_until_clear auflösen können.
|
||||
|
||||
Args:
|
||||
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:
|
||||
logger.debug(
|
||||
@@ -251,12 +297,22 @@ class OutboundGate:
|
||||
|
||||
existing = self._in_flight[room_id]
|
||||
if existing.task_token != task_token:
|
||||
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
|
||||
# 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(
|
||||
"[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]
|
||||
self.stats.released_total += 1
|
||||
|
||||
@@ -349,6 +349,9 @@ class PresenceEngine:
|
||||
If the honeymoon hasn't elapsed yet, the timer callback will
|
||||
handle the transition when it fires.
|
||||
|
||||
Phase 5: Wenn background_tasks > 0, NICHT auf online gehen.
|
||||
Stattdessen _update_presence_with_subagents() aufrufen.
|
||||
|
||||
Must be called in a finally block to ensure counter balance
|
||||
even on exceptions.
|
||||
"""
|
||||
@@ -363,11 +366,12 @@ class PresenceEngine:
|
||||
if counter == 0:
|
||||
elapsed = time.monotonic() - self._busy_started_at
|
||||
if elapsed >= self.MIN_BUSY_VISIBLE_S:
|
||||
# Honeymoon already elapsed — transition to online now
|
||||
# Honeymoon already elapsed — transition now
|
||||
self._cancel_honeymoon_timer()
|
||||
self.update_presence()
|
||||
# Phase 5: Check background_tasks before going online
|
||||
self._transition_from_busy()
|
||||
logger.debug(
|
||||
"[presence] Honeymoon abgelaufen (%.2fs) → online", elapsed,
|
||||
"[presence] Honeymoon abgelaufen (%.2fs) → transition", elapsed,
|
||||
)
|
||||
else:
|
||||
# Honeymoon still running — timer callback will handle it
|
||||
@@ -380,6 +384,81 @@ class PresenceEngine:
|
||||
"[presence] mark_busy_done: counter=%d (weitere Tasks aktiv)", counter,
|
||||
)
|
||||
|
||||
def _transition_from_busy(self) -> None:
|
||||
"""Phase 5: Transition from busy — check subagents before going online.
|
||||
|
||||
Called when mark_busy_done or _honeymoon_expired would normally
|
||||
transition to online. If background_tasks > 0 or subagent_status.json
|
||||
has active entries, start/keep PulseController instead.
|
||||
"""
|
||||
with self._background_tasks_lock:
|
||||
bg = self._background_tasks
|
||||
|
||||
# Phase 5: Auch subagent_status.json prüfen
|
||||
subagent_count = self._read_subagent_count()
|
||||
|
||||
if bg > 0 or subagent_count > 0:
|
||||
# Subagenten laufen noch — Pulse-Modus statt online
|
||||
self._update_presence_with_subagents(max(bg, subagent_count))
|
||||
else:
|
||||
# Keine Subagenten — klassischer Pfad: online
|
||||
self.update_presence()
|
||||
|
||||
def _read_subagent_count(self) -> int:
|
||||
"""Phase 5: Read active subagent count from subagent_status.json.
|
||||
|
||||
Returns:
|
||||
Number of active subagent entries, or 0 on any error.
|
||||
"""
|
||||
try:
|
||||
from archivar.subagent_tracker import _read_subagent_state, _get_subagent_state_path
|
||||
state = _read_subagent_state(_get_subagent_state_path())
|
||||
return len(state.get("active", []))
|
||||
except Exception:
|
||||
return 0
|
||||
|
||||
def _update_presence_with_subagents(self, subagent_count: int) -> None:
|
||||
"""Phase 5: Set presence when subagents are active.
|
||||
|
||||
Two modes:
|
||||
1. Hauptagent busy (_active_tasks > 0): Status bleibt "busy",
|
||||
Message = "Verarbeitet in X (N Subagent)"
|
||||
2. Hauptagent idle (_active_tasks == 0): PulseController mit
|
||||
pulse_target="away", Message = "N Subagent läuft"
|
||||
|
||||
Args:
|
||||
subagent_count: Number of active subagents.
|
||||
"""
|
||||
with self._active_tasks_lock:
|
||||
active = self._active_tasks
|
||||
|
||||
if active > 0:
|
||||
# Hauptagent busy + Subagenten → busy mit erweiterter Message
|
||||
msg = f"Verarbeitet in {self._current_room_name} ({subagent_count} Subagent)" if self._current_room_name else f"Verarbeitet ({subagent_count} Subagent)"
|
||||
self._set_presence("busy", msg)
|
||||
# PulseController im busy-Modus halten für Message-Pulse
|
||||
if not self._pulse_controller.is_running():
|
||||
self._pulse_controller.set_pulse_target("busy")
|
||||
self._pulse_controller.start()
|
||||
else:
|
||||
self._pulse_controller.set_pulse_target("busy")
|
||||
logger.info(
|
||||
"[presence] Subagent-Pulse: busy+%d subagents (active_tasks=%d)",
|
||||
subagent_count, active,
|
||||
)
|
||||
else:
|
||||
# Hauptagent idle + Subagenten → Pulse online↔away
|
||||
msg = f"{subagent_count} Subagent läuft"
|
||||
self._pulse_controller.set_pulse_target("away")
|
||||
if not self._pulse_controller.is_running():
|
||||
self._pulse_controller.start()
|
||||
# Set initial status to away (Pulse toggles from here)
|
||||
self._set_presence("away", msg)
|
||||
logger.info(
|
||||
"[presence] Subagent-Pulse: idle+%d subagents → away-pulse",
|
||||
subagent_count,
|
||||
)
|
||||
|
||||
def _honeymoon_expired(self) -> None:
|
||||
"""P1a: Honeymoon timer callback — transition to online if idle.
|
||||
|
||||
@@ -387,6 +466,9 @@ class PresenceEngine:
|
||||
If no active tasks remain, sets status to online.
|
||||
B3: Checks pending_status under _active_tasks_lock to prevent
|
||||
race with mark_busy_started.
|
||||
|
||||
Phase 5: Nutzt _transition_from_busy() statt direkt update_presence(),
|
||||
damit Subagent-Check auch im Honeymoon-Pfad greift.
|
||||
"""
|
||||
with self._busy_honeymoon_lock:
|
||||
self._busy_honeymoon_timer = None
|
||||
@@ -410,9 +492,10 @@ class PresenceEngine:
|
||||
# and no active tasks remain — next busy cycle starts fresh.
|
||||
self._busy_started_at = 0.0
|
||||
logger.info(
|
||||
"[presence] Honeymoon-Timer abgelaufen, active_tasks=0 → online"
|
||||
"[presence] Honeymoon-Timer abgelaufen, active_tasks=0 → transition"
|
||||
)
|
||||
self.update_presence()
|
||||
# Phase 5: _transition_from_busy prüft subagent_status.json
|
||||
self._transition_from_busy()
|
||||
else:
|
||||
logger.debug(
|
||||
"[presence] Honeymoon-Timer abgelaufen, aber active_tasks=%d — kein Wechsel",
|
||||
@@ -482,6 +565,9 @@ class PresenceEngine:
|
||||
_background_tasks_lock aufgerufen, sodass kein veralteter Count
|
||||
persistiert werden kann (Race zwischen zwei konkurrierenden Threads).
|
||||
|
||||
Phase 5: stop()-Aufruf entfernt. PulseController wird jetzt von
|
||||
_update_presence_with_subagents() gesteuert, nicht vom Counter.
|
||||
|
||||
Returns:
|
||||
New counter value.
|
||||
"""
|
||||
@@ -490,8 +576,8 @@ class PresenceEngine:
|
||||
self._background_tasks -= 1
|
||||
count = self._background_tasks
|
||||
self._pulse_controller.set_background_count(count)
|
||||
if count == 0:
|
||||
self._pulse_controller.stop()
|
||||
# Phase 5: stop() NICHT hier — _update_presence_with_subagents()
|
||||
# entscheidet basierend auf subagent_status.json + background_tasks
|
||||
self._persist_plugin_state(count)
|
||||
return count
|
||||
|
||||
@@ -746,6 +832,25 @@ class PulseController:
|
||||
self._loop: Optional[asyncio.AbstractEventLoop] = None
|
||||
self._await_timeout: float = 2.0
|
||||
|
||||
# Phase 5: pulse_target — "away" (default) oder "busy"
|
||||
# "away": pulsiert online↔away (Subagent läuft, Hauptagent idle)
|
||||
# "busy": pulsiert Message bei busy-Status (Subagent läuft, Hauptagent busy)
|
||||
self._pulse_target: str = "away"
|
||||
self._mode_lock = threading.Lock() # Mode-Sentinel (Risiko #2)
|
||||
self._tick_counter: int = 0 # für Message-only-every-2-ticks
|
||||
|
||||
# P1: Circuit-Breaker — verhindert 429-Endlosschleife im Gateway
|
||||
# States: CLOSED (normal) → OPEN (nach N×429: Pause) → HALF_OPEN (Test-Ping)
|
||||
self._breaker_state: str = "CLOSED"
|
||||
self._consecutive_429s: int = 0
|
||||
self._breaker_opened_at: float = 0.0
|
||||
self._breaker_cooldown_s: float = 30.0
|
||||
self._breaker_429_threshold: int = 3
|
||||
self._base_pulse_interval: float = self._pulse_interval
|
||||
self._backoff_level: int = 0
|
||||
# Adaptive Backoff: pulse_interval wird bei OPEN eskaliert
|
||||
self._backoff_intervals: tuple = (5.0, 15.0, 60.0)
|
||||
|
||||
# ── Public API ───────────────────────────────────────────────────────
|
||||
|
||||
def bind_ddp(self, ddp: object) -> None:
|
||||
@@ -780,6 +885,32 @@ class PulseController:
|
||||
"""Set the background task count for heartbeat messages."""
|
||||
self._background_count = count
|
||||
|
||||
def set_pulse_target(self, target: str) -> bool:
|
||||
"""Phase 5: Set the pulse target mode with Mode-Sentinel.
|
||||
|
||||
Args:
|
||||
target: "away" (pulse online↔away) or "busy" (pulse message while busy).
|
||||
|
||||
Returns:
|
||||
True if mode was changed, False if already in that mode.
|
||||
|
||||
Raises:
|
||||
ValueError: if target is not "away" or "busy".
|
||||
"""
|
||||
if target not in ("away", "busy"):
|
||||
raise ValueError(f"pulse_target must be 'away' or 'busy', got '{target}'")
|
||||
with self._mode_lock:
|
||||
if self._pulse_target == target:
|
||||
return False
|
||||
old = self._pulse_target
|
||||
self._pulse_target = target
|
||||
logger.info("[pulse] pulse_target: %s → %s", old, target)
|
||||
return True
|
||||
|
||||
def get_pulse_target(self) -> str:
|
||||
"""Phase 5: Get the current pulse target mode."""
|
||||
return self._pulse_target
|
||||
|
||||
def start(self) -> None:
|
||||
"""Start the pulse thread."""
|
||||
logger.info(
|
||||
@@ -855,6 +986,121 @@ class PulseController:
|
||||
self._cancel_pending_event.set()
|
||||
logger.debug("[pulse] cancel_pending: next tick will be skipped")
|
||||
|
||||
# ── P1: Circuit-Breaker — 429-Schutz ──────────────────────────────────
|
||||
|
||||
def _classify_ddp_error(self, error: Exception) -> str:
|
||||
"""Classify a DDP error to decide whether it triggers REST fallback.
|
||||
|
||||
'server returned false' is a transient DDP protocol quirk — NOT a
|
||||
real error. It must NOT trigger a REST fallback, because that REST
|
||||
call would itself hit 429 and cascade into the Gateway hang.
|
||||
|
||||
Returns:
|
||||
'429' — rate-limit error (triggers breaker)
|
||||
'ddp_transient' — DDP protocol noise, no fallback
|
||||
'other' — real error, REST fallback allowed
|
||||
"""
|
||||
error_str = str(error).lower()
|
||||
if "429" in error_str or "too many requests" in error_str or "rate limit" in error_str:
|
||||
return "429"
|
||||
if "server returned false" in error_str:
|
||||
return "ddp_transient"
|
||||
return "other"
|
||||
|
||||
def _record_429(self) -> None:
|
||||
"""Record a 429 error and transition breaker state.
|
||||
|
||||
CLOSED + consecutive_429s >= threshold → OPEN (pause + backoff)
|
||||
HALF_OPEN + 429 → OPEN (stay open, escalate backoff)
|
||||
"""
|
||||
self._consecutive_429s += 1
|
||||
logger.warning(
|
||||
"[pulse] Circuit-Breaker: 429 #%d/%d (state=%s)",
|
||||
self._consecutive_429s, self._breaker_429_threshold, self._breaker_state,
|
||||
)
|
||||
|
||||
if self._breaker_state == "CLOSED" and self._consecutive_429s >= self._breaker_429_threshold:
|
||||
self._breaker_state = "OPEN"
|
||||
self._breaker_opened_at = time.monotonic()
|
||||
# Use current backoff_level, THEN increment for next cycle
|
||||
self._pulse_interval = self._backoff_intervals[self._backoff_level]
|
||||
self._backoff_level = min(self._backoff_level + 1, len(self._backoff_intervals) - 1)
|
||||
logger.warning(
|
||||
"[pulse] Circuit-Breaker: CLOSED→OPEN (cooldown=%.0fs, backoff_level=%d, "
|
||||
"pulse_interval=%.1fs)",
|
||||
self._breaker_cooldown_s, self._backoff_level, self._pulse_interval,
|
||||
)
|
||||
elif self._breaker_state == "HALF_OPEN":
|
||||
self._breaker_state = "OPEN"
|
||||
self._breaker_opened_at = time.monotonic()
|
||||
# Use current backoff_level, THEN increment for next cycle
|
||||
self._pulse_interval = self._backoff_intervals[self._backoff_level]
|
||||
self._backoff_level = min(self._backoff_level + 1, len(self._backoff_intervals) - 1)
|
||||
logger.warning(
|
||||
"[pulse] Circuit-Breaker: HALF_OPEN→OPEN (test ping failed, "
|
||||
"backoff_level=%d, pulse_interval=%.1fs)",
|
||||
self._backoff_level, self._pulse_interval,
|
||||
)
|
||||
|
||||
def _record_success(self) -> None:
|
||||
"""Record a successful status set and reset breaker to CLOSED."""
|
||||
if self._breaker_state != "CLOSED":
|
||||
logger.info(
|
||||
"[pulse] Circuit-Breaker: %s→CLOSED (success, backoff_level=%d→0, "
|
||||
"pulse_interval=%.1fs→%.1fs)",
|
||||
self._breaker_state, self._backoff_level,
|
||||
self._pulse_interval, self._base_pulse_interval,
|
||||
)
|
||||
self._breaker_state = "CLOSED"
|
||||
self._consecutive_429s = 0
|
||||
self._backoff_level = 0
|
||||
self._pulse_interval = self._base_pulse_interval
|
||||
|
||||
def _check_breaker(self) -> bool:
|
||||
"""Check if the circuit breaker allows a tick.
|
||||
|
||||
CLOSED: allow
|
||||
OPEN: if cooldown elapsed → HALF_OPEN (allow one test ping), else block
|
||||
HALF_OPEN: allow (the test ping)
|
||||
|
||||
Returns:
|
||||
True if tick is allowed, False if blocked.
|
||||
"""
|
||||
if self._breaker_state == "CLOSED":
|
||||
return True
|
||||
|
||||
if self._breaker_state == "OPEN":
|
||||
elapsed = time.monotonic() - self._breaker_opened_at
|
||||
if elapsed >= self._breaker_cooldown_s:
|
||||
self._breaker_state = "HALF_OPEN"
|
||||
logger.info(
|
||||
"[pulse] Circuit-Breaker: OPEN→HALF_OPEN (cooldown elapsed, "
|
||||
"sending test ping, pulse_interval=%.1fs)",
|
||||
self._pulse_interval,
|
||||
)
|
||||
return True
|
||||
else:
|
||||
logger.debug(
|
||||
"[pulse] Circuit-Breaker: OPEN (cooldown %.0f/%.0fs remaining)",
|
||||
self._breaker_cooldown_s - elapsed, self._breaker_cooldown_s,
|
||||
)
|
||||
return False
|
||||
|
||||
# HALF_OPEN: allow the test ping
|
||||
return True
|
||||
|
||||
def get_breaker_state(self) -> str:
|
||||
"""Return current breaker state (for testing)."""
|
||||
return self._breaker_state
|
||||
|
||||
def get_consecutive_429s(self) -> int:
|
||||
"""Return current consecutive 429 count (for testing)."""
|
||||
return self._consecutive_429s
|
||||
|
||||
def get_effective_pulse_interval(self) -> float:
|
||||
"""Return current effective pulse interval (for testing)."""
|
||||
return self._pulse_interval
|
||||
|
||||
# ── Internal: Pulse Loop ─────────────────────────────────────────────
|
||||
|
||||
def _pulse_loop(self) -> None:
|
||||
@@ -892,16 +1138,22 @@ class PulseController:
|
||||
def _pulse_tick(self) -> None:
|
||||
"""Execute one pulse tick: toggle phase and send status.
|
||||
|
||||
P1: Circuit-Breaker check before any I/O — if OPEN and cooldown
|
||||
not elapsed, skip the tick entirely. DDP errors are classified:
|
||||
'server returned false' does NOT trigger REST fallback.
|
||||
|
||||
P1-2 O-2: When an asyncio loop is bound, delegates to
|
||||
_pulse_tick_async via run_coroutine_threadsafe. Otherwise
|
||||
uses the legacy sync path (graceful degradation).
|
||||
"""
|
||||
logger.debug(
|
||||
"[pulse] _pulse_tick fired, phase=%s, ddp=%s, paused=%s, cancel_pending=%s, loop=%s",
|
||||
"[pulse] _pulse_tick fired, phase=%s, ddp=%s, paused=%s, cancel_pending=%s, "
|
||||
"breaker=%s, loop=%s",
|
||||
self._phase,
|
||||
self._ddp is not None,
|
||||
self._paused.is_set(),
|
||||
self._cancel_pending_event.is_set(),
|
||||
self._breaker_state,
|
||||
self._loop is not None,
|
||||
)
|
||||
|
||||
@@ -912,6 +1164,11 @@ class PulseController:
|
||||
logger.debug("[pulse] _pulse_tick skip: cancel_pending was set")
|
||||
return
|
||||
|
||||
# P1: Circuit-Breaker — block tick if OPEN and cooldown not elapsed
|
||||
if not self._check_breaker():
|
||||
logger.debug("[pulse] _pulse_tick skip: circuit breaker OPEN")
|
||||
return
|
||||
|
||||
# Toggle phase
|
||||
self._phase = not self._phase
|
||||
|
||||
@@ -954,17 +1211,30 @@ class PulseController:
|
||||
logger.debug("[pulse] _pulse_tick sending (sync): status=%s", status)
|
||||
|
||||
# Try DDP first (K1: DDP set_status has no message variant)
|
||||
ddp_error_type = None
|
||||
if self._ddp is not None and getattr(self._ddp, 'connected', False):
|
||||
try:
|
||||
self._ddp.set_status(status)
|
||||
self._last_sent_phase = self._phase
|
||||
self._increment_telemetry()
|
||||
self._record_success()
|
||||
logger.debug("[pulse] _pulse_tick DDP set_status OK: %s", status)
|
||||
return
|
||||
except Exception as e:
|
||||
logger.info("[pulse] _pulse_tick DDP set_status failed: %s", e)
|
||||
ddp_error_type = self._classify_ddp_error(e)
|
||||
logger.info(
|
||||
"[pulse] _pulse_tick DDP set_status failed: %s (classified=%s)",
|
||||
e, ddp_error_type,
|
||||
)
|
||||
if ddp_error_type == "429":
|
||||
self._record_429()
|
||||
return # P1: 429 → no REST fallback, stop here
|
||||
# ddp_transient: no REST fallback, just skip
|
||||
if ddp_error_type == "ddp_transient":
|
||||
return
|
||||
# 'other': fall through to REST fallback
|
||||
|
||||
# REST fallback for message text
|
||||
# REST fallback for message text (only for non-429, non-transient DDP errors)
|
||||
if self._rest is not None and getattr(self._rest, 'auth_token', None):
|
||||
try:
|
||||
msg = ""
|
||||
@@ -980,8 +1250,13 @@ class PulseController:
|
||||
)
|
||||
self._last_sent_phase = self._phase
|
||||
self._increment_telemetry()
|
||||
self._record_success()
|
||||
logger.debug("[pulse] _pulse_tick REST setStatus OK: %s", status)
|
||||
except Exception as e:
|
||||
error_str = str(e).lower()
|
||||
if "429" in error_str or "too many requests" in error_str:
|
||||
self._record_429()
|
||||
return # P1: 429 → stop here, symmetric with DDP path
|
||||
logger.info("[pulse] _pulse_tick REST setStatus failed: %s", e)
|
||||
else:
|
||||
logger.debug(
|
||||
@@ -993,6 +1268,9 @@ class PulseController:
|
||||
async def _pulse_tick_async(self) -> None:
|
||||
"""P1-2 O-2: Async pulse tick using await set_status_async.
|
||||
|
||||
P1: DDP errors are classified — 'server returned false' does NOT
|
||||
trigger REST fallback. 429 errors trigger circuit breaker.
|
||||
|
||||
Runs on the asyncio event loop (dispatched via
|
||||
run_coroutine_threadsafe from the pulse thread).
|
||||
Uses DDPClient.set_status_async for true await-semantics
|
||||
@@ -1007,16 +1285,23 @@ class PulseController:
|
||||
await self._ddp.set_status_async(status, timeout=self._await_timeout)
|
||||
self._last_sent_phase = self._phase
|
||||
self._increment_telemetry()
|
||||
self._record_success()
|
||||
logger.debug("[pulse] _pulse_tick_async DDP set_status_async OK: %s", status)
|
||||
return
|
||||
except Exception as e:
|
||||
ddp_error_type = self._classify_ddp_error(e)
|
||||
logger.info(
|
||||
"[pulse] _pulse_tick_async DDP set_status_async failed: %s — "
|
||||
"falling back to REST",
|
||||
e,
|
||||
"[pulse] _pulse_tick_async DDP set_status_async failed: %s (classified=%s)",
|
||||
e, ddp_error_type,
|
||||
)
|
||||
if ddp_error_type == "429":
|
||||
self._record_429()
|
||||
return # P1: 429 → no REST fallback
|
||||
if ddp_error_type == "ddp_transient":
|
||||
return # P1: transient → no REST fallback
|
||||
# 'other': fall through to REST fallback
|
||||
|
||||
# REST fallback for message text
|
||||
# REST fallback for message text (only for non-429, non-transient DDP errors)
|
||||
if self._rest is not None and getattr(self._rest, 'auth_token', None):
|
||||
try:
|
||||
msg = ""
|
||||
@@ -1032,8 +1317,13 @@ class PulseController:
|
||||
)
|
||||
self._last_sent_phase = self._phase
|
||||
self._increment_telemetry()
|
||||
self._record_success()
|
||||
logger.debug("[pulse] _pulse_tick_async REST setStatus OK: %s", status)
|
||||
except Exception as e:
|
||||
error_str = str(e).lower()
|
||||
if "429" in error_str or "too many requests" in error_str:
|
||||
self._record_429()
|
||||
return # P1: 429 → stop here, symmetric with DDP path
|
||||
logger.info("[pulse] _pulse_tick_async REST setStatus failed: %s", e)
|
||||
else:
|
||||
logger.debug(
|
||||
@@ -1061,13 +1351,17 @@ class PulseController:
|
||||
class DetectionTimer:
|
||||
"""Detects whether background agents are active.
|
||||
|
||||
P1b: gateway_state.json is PRIMARY — active_agents > 1 means active.
|
||||
P1-2: plugin_state.json is SECONDARY — background_tasks > 0 means active.
|
||||
pgrep is TERTIARY/CONFIRM — used as fallback when gateway_state and
|
||||
plugin_state are unavailable or return 0/1 (ambiguous).
|
||||
P2 Fix Option D: PID-Sentinel ist PRIMARY — prüft ob Gateway-Prozess lebt.
|
||||
gateway_state.json ist SECONDARY — active_agents > 0 bedeutet Subagenten aktiv.
|
||||
plugin_state.json ist TERTIARY — background_tasks > 0 bedeutet aktiv.
|
||||
pgrep ist QUATERNARY/FALLBACK — 'hermes_cli|hermes chat|gateway run'.
|
||||
|
||||
pgrep pattern: 'hermes_cli|hermes chat' (catches subagents AND gateway
|
||||
subprocesses). Self-pid exclude is preserved.
|
||||
pgrep pattern: 'hermes_cli|hermes chat|gateway run' (fängt Subagenten
|
||||
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.
|
||||
"""
|
||||
@@ -1132,17 +1426,37 @@ class DetectionTimer:
|
||||
self._thread = None
|
||||
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:
|
||||
"""Check if background agents are active.
|
||||
|
||||
P1b: gateway_state.json is PRIMARY — active_agents > 1 means active.
|
||||
P1-2: plugin_state.json is SECONDARY — background_tasks > 0 means active.
|
||||
pgrep is TERTIARY/CONFIRM — used as fallback when gateway_state and
|
||||
plugin_state are unavailable or return 0/1 (ambiguous).
|
||||
P2 Fix Option D: PID-Sentinel ist PRIMARY — prüft ob Gateway-Prozess lebt.
|
||||
gateway_state.json ist SECONDARY — active_agents > 0 bedeutet Subagenten aktiv.
|
||||
plugin_state.json ist TERTIARY — background_tasks > 0 bedeutet aktiv.
|
||||
pgrep ist QUATERNARY/FALLBACK — 'hermes_cli|hermes chat|gateway run'.
|
||||
|
||||
pgrep pattern expanded from 'hermes chat --profile' to
|
||||
'hermes_cli|hermes chat' to catch subagents AND gateway subprocesses.
|
||||
Self-pid exclude is preserved.
|
||||
pgrep pattern: 'hermes_cli|hermes chat|gateway run' (fängt Subagenten
|
||||
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.
|
||||
|
||||
Returns:
|
||||
True if background agents are detected, False otherwise.
|
||||
@@ -1153,27 +1467,38 @@ class DetectionTimer:
|
||||
result = False
|
||||
pgrep_pids = -1 # -1 = not yet run, >=0 = count, stays -1 on error
|
||||
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
|
||||
plugin_used = False # P1-2: True if plugin_state was the deciding signal
|
||||
plugin_bg_tasks = -1 # P1-2: -1 = not read, >=0 = count
|
||||
subagent_used = False # Phase 5: True if subagent_status.json was the deciding signal
|
||||
subagent_count = -1 # Phase 5: -1 = not read, >=0 = count
|
||||
detection_source = "none" # P1-2: which signal decided
|
||||
|
||||
# ── PRIMARY: gateway_state.json ────────────────────────────────────
|
||||
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)
|
||||
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
|
||||
# ── P2 PRIMARY: PID-Sentinel — prüft ob Gateway-Prozess lebt ────────
|
||||
if self._check_gateway_pid_alive():
|
||||
result = True
|
||||
pid_used = True
|
||||
detection_source = "gateway_pid"
|
||||
|
||||
# ── P1-2: SECONDARY: plugin_state.json ─────────────────────────────
|
||||
if not gateway_used:
|
||||
# ── P2 SECONDARY: gateway_state.json (Schwelle >0, war >1) ──────────
|
||||
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_bg_tasks = plugin_state.get("background_tasks", 0)
|
||||
if plugin_bg_tasks > 0:
|
||||
@@ -1181,13 +1506,26 @@ class DetectionTimer:
|
||||
plugin_used = True
|
||||
detection_source = "plugin_state"
|
||||
|
||||
# ── TERTIARY: pgrep — run when neither gateway nor plugin decided ──
|
||||
if not gateway_used and not plugin_used:
|
||||
# ── Phase 5: QUATERNARY: subagent_status.json ────────────────────────
|
||||
if not pid_used and not gateway_used and not plugin_used:
|
||||
try:
|
||||
from archivar.subagent_tracker import _read_subagent_state, _get_subagent_state_path
|
||||
subagent_state = _read_subagent_state(_get_subagent_state_path())
|
||||
subagent_count = len(subagent_state.get("active", []))
|
||||
if subagent_count > 0:
|
||||
result = True
|
||||
subagent_used = True
|
||||
detection_source = "subagent_status"
|
||||
except Exception as e:
|
||||
logger.debug("[detection] subagent_status.json read failed: %s", e)
|
||||
|
||||
# ── P2 QUATERNARY: pgrep — erweitertes Pattern 'gateway run' ────────
|
||||
if not pid_used and not gateway_used and not plugin_used and not subagent_used:
|
||||
try:
|
||||
own_pid = os.getpid()
|
||||
# P1b: Expanded pattern catches subagents AND gateway subprocesses
|
||||
# P2 Fix: Pattern um 'gateway run' erweitert
|
||||
proc = subprocess.run(
|
||||
["pgrep", "-f", "hermes_cli|hermes chat"],
|
||||
["pgrep", "-f", "hermes_cli|hermes chat|gateway run"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=5,
|
||||
@@ -1207,14 +1545,19 @@ class DetectionTimer:
|
||||
# ── Log: all signals, result, source ───────────────────────────────
|
||||
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"
|
||||
subagent_str = str(subagent_count) if subagent_count >= 0 else "n/a"
|
||||
logger.info(
|
||||
"[detection] check #%d: gateway_state=%d (primary=%s), "
|
||||
"plugin_state=%s (bg_tasks=%s), pgrep=%s, "
|
||||
"[detection] check #%d: pid_sentinel=%s, gateway_state=%d (primary=%s), "
|
||||
"plugin_state=%s (bg_tasks=%s), subagent_status=%s (active=%s), pgrep=%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 plugin_used else "no",
|
||||
plugin_str,
|
||||
"yes" if subagent_used else "no",
|
||||
subagent_str,
|
||||
pgrep_str,
|
||||
"active" if result else "inactive",
|
||||
detection_source,
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
"""
|
||||
V8.6 Phase 5: SubagentTracker — Adapter-seitiges Modul für Subagent-Status.
|
||||
|
||||
Persistiert aktive Subagenten nach ~/.hermes/plugin_state/subagent_status.json.
|
||||
Thread-safe. Atomic write via temp+rename (Pattern aus _write_plugin_state).
|
||||
|
||||
Zero external dependencies — stdlib only.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional, List, Dict
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Constants
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
SUBAGENT_STATE_DIR = os.path.expanduser("~/.hermes/plugin_state")
|
||||
SUBAGENT_STATE_FILENAME = "subagent_status.json"
|
||||
SUBAGENT_STATE_SCHEMA_VERSION = 1
|
||||
|
||||
|
||||
def _get_subagent_state_path() -> str:
|
||||
"""Return the path to the subagent status file."""
|
||||
return os.path.join(SUBAGENT_STATE_DIR, SUBAGENT_STATE_FILENAME)
|
||||
|
||||
|
||||
def _read_subagent_state(path: str) -> dict:
|
||||
"""Read the subagent state file, returning default empty dict if missing or corrupt."""
|
||||
try:
|
||||
if not os.path.exists(path):
|
||||
return {"active": [], "last_change_iso": "", "schema_version": SUBAGENT_STATE_SCHEMA_VERSION, "source": "plugin_internal"}
|
||||
with open(path, 'r') as f:
|
||||
return json.load(f)
|
||||
except (json.JSONDecodeError, IOError, OSError) as e:
|
||||
logger.debug("[subagent_tracker] read failed: %s", e)
|
||||
return {"active": [], "last_change_iso": "", "schema_version": SUBAGENT_STATE_SCHEMA_VERSION, "source": "plugin_internal"}
|
||||
|
||||
|
||||
def _write_subagent_state(path: str, data: dict) -> None:
|
||||
"""Atomically write the subagent state file (write-temp + rename).
|
||||
|
||||
Pattern from _write_plugin_state in presence_engine.py.
|
||||
"""
|
||||
try:
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
fd, tmp_path = tempfile.mkstemp(
|
||||
suffix=".tmp",
|
||||
prefix="subagent_state_",
|
||||
dir=os.path.dirname(path),
|
||||
)
|
||||
try:
|
||||
with os.fdopen(fd, 'w') as f:
|
||||
json.dump(data, f, ensure_ascii=False)
|
||||
os.replace(tmp_path, path) # atomic on POSIX
|
||||
except Exception:
|
||||
try:
|
||||
os.unlink(tmp_path)
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.debug("[subagent_tracker] write failed: %s", e)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# SubagentTracker
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class SubagentTracker:
|
||||
"""Tracks active subagents for the PresenceEngine.
|
||||
|
||||
Thread-safe: uses threading.Lock for all state mutations.
|
||||
Atomic write: temp+rename pattern prevents corruption.
|
||||
|
||||
Usage:
|
||||
tracker = SubagentTracker()
|
||||
tracker.register("delegate_task", room_name="user:bernd")
|
||||
# ... subagent runs ...
|
||||
tracker.complete("delegate_task")
|
||||
active = tracker.list() # → []
|
||||
"""
|
||||
|
||||
def __init__(self, state_path: str = ""):
|
||||
"""Initialize SubagentTracker.
|
||||
|
||||
Args:
|
||||
state_path: Path to subagent_status.json. Defaults to
|
||||
~/.hermes/plugin_state/subagent_status.json.
|
||||
"""
|
||||
if not state_path:
|
||||
state_path = _get_subagent_state_path()
|
||||
self._state_path = state_path
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def register(self, subagent_type: str, room_name: str = "", task_id: str = "") -> dict:
|
||||
"""Register a new active subagent.
|
||||
|
||||
Args:
|
||||
subagent_type: One of 'delegate_task', 'terminal_background', 'task_management'.
|
||||
room_name: Owner room (e.g. 'user:bernd').
|
||||
task_id: Optional task identifier. Auto-generated if empty.
|
||||
|
||||
Returns:
|
||||
The created entry dict.
|
||||
"""
|
||||
if not task_id:
|
||||
task_id = f"t_{int(time.time() * 1_000_000)}"
|
||||
|
||||
entry = {
|
||||
"task_id": task_id,
|
||||
"type": subagent_type,
|
||||
"owner_room": room_name,
|
||||
"started_at": datetime.now(timezone.utc).isoformat(),
|
||||
"expected_duration_s": 600,
|
||||
"plugin_state_source": "adapter.subagent_tracker",
|
||||
}
|
||||
|
||||
with self._lock:
|
||||
state = _read_subagent_state(self._state_path)
|
||||
active = state.get("active", [])
|
||||
active.append(entry)
|
||||
state["active"] = active
|
||||
state["last_change_iso"] = datetime.now(timezone.utc).isoformat()
|
||||
state["schema_version"] = SUBAGENT_STATE_SCHEMA_VERSION
|
||||
state["source"] = "plugin_internal"
|
||||
_write_subagent_state(self._state_path, state)
|
||||
|
||||
logger.info(
|
||||
"[subagent_tracker] registered: type=%s, task_id=%s, room=%s, active_count=%d",
|
||||
subagent_type, task_id, room_name, len(active),
|
||||
)
|
||||
return entry
|
||||
|
||||
def complete(self, subagent_type: str, task_id: str = "") -> int:
|
||||
"""Remove a subagent entry by type (and optionally task_id).
|
||||
|
||||
If task_id is provided, only removes the matching entry.
|
||||
If task_id is empty, removes ALL entries of the given type.
|
||||
|
||||
Args:
|
||||
subagent_type: Type to remove.
|
||||
task_id: Optional specific task_id to remove.
|
||||
|
||||
Returns:
|
||||
Number of remaining active entries.
|
||||
"""
|
||||
with self._lock:
|
||||
state = _read_subagent_state(self._state_path)
|
||||
active = state.get("active", [])
|
||||
|
||||
if task_id:
|
||||
active = [e for e in active if not (e.get("type") == subagent_type and e.get("task_id") == task_id)]
|
||||
else:
|
||||
active = [e for e in active if e.get("type") != subagent_type]
|
||||
|
||||
state["active"] = active
|
||||
state["last_change_iso"] = datetime.now(timezone.utc).isoformat()
|
||||
_write_subagent_state(self._state_path, state)
|
||||
|
||||
logger.info(
|
||||
"[subagent_tracker] completed: type=%s, task_id=%s, remaining=%d",
|
||||
subagent_type, task_id, len(active),
|
||||
)
|
||||
return len(active)
|
||||
|
||||
def list(self) -> List[Dict]:
|
||||
"""List all currently active subagent entries.
|
||||
|
||||
Returns:
|
||||
List of active entry dicts.
|
||||
"""
|
||||
state = _read_subagent_state(self._state_path)
|
||||
return state.get("active", [])
|
||||
|
||||
def count(self) -> int:
|
||||
"""Return the number of active subagents.
|
||||
|
||||
Returns:
|
||||
Count of active entries.
|
||||
"""
|
||||
return len(self.list())
|
||||
|
||||
def clear_all(self) -> None:
|
||||
"""Remove all active entries (for testing/reset)."""
|
||||
with self._lock:
|
||||
state = _read_subagent_state(self._state_path)
|
||||
state["active"] = []
|
||||
state["last_change_iso"] = datetime.now(timezone.utc).isoformat()
|
||||
_write_subagent_state(self._state_path, state)
|
||||
logger.info("[subagent_tracker] all entries cleared")
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Module-level convenience (singleton pattern for adapter use)
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
_default_tracker: Optional[SubagentTracker] = None
|
||||
_tracker_lock = threading.Lock()
|
||||
|
||||
|
||||
def get_tracker() -> SubagentTracker:
|
||||
"""Get or create the module-level SubagentTracker singleton."""
|
||||
global _default_tracker
|
||||
if _default_tracker is None:
|
||||
with _tracker_lock:
|
||||
if _default_tracker is None:
|
||||
_default_tracker = SubagentTracker()
|
||||
return _default_tracker
|
||||
@@ -280,3 +280,53 @@ def test_outbound_gate_stats_defaults():
|
||||
assert stats.quick_reply == 0
|
||||
assert stats.stale_swept == 0
|
||||
assert stats.released_total == 0
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# 6.1: mark_quick_reply_sent returns True on first call
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
@pytest.mark.outbound_gate
|
||||
def test_mark_quick_reply_sent_first_call_returns_true():
|
||||
"""6.1: mark_quick_reply_sent returns True beim ersten Aufruf."""
|
||||
gate = OutboundGate()
|
||||
room = "ROOM_QR_TEST_1"
|
||||
|
||||
result = gate.mark_quick_reply_sent(room)
|
||||
assert result is True, "First mark_quick_reply_sent should return True"
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# 6.2: mark_quick_reply_sent returns False on second call (idempotent)
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
@pytest.mark.outbound_gate
|
||||
def test_mark_quick_reply_sent_second_call_returns_false():
|
||||
"""6.2: mark_quick_reply_sent returns False beim zweiten Aufruf (idempotent)."""
|
||||
gate = OutboundGate()
|
||||
room = "ROOM_QR_TEST_2"
|
||||
|
||||
first = gate.mark_quick_reply_sent(room)
|
||||
assert first is True
|
||||
|
||||
second = gate.mark_quick_reply_sent(room)
|
||||
assert second is False, "Second mark_quick_reply_sent should return False (idempotent)"
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# 6.3: quick_reply_already_sent returns correct before/after mark
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
@pytest.mark.outbound_gate
|
||||
def test_quick_reply_already_sent_before_and_after():
|
||||
"""6.3: quick_reply_already_sent returns korrekt vor/nach mark."""
|
||||
gate = OutboundGate()
|
||||
room = "ROOM_QR_TEST_3"
|
||||
|
||||
# Before mark: should be False
|
||||
assert gate.quick_reply_already_sent(room) is False
|
||||
|
||||
gate.mark_quick_reply_sent(room)
|
||||
|
||||
# After mark: should be True
|
||||
assert gate.quick_reply_already_sent(room) is True
|
||||
|
||||
@@ -1362,7 +1362,8 @@ class TestDetectionTimerPgrepSelfExclude:
|
||||
own_pid = os.getpid()
|
||||
|
||||
# Mock subprocess.run: pgrep returns only our own PID
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run, \
|
||||
patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||
mock_run.return_value = MagicMock(
|
||||
stdout=f"{own_pid}\n",
|
||||
stderr="",
|
||||
@@ -1425,7 +1426,8 @@ class TestDetectionTimerOnChangeCallback:
|
||||
MagicMock(stdout=f"{own_pid}\n", stderr="", returncode=0),
|
||||
]
|
||||
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run, \
|
||||
patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||
mock_run.side_effect = mock_results
|
||||
|
||||
dt = DetectionTimer(
|
||||
@@ -2088,7 +2090,8 @@ class TestDetectionTimerPluginState:
|
||||
})
|
||||
|
||||
own_pid = os.getpid()
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run, \
|
||||
patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||
mock_run.return_value = MagicMock(
|
||||
stdout=f"{own_pid}\n",
|
||||
stderr="",
|
||||
@@ -2215,7 +2218,8 @@ class TestDetectionSourceTelemetry:
|
||||
detection_interval=0.1,
|
||||
plugin_state_path=state_path,
|
||||
)
|
||||
dt.check()
|
||||
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||
dt.check()
|
||||
assert routing_telemetry.heartbeat_detection_source == "plugin_state"
|
||||
|
||||
def test_detection_source_none_when_inactive(self):
|
||||
@@ -2226,7 +2230,8 @@ class TestDetectionSourceTelemetry:
|
||||
routing_telemetry.heartbeat_detection_source = "none"
|
||||
|
||||
own_pid = os.getpid()
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run, \
|
||||
patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||
mock_run.return_value = MagicMock(
|
||||
stdout=f"{own_pid}\n",
|
||||
stderr="",
|
||||
@@ -2248,7 +2253,8 @@ class TestDetectionSourceTelemetry:
|
||||
routing_telemetry.heartbeat_detection_source = "none"
|
||||
|
||||
own_pid = os.getpid()
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run, \
|
||||
patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||
mock_run.return_value = MagicMock(
|
||||
stdout=f"{own_pid}\n99999\n",
|
||||
stderr="",
|
||||
@@ -2276,7 +2282,8 @@ class TestDetectionSourceTelemetry:
|
||||
gw_path = f.name
|
||||
|
||||
try:
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run, \
|
||||
patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path=gw_path,
|
||||
detection_interval=0.1,
|
||||
@@ -2308,3 +2315,403 @@ class TestPresenceEnginePluginStateIntegration:
|
||||
assert engine._detection_timer._plugin_state_path is not None
|
||||
assert "plugin_state" in engine._detection_timer._plugin_state_path
|
||||
assert "hermes_rocket_plugin.json" in engine._detection_timer._plugin_state_path
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# P1: Circuit-Breaker — 429-Schutz im PulseController
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestCircuitBreakerStateTransitions:
|
||||
"""P1: Circuit-Breaker state machine — CLOSED → OPEN → HALF_OPEN → CLOSED."""
|
||||
|
||||
def test_breaker_starts_closed(self):
|
||||
"""Neuer PulseController startet im CLOSED state."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||
assert pc.get_breaker_state() == "CLOSED"
|
||||
assert pc.get_consecutive_429s() == 0
|
||||
|
||||
def test_three_consecutive_429s_open_breaker(self):
|
||||
"""3 aufeinanderfolgende 429 → CLOSED→OPEN, pulse_interval steigt."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
mock_ddp = MagicMock()
|
||||
mock_ddp.connected = True
|
||||
# DDP wirft 429-Fehler
|
||||
mock_ddp.set_status = MagicMock(side_effect=Exception("HTTP 429 Too Many Requests"))
|
||||
|
||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||
pc.bind_ddp(mock_ddp)
|
||||
|
||||
base_interval = pc.get_effective_pulse_interval()
|
||||
|
||||
# Tick 1: 429 #1
|
||||
pc._pulse_tick()
|
||||
assert pc.get_breaker_state() == "CLOSED"
|
||||
assert pc.get_consecutive_429s() == 1
|
||||
|
||||
# Tick 2: 429 #2
|
||||
pc._pulse_tick()
|
||||
assert pc.get_breaker_state() == "CLOSED"
|
||||
assert pc.get_consecutive_429s() == 2
|
||||
|
||||
# Tick 3: 429 #3 → OPEN
|
||||
pc._pulse_tick()
|
||||
assert pc.get_breaker_state() == "OPEN"
|
||||
assert pc.get_consecutive_429s() == 3
|
||||
# pulse_interval sollte auf backoff_level=0 → 5.0s gestiegen sein
|
||||
assert pc.get_effective_pulse_interval() > base_interval
|
||||
|
||||
def test_breaker_blocks_ticks_when_open(self):
|
||||
"""OPEN state blockiert Ticks bis Cooldown abläuft."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
mock_ddp = MagicMock()
|
||||
mock_ddp.connected = True
|
||||
mock_ddp.set_status = MagicMock(side_effect=Exception("HTTP 429 Too Many Requests"))
|
||||
|
||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||
pc.bind_ddp(mock_ddp)
|
||||
|
||||
# 3×429 → OPEN
|
||||
for _ in range(3):
|
||||
pc._pulse_tick()
|
||||
assert pc.get_breaker_state() == "OPEN"
|
||||
|
||||
# Weitere Ticks werden geblockt (kein DDP-Call mehr)
|
||||
call_count_before = mock_ddp.set_status.call_count
|
||||
for _ in range(5):
|
||||
pc._pulse_tick()
|
||||
# Keine neuen DDP-Calls (breaker blockiert)
|
||||
assert mock_ddp.set_status.call_count == call_count_before
|
||||
|
||||
|
||||
class TestCircuitBreakerHalfOpen:
|
||||
"""P1: HALF_OPEN-Pfad — Test-Ping nach Cooldown."""
|
||||
|
||||
def test_half_open_success_returns_to_closed(self):
|
||||
"""HALF_OPEN Test-Ping success → CLOSED, pulse_interval reset."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
# DDP wirft 3×429, dann success
|
||||
call_count = [0]
|
||||
|
||||
def ddp_side_effect(status):
|
||||
call_count[0] += 1
|
||||
if call_count[0] <= 3:
|
||||
raise Exception("HTTP 429 Too Many Requests")
|
||||
return True
|
||||
|
||||
mock_ddp = MagicMock()
|
||||
mock_ddp.connected = True
|
||||
mock_ddp.set_status = MagicMock(side_effect=ddp_side_effect)
|
||||
|
||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||
pc.bind_ddp(mock_ddp)
|
||||
|
||||
# 3×429 → OPEN
|
||||
for _ in range(3):
|
||||
pc._pulse_tick()
|
||||
assert pc.get_breaker_state() == "OPEN"
|
||||
|
||||
# Simuliere Cooldown-Ablauf: setze _breaker_opened_at in die Vergangenheit
|
||||
pc._breaker_opened_at = time.monotonic() - pc._breaker_cooldown_s - 1.0
|
||||
|
||||
# Nächster Tick: _check_breaker → HALF_OPEN, dann success → CLOSED
|
||||
pc._pulse_tick()
|
||||
assert pc.get_breaker_state() == "CLOSED"
|
||||
assert pc.get_consecutive_429s() == 0
|
||||
# pulse_interval zurück auf base
|
||||
assert pc.get_effective_pulse_interval() == 0.05
|
||||
|
||||
def test_half_open_429_returns_to_open(self):
|
||||
"""HALF_OPEN Test-Ping bekommt 429 → OPEN, backoff eskaliert."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
# DDP wirft IMMER 429
|
||||
mock_ddp = MagicMock()
|
||||
mock_ddp.connected = True
|
||||
mock_ddp.set_status = MagicMock(side_effect=Exception("HTTP 429 Too Many Requests"))
|
||||
|
||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||
pc.bind_ddp(mock_ddp)
|
||||
|
||||
# 3×429 → OPEN (backoff_level=0, pulse_interval=5.0)
|
||||
for _ in range(3):
|
||||
pc._pulse_tick()
|
||||
assert pc.get_breaker_state() == "OPEN"
|
||||
first_open_interval = pc.get_effective_pulse_interval()
|
||||
|
||||
# Simuliere Cooldown-Ablauf
|
||||
pc._breaker_opened_at = time.monotonic() - pc._breaker_cooldown_s - 1.0
|
||||
|
||||
# HALF_OPEN Test-Ping → 429 → OPEN again, backoff_level=1 → 15.0s
|
||||
pc._pulse_tick()
|
||||
assert pc.get_breaker_state() == "OPEN"
|
||||
assert pc.get_effective_pulse_interval() > first_open_interval
|
||||
|
||||
|
||||
class TestCircuitBreakerSustained429:
|
||||
"""P1: sustained-429 — adaptives pulse_interval steigt unter Last."""
|
||||
|
||||
def test_sustained_429_escalates_pulse_interval(self):
|
||||
"""Anhaltende 429 → pulse_interval: 1.5s → 5s → 15s → 60s."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
mock_ddp = MagicMock()
|
||||
mock_ddp.connected = True
|
||||
mock_ddp.set_status = MagicMock(side_effect=Exception("HTTP 429 Too Many Requests"))
|
||||
|
||||
pc = PulseController(pulse_interval=1.5, _clamp_pulse=False)
|
||||
pc.bind_ddp(mock_ddp)
|
||||
|
||||
intervals_seen = [pc.get_effective_pulse_interval()]
|
||||
|
||||
# Zyklus 1: 3×429 → OPEN (backoff 0: 5.0s)
|
||||
for _ in range(3):
|
||||
pc._pulse_tick()
|
||||
intervals_seen.append(pc.get_effective_pulse_interval())
|
||||
|
||||
# Cooldown ablaufen lassen → HALF_OPEN → 429 → OPEN (backoff 1: 15.0s)
|
||||
pc._breaker_opened_at = time.monotonic() - pc._breaker_cooldown_s - 1.0
|
||||
pc._pulse_tick()
|
||||
intervals_seen.append(pc.get_effective_pulse_interval())
|
||||
|
||||
# Cooldown ablaufen lassen → HALF_OPEN → 429 → OPEN (backoff 2: 60.0s)
|
||||
pc._breaker_opened_at = time.monotonic() - pc._breaker_cooldown_s - 1.0
|
||||
pc._pulse_tick()
|
||||
intervals_seen.append(pc.get_effective_pulse_interval())
|
||||
|
||||
# Intervalle müssen monoton steigen
|
||||
for i in range(1, len(intervals_seen)):
|
||||
assert intervals_seen[i] >= intervals_seen[i - 1], (
|
||||
f"pulse_interval nicht monoton: {intervals_seen}"
|
||||
)
|
||||
|
||||
# Letztes Intervall sollte 60.0 sein (max backoff)
|
||||
assert intervals_seen[-1] == 60.0, (
|
||||
f"Erwartet 60.0s max backoff, bekam {intervals_seen[-1]}"
|
||||
)
|
||||
|
||||
def test_backoff_capped_at_max(self):
|
||||
"""Backoff-Level capped bei len(backoff_intervals)-1 (60s)."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
mock_ddp = MagicMock()
|
||||
mock_ddp.connected = True
|
||||
mock_ddp.set_status = MagicMock(side_effect=Exception("HTTP 429 Too Many Requests"))
|
||||
|
||||
pc = PulseController(pulse_interval=1.5, _clamp_pulse=False)
|
||||
pc.bind_ddp(mock_ddp)
|
||||
|
||||
# 5 Zyklen OPEN→HALF_OPEN→OPEN (mehr als backoff_intervals Länge)
|
||||
for cycle in range(5):
|
||||
# 3×429 → OPEN
|
||||
for _ in range(3):
|
||||
pc._pulse_tick()
|
||||
# Cooldown ablaufen → HALF_OPEN → 429 → OPEN
|
||||
pc._breaker_opened_at = time.monotonic() - pc._breaker_cooldown_s - 1.0
|
||||
pc._pulse_tick()
|
||||
|
||||
# Sollte bei 60.0 gecapped sein, nicht höher
|
||||
assert pc.get_effective_pulse_interval() == 60.0
|
||||
|
||||
|
||||
class TestCircuitBreakerDdpErrorClassification:
|
||||
"""P1: DDP-Error-Klassifizierung — 'server returned false' kein REST-Fallback."""
|
||||
|
||||
def test_server_returned_false_is_transient(self):
|
||||
"""'server returned false' wird als ddp_transient klassifiziert."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||
result = pc._classify_ddp_error(Exception("DDP: server returned false"))
|
||||
assert result == "ddp_transient"
|
||||
|
||||
def test_429_error_is_classified_as_429(self):
|
||||
"""HTTP 429 wird als '429' klassifiziert."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||
result = pc._classify_ddp_error(Exception("HTTP 429 Too Many Requests"))
|
||||
assert result == "429"
|
||||
|
||||
def test_other_error_is_classified_as_other(self):
|
||||
"""Andere Fehler werden als 'other' klassifiziert."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||
result = pc._classify_ddp_error(Exception("Connection refused"))
|
||||
assert result == "other"
|
||||
|
||||
def test_ddp_transient_does_not_trigger_rest_fallback(self):
|
||||
"""'server returned false' DDP-Fehler → kein REST-Fallback, kein 429-Count."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
mock_ddp = MagicMock()
|
||||
mock_ddp.connected = True
|
||||
mock_ddp.set_status = MagicMock(side_effect=Exception("DDP: server returned false"))
|
||||
|
||||
mock_rest = MagicMock()
|
||||
mock_rest.auth_token = "token"
|
||||
mock_rest.user_id = "user123"
|
||||
mock_rest._request = MagicMock(return_value={"success": True})
|
||||
|
||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||
pc.bind_ddp(mock_ddp)
|
||||
pc.bind_rest(mock_rest)
|
||||
|
||||
# 10 Ticks mit 'server returned false' → kein REST-Fallback, kein 429
|
||||
for _ in range(10):
|
||||
pc._pulse_tick()
|
||||
|
||||
# REST wurde NICHT aufgerufen (kein Fallback)
|
||||
mock_rest._request.assert_not_called()
|
||||
# Kein 429 gezählt
|
||||
assert pc.get_consecutive_429s() == 0
|
||||
# Breaker bleibt CLOSED
|
||||
assert pc.get_breaker_state() == "CLOSED"
|
||||
|
||||
def test_429_ddp_error_does_not_trigger_rest_fallback(self):
|
||||
"""429 DDP-Fehler → kein REST-Fallback (verhindert Kaskade)."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
mock_ddp = MagicMock()
|
||||
mock_ddp.connected = True
|
||||
mock_ddp.set_status = MagicMock(side_effect=Exception("HTTP 429 Too Many Requests"))
|
||||
|
||||
mock_rest = MagicMock()
|
||||
mock_rest.auth_token = "token"
|
||||
mock_rest.user_id = "user123"
|
||||
mock_rest._request = MagicMock(return_value={"success": True})
|
||||
|
||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||
pc.bind_ddp(mock_ddp)
|
||||
pc.bind_rest(mock_rest)
|
||||
|
||||
# 3×429 DDP → OPEN, REST wurde NIE aufgerufen
|
||||
for _ in range(3):
|
||||
pc._pulse_tick()
|
||||
|
||||
# REST wurde NICHT aufgerufen (429 blockiert Fallback)
|
||||
mock_rest._request.assert_not_called()
|
||||
assert pc.get_breaker_state() == "OPEN"
|
||||
|
||||
|
||||
class TestCircuitBreakerRecordSuccess:
|
||||
"""P1: _record_success() resetet Breaker und pulse_interval."""
|
||||
|
||||
def test_record_success_resets_everything(self):
|
||||
"""_record_success() → CLOSED, 429s=0, backoff=0, pulse_interval=base."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
pc = PulseController(pulse_interval=1.5, _clamp_pulse=False)
|
||||
|
||||
# Manuell in OPEN setzen
|
||||
pc._breaker_state = "OPEN"
|
||||
pc._consecutive_429s = 5
|
||||
pc._backoff_level = 2
|
||||
pc._pulse_interval = 60.0
|
||||
|
||||
pc._record_success()
|
||||
|
||||
assert pc.get_breaker_state() == "CLOSED"
|
||||
assert pc.get_consecutive_429s() == 0
|
||||
assert pc.get_effective_pulse_interval() == 1.5
|
||||
|
||||
def test_success_after_open_resets_interval(self):
|
||||
"""Nach OPEN→HALF_OPEN→success: pulse_interval zurück auf base."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
call_count = [0]
|
||||
|
||||
def ddp_side_effect(status):
|
||||
call_count[0] += 1
|
||||
if call_count[0] <= 3:
|
||||
raise Exception("HTTP 429 Too Many Requests")
|
||||
return True
|
||||
|
||||
mock_ddp = MagicMock()
|
||||
mock_ddp.connected = True
|
||||
mock_ddp.set_status = MagicMock(side_effect=ddp_side_effect)
|
||||
|
||||
pc = PulseController(pulse_interval=1.5, _clamp_pulse=False)
|
||||
pc.bind_ddp(mock_ddp)
|
||||
|
||||
# 3×429 → OPEN (pulse_interval=5.0)
|
||||
for _ in range(3):
|
||||
pc._pulse_tick()
|
||||
assert pc.get_breaker_state() == "OPEN"
|
||||
assert pc.get_effective_pulse_interval() == 5.0
|
||||
|
||||
# Cooldown ablaufen → HALF_OPEN → success → CLOSED
|
||||
pc._breaker_opened_at = time.monotonic() - pc._breaker_cooldown_s - 1.0
|
||||
pc._pulse_tick()
|
||||
|
||||
assert pc.get_breaker_state() == "CLOSED"
|
||||
assert pc.get_effective_pulse_interval() == 1.5
|
||||
|
||||
|
||||
class TestCircuitBreakerRest429Return:
|
||||
"""P1: REST 429 path has explicit return — symmetric with DDP path."""
|
||||
|
||||
def test_rest_429_stops_execution(self):
|
||||
"""Nach _record_429() im REST-Pfad wird kein weiterer Code ausgeführt."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
mock_rest = MagicMock()
|
||||
mock_rest.auth_token = "token"
|
||||
mock_rest.user_id = "user123"
|
||||
# REST wirft 429
|
||||
mock_rest._request = MagicMock(
|
||||
side_effect=Exception("HTTP 429 Too Many Requests")
|
||||
)
|
||||
|
||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||
pc.bind_rest(mock_rest)
|
||||
# Kein DDP → fällt direkt in REST-Fallback
|
||||
# Phase=True → away (damit message gesetzt wird)
|
||||
|
||||
# Mock _record_429 um Aufruf zu verfolgen
|
||||
record_calls = []
|
||||
pc._record_429 = lambda: record_calls.append(1)
|
||||
|
||||
with patch.object(pc.__class__, "_record_429", side_effect=lambda self: record_calls.append(1)) as mock_record:
|
||||
pc._pulse_tick()
|
||||
|
||||
# _record_429 wurde aufgerufen
|
||||
assert len(record_calls) == 1, (
|
||||
f"Expected _record_429 to be called once, got {len(record_calls)}"
|
||||
)
|
||||
# REST._request wurde aufgerufen (hat 429 geworfen)
|
||||
assert mock_rest._request.call_count == 1
|
||||
|
||||
def test_rest_429_does_not_log_failure(self):
|
||||
"""Nach _record_429() im REST-Pfad wird 'REST setStatus failed' NICHT geloggt."""
|
||||
import logging
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
mock_rest = MagicMock()
|
||||
mock_rest.auth_token = "token"
|
||||
mock_rest.user_id = "user123"
|
||||
mock_rest._request = MagicMock(
|
||||
side_effect=Exception("HTTP 429 Too Many Requests")
|
||||
)
|
||||
|
||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||
pc.bind_rest(mock_rest)
|
||||
|
||||
# Capture logger output
|
||||
with patch.object(logging.getLogger("plugin.archivar.presence_engine"), "info") as mock_info:
|
||||
pc._pulse_tick()
|
||||
|
||||
# Prüfe dass "REST setStatus failed" NICHT geloggt wurde
|
||||
failure_logged = any(
|
||||
"REST setStatus failed" in str(call_args)
|
||||
for call_args in mock_info.call_args_list
|
||||
)
|
||||
assert not failure_logged, (
|
||||
"REST setStatus failed should NOT be logged after _record_429 returns"
|
||||
)
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
"""
|
||||
P1: Quick-Reply Dedup — Integration-Tests fuer _maybe_send_quick_reply.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
|
||||
from plugin.archivar.outbound_gate import OutboundGate
|
||||
|
||||
|
||||
def _make_bare_adapter():
|
||||
from plugin.adapter import RocketChatAdapter
|
||||
return RocketChatAdapter.__new__(RocketChatAdapter)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_parallel_tasks_quick_reply_only_once():
|
||||
"""Parallele Tasks → Quick-Reply nur 1x (Dedup)."""
|
||||
adapter = _make_bare_adapter()
|
||||
gate = OutboundGate()
|
||||
adapter._outbound_gate = gate
|
||||
await gate.try_acquire("ROOM_A", "token-a")
|
||||
|
||||
call_count = 0
|
||||
async def mock_post(room_id, text):
|
||||
nonlocal call_count; call_count += 1; return "ok"
|
||||
adapter._post_message_unlocked = mock_post
|
||||
|
||||
results = await asyncio.gather(
|
||||
adapter._maybe_send_quick_reply("ROOM_B", "ROOM_A", "Alpha"),
|
||||
adapter._maybe_send_quick_reply("ROOM_B", "ROOM_A", "Alpha"),
|
||||
)
|
||||
assert call_count == 1
|
||||
assert sum(1 for r in results if r is not None) == 1
|
||||
assert sum(1 for r in results if r is None) == 1
|
||||
gate.release("ROOM_A", "token-a")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_same_room_quick_reply_text_no_room_name():
|
||||
"""Same-Raum → Text OHNE Raum-Namen."""
|
||||
adapter = _make_bare_adapter()
|
||||
gate = OutboundGate()
|
||||
adapter._outbound_gate = gate
|
||||
await gate.try_acquire("ROOM_S", "token-s")
|
||||
|
||||
posted = []
|
||||
async def mock_post(room_id, text):
|
||||
posted.append(text); return "ok"
|
||||
adapter._post_message_unlocked = mock_post
|
||||
|
||||
result = await adapter._maybe_send_quick_reply("ROOM_S", "ROOM_S", "Testraum")
|
||||
assert result is not None
|
||||
assert "Testraum" not in posted[0]
|
||||
assert "#" not in posted[0]
|
||||
assert "beschäftigt" in posted[0]
|
||||
gate.release("ROOM_S", "token-s")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cross_room_quick_reply_text_has_room_name():
|
||||
"""Cross-Raum → Text MIT Raum-Namen."""
|
||||
adapter = _make_bare_adapter()
|
||||
gate = OutboundGate()
|
||||
adapter._outbound_gate = gate
|
||||
await gate.try_acquire("ROOM_A", "token-c")
|
||||
|
||||
posted = []
|
||||
async def mock_post(room_id, text):
|
||||
posted.append(text); return "ok"
|
||||
adapter._post_message_unlocked = mock_post
|
||||
|
||||
result = await adapter._maybe_send_quick_reply("ROOM_T", "ROOM_A", "Gamma")
|
||||
assert result is not None
|
||||
assert "Gamma" in posted[0]
|
||||
assert "#" in posted[0]
|
||||
gate.release("ROOM_A", "token-c")
|
||||
@@ -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()
|
||||
@@ -0,0 +1,432 @@
|
||||
"""
|
||||
V8.6 Phase 5: Subagent-Status — PresenceEngine Integrationstests.
|
||||
|
||||
Testet:
|
||||
- mark_busy_done mit background_tasks > 0 (kein online-Übergang)
|
||||
- mark_busy_done mit background_tasks == 0 (Regression: online-Übergang)
|
||||
- _honeymoon_expired mit background_tasks > 0
|
||||
- DetectionTimer liest subagent_status.json
|
||||
- PulseController pulse_target="away" toggles
|
||||
- PulseController pulse_target="busy" message-pulses
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, patch, call
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# B4: Autouse fixture — engine.shutdown() nach jedem Test
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
_ENGINE_REGISTRY: list = []
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _shutdown_presence_engines():
|
||||
"""Track all PresenceEngine instances and call shutdown() after each test."""
|
||||
from plugin.archivar.presence_engine import PresenceEngine
|
||||
|
||||
_original_init = PresenceEngine.__init__
|
||||
|
||||
def _tracking_init(self, *args, **kwargs):
|
||||
_original_init(self, *args, **kwargs)
|
||||
_ENGINE_REGISTRY.append(self)
|
||||
|
||||
PresenceEngine.__init__ = _tracking_init
|
||||
_ENGINE_REGISTRY.clear()
|
||||
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
PresenceEngine.__init__ = _original_init
|
||||
for engine in _ENGINE_REGISTRY:
|
||||
try:
|
||||
engine.shutdown()
|
||||
except Exception:
|
||||
pass
|
||||
_ENGINE_REGISTRY.clear()
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Helper: create a PresenceEngine with mocked REST
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
def _make_engine(**kwargs):
|
||||
from plugin.archivar.presence_engine import PresenceEngine
|
||||
mock_rest = MagicMock()
|
||||
mock_rest.auth_token = "token"
|
||||
mock_rest.user_id = "user123"
|
||||
mock_rest._request = MagicMock(return_value={"success": True})
|
||||
engine = PresenceEngine(rest=mock_rest, **kwargs)
|
||||
return engine, mock_rest
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 3: mark_busy_done with bg_tasks > 0 does NOT transition to online
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestMarkBusyDoneWithBgTasks:
|
||||
"""Test 3: mark_busy_done mit background_tasks > 0 geht NICHT auf online."""
|
||||
|
||||
def test_busy_done_with_bg_tasks_stays_away_or_busy(self):
|
||||
"""Wenn background_tasks > 0, transitioniert mark_busy_done nicht auf online."""
|
||||
engine, mock_rest = _make_engine(coalesce_ms=100)
|
||||
|
||||
# Simuliere: Hauptagent busy + Subagent läuft
|
||||
engine.mark_busy_started(room_name="testroom")
|
||||
engine.increment_background_tasks() # bg=1
|
||||
|
||||
# Honeymoon abwarten
|
||||
time.sleep(1.2)
|
||||
|
||||
# mark_busy_done — sollte NICHT auf online gehen weil bg=1
|
||||
engine.mark_busy_done()
|
||||
|
||||
# Flush coalesce
|
||||
time.sleep(0.3)
|
||||
|
||||
# Prüfe: letzter gesendeter Status ist NICHT "online"
|
||||
# (sollte "away" sein wegen Subagent-Pulse)
|
||||
calls = mock_rest._request.call_args_list
|
||||
assert len(calls) > 0, "Expected at least one REST call"
|
||||
# Der letzte Call sollte nicht "online" mit leerer Message sein
|
||||
last_call = calls[-1]
|
||||
last_data = last_call[1].get("data", {})
|
||||
# Entweder "away" (idle+subagent) oder "busy" (busy+subagent)
|
||||
assert last_data.get("status") != "online", (
|
||||
f"Expected non-online status, got {last_data}"
|
||||
)
|
||||
|
||||
def test_busy_done_zero_bg_tasks_transitions_to_online(self):
|
||||
"""Regression: background_tasks == 0 → online (klassischer Pfad)."""
|
||||
engine, mock_rest = _make_engine(coalesce_ms=100)
|
||||
|
||||
engine.mark_busy_started(room_name="testroom")
|
||||
# KEIN increment_background_tasks → bg=0
|
||||
|
||||
time.sleep(1.2)
|
||||
|
||||
engine.mark_busy_done()
|
||||
time.sleep(0.3)
|
||||
|
||||
calls = mock_rest._request.call_args_list
|
||||
last_call = calls[-1]
|
||||
last_data = last_call[1].get("data", {})
|
||||
assert last_data.get("status") == "online", (
|
||||
f"Expected online status, got {last_data}"
|
||||
)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 5: _honeymoon_expired with bg_tasks > 0
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestHoneymoonExpiredWithBgTasks:
|
||||
"""Test 5: _honeymoon_expired mit background_tasks > 0 geht nicht auf online."""
|
||||
|
||||
def test_honeymoon_expired_with_bg_tasks_does_not_transition(self):
|
||||
"""Honeymoon-Timer feuert, aber bg_tasks > 0 → kein online."""
|
||||
engine, mock_rest = _make_engine(coalesce_ms=100)
|
||||
|
||||
# Starte busy, dann sofort mark_busy_done (Honeymoon läuft noch)
|
||||
engine.mark_busy_started(room_name="testroom")
|
||||
engine.increment_background_tasks() # bg=1
|
||||
|
||||
# Honeymoon abwarten
|
||||
time.sleep(1.2)
|
||||
|
||||
# Honeymoon-Timer sollte gefeuert haben, aber bg=1 → kein online
|
||||
# Rufe _transition_from_busy manuell auf um zu prüfen
|
||||
engine._transition_from_busy()
|
||||
|
||||
time.sleep(0.3)
|
||||
|
||||
calls = mock_rest._request.call_args_list
|
||||
last_call = calls[-1]
|
||||
last_data = last_call[1].get("data", {})
|
||||
assert last_data.get("status") != "online", (
|
||||
f"Expected non-online status after honeymoon with bg_tasks, got {last_data}"
|
||||
)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 6: DetectionTimer reads subagent_status.json
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestDetectionTimerReadsSubagentStatus:
|
||||
"""Test 6: DetectionTimer.check() liest subagent_status.json."""
|
||||
|
||||
def test_detection_timer_detects_subagent_status(self):
|
||||
"""DetectionTimer erkennt aktive Einträge in subagent_status.json."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
from plugin.archivar.subagent_tracker import _write_subagent_state, _get_subagent_state_path
|
||||
|
||||
# Schreibe einen aktiven Subagenten
|
||||
subagent_path = _get_subagent_state_path()
|
||||
_write_subagent_state(subagent_path, {
|
||||
"active": [{"task_id": "t_123", "type": "delegate_task", "owner_room": "user:bernd"}],
|
||||
"last_change_iso": "",
|
||||
"schema_version": 1,
|
||||
"source": "plugin_internal",
|
||||
})
|
||||
|
||||
# DetectionTimer ohne gateway_state (damit PID-Sentinel + gateway fehlschlagen)
|
||||
with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f:
|
||||
gateway_path = f.name
|
||||
try:
|
||||
# Leeres gateway_state → PID-Sentinel greift (Gateway lebt)
|
||||
# Um subagent_status zu testen, mocken wir _check_gateway_pid_alive
|
||||
timer = DetectionTimer(
|
||||
gateway_state_path=gateway_path,
|
||||
detection_interval=10.0,
|
||||
)
|
||||
|
||||
with patch.object(timer, '_check_gateway_pid_alive', return_value=False):
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||
mock_run.return_value = MagicMock(stdout="", returncode=1)
|
||||
result = timer.check()
|
||||
|
||||
# Sollte True sein weil subagent_status.json aktive Einträge hat
|
||||
assert result is True, f"Expected True, got {result}"
|
||||
|
||||
finally:
|
||||
os.unlink(gateway_path)
|
||||
# Cleanup subagent_status.json
|
||||
try:
|
||||
os.unlink(subagent_path)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def test_detection_timer_empty_subagent_status(self):
|
||||
"""DetectionTimer erkennt leere subagent_status.json nicht als aktiv."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
from plugin.archivar.subagent_tracker import _write_subagent_state, _get_subagent_state_path
|
||||
|
||||
subagent_path = _get_subagent_state_path()
|
||||
_write_subagent_state(subagent_path, {
|
||||
"active": [],
|
||||
"last_change_iso": "",
|
||||
"schema_version": 1,
|
||||
"source": "plugin_internal",
|
||||
})
|
||||
|
||||
# Auch plugin_state.json bereinigen (könnte bg_tasks vom vorherigen Test haben)
|
||||
from plugin.archivar.presence_engine import _get_plugin_state_path, _write_plugin_state
|
||||
plugin_path = _get_plugin_state_path()
|
||||
_write_plugin_state(plugin_path, {
|
||||
"background_tasks": 0,
|
||||
"last_update_iso": "",
|
||||
"source": "plugin_internal",
|
||||
"schema_version": 1,
|
||||
})
|
||||
|
||||
with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f:
|
||||
gateway_path = f.name
|
||||
try:
|
||||
timer = DetectionTimer(
|
||||
gateway_state_path=gateway_path,
|
||||
detection_interval=10.0,
|
||||
)
|
||||
|
||||
with patch.object(timer, '_check_gateway_pid_alive', return_value=False):
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||
mock_run.return_value = MagicMock(stdout="", returncode=1)
|
||||
result = timer.check()
|
||||
|
||||
# Sollte False sein weil keine Quellen aktiv
|
||||
assert result is False, f"Expected False, got {result}"
|
||||
|
||||
finally:
|
||||
os.unlink(gateway_path)
|
||||
try:
|
||||
os.unlink(subagent_path)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 7: PulseController pulse_target="away" toggles
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestPulseControllerAwayMode:
|
||||
"""Test 7: PulseController mit pulse_target='away' toggled online↔away."""
|
||||
|
||||
def test_pulse_target_default_is_away(self):
|
||||
"""Default pulse_target ist 'away'."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
pc = PulseController(pulse_interval=0.1, _clamp_pulse=False)
|
||||
assert pc.get_pulse_target() == "away"
|
||||
|
||||
def test_set_pulse_target_away(self):
|
||||
"""set_pulse_target('away') funktioniert."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
pc = PulseController(pulse_interval=0.1, _clamp_pulse=False)
|
||||
changed = pc.set_pulse_target("away")
|
||||
assert changed is False # already "away"
|
||||
assert pc.get_pulse_target() == "away"
|
||||
|
||||
def test_set_pulse_target_busy(self):
|
||||
"""set_pulse_target('busy') wechselt Modus."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
pc = PulseController(pulse_interval=0.1, _clamp_pulse=False)
|
||||
changed = pc.set_pulse_target("busy")
|
||||
assert changed is True
|
||||
assert pc.get_pulse_target() == "busy"
|
||||
|
||||
def test_set_pulse_target_invalid_raises(self):
|
||||
"""Ungültiger pulse_target wirft ValueError."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
pc = PulseController(pulse_interval=0.1, _clamp_pulse=False)
|
||||
with pytest.raises(ValueError):
|
||||
pc.set_pulse_target("invalid")
|
||||
|
||||
def test_pulse_target_mode_sentinel_prevents_race(self):
|
||||
"""Mode-Sentinel: parallele set_pulse_target-Aufrufe sind sicher."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
pc = PulseController(pulse_interval=0.1, _clamp_pulse=False)
|
||||
|
||||
errors = []
|
||||
|
||||
def toggle_mode():
|
||||
try:
|
||||
for _ in range(50):
|
||||
pc.set_pulse_target("away")
|
||||
pc.set_pulse_target("busy")
|
||||
except Exception as e:
|
||||
errors.append(e)
|
||||
|
||||
threads = [threading.Thread(target=toggle_mode) for _ in range(4)]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
|
||||
assert len(errors) == 0, f"Errors: {errors}"
|
||||
# Final mode should be one of the two valid values
|
||||
assert pc.get_pulse_target() in ("away", "busy")
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 8: PulseController pulse_target="busy" message-pulses
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestPulseControllerBusyMode:
|
||||
"""Test 8: PulseController mit pulse_target='busy' hält busy-Status."""
|
||||
|
||||
def test_busy_mode_does_not_toggle_to_online(self):
|
||||
"""Im busy-Modus wird nicht auf online getoggled."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
pc = PulseController(pulse_interval=0.1, _clamp_pulse=False)
|
||||
pc.set_pulse_target("busy")
|
||||
|
||||
# Mock DDP
|
||||
mock_ddp = MagicMock()
|
||||
mock_ddp.connected = True
|
||||
mock_ddp.set_status = MagicMock()
|
||||
pc.bind_ddp(mock_ddp)
|
||||
|
||||
# Start pulse
|
||||
pc.start()
|
||||
time.sleep(0.4) # Wait for a few ticks
|
||||
pc.stop()
|
||||
|
||||
# Im busy-Modus sollte der PulseController NICHT online↔away togglen
|
||||
# sondern den busy-Status halten (via _update_presence_with_subagents)
|
||||
# Hier testen wir nur dass der Mode korrekt gesetzt ist
|
||||
assert pc.get_pulse_target() == "busy"
|
||||
|
||||
def test__update_presence_with_subagents_idle(self):
|
||||
"""_update_presence_with_subagents bei idle startet away-Pulse."""
|
||||
engine, mock_rest = _make_engine(coalesce_ms=100)
|
||||
|
||||
# Sicherstellen dass active_tasks == 0
|
||||
assert engine._active_tasks == 0
|
||||
|
||||
engine._update_presence_with_subagents(3)
|
||||
|
||||
time.sleep(0.3)
|
||||
|
||||
# Sollte "away" mit Message "3 Subagent läuft" gesendet haben
|
||||
calls = mock_rest._request.call_args_list
|
||||
assert len(calls) > 0
|
||||
last_data = calls[-1][1].get("data", {})
|
||||
assert last_data.get("status") == "away"
|
||||
assert "3 Subagent" in last_data.get("message", "")
|
||||
|
||||
def test__update_presence_with_subagents_busy(self):
|
||||
"""_update_presence_with_subagents bei busy setzt busy+Message."""
|
||||
engine, mock_rest = _make_engine(coalesce_ms=100)
|
||||
|
||||
# Simuliere busy
|
||||
engine.increment_active_tasks()
|
||||
engine.set_current_room("testroom")
|
||||
|
||||
engine._update_presence_with_subagents(2)
|
||||
|
||||
time.sleep(0.3)
|
||||
|
||||
calls = mock_rest._request.call_args_list
|
||||
assert len(calls) > 0
|
||||
last_data = calls[-1][1].get("data", {})
|
||||
assert last_data.get("status") == "busy"
|
||||
assert "2 Subagent" in last_data.get("message", "")
|
||||
assert "testroom" in last_data.get("message", "")
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test: _read_subagent_count
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestReadSubagentCount:
|
||||
"""Test: _read_subagent_count() liest subagent_status.json."""
|
||||
|
||||
def test_read_subagent_count_returns_zero_when_empty(self):
|
||||
"""Leere Datei → 0."""
|
||||
engine, _ = _make_engine()
|
||||
# Clean state
|
||||
from plugin.archivar.subagent_tracker import _write_subagent_state, _get_subagent_state_path
|
||||
_write_subagent_state(_get_subagent_state_path(), {
|
||||
"active": [],
|
||||
"last_change_iso": "",
|
||||
"schema_version": 1,
|
||||
"source": "plugin_internal",
|
||||
})
|
||||
assert engine._read_subagent_count() == 0
|
||||
|
||||
def test_read_subagent_count_returns_count(self):
|
||||
"""Datei mit 2 Einträgen → 2."""
|
||||
engine, _ = _make_engine()
|
||||
from plugin.archivar.subagent_tracker import _write_subagent_state, _get_subagent_state_path
|
||||
_write_subagent_state(_get_subagent_state_path(), {
|
||||
"active": [
|
||||
{"task_id": "t_1", "type": "delegate_task"},
|
||||
{"task_id": "t_2", "type": "terminal_background"},
|
||||
],
|
||||
"last_change_iso": "",
|
||||
"schema_version": 1,
|
||||
"source": "plugin_internal",
|
||||
})
|
||||
assert engine._read_subagent_count() == 2
|
||||
|
||||
def test_read_subagent_count_missing_file_returns_zero(self):
|
||||
"""Fehlende Datei → 0 (graceful degradation)."""
|
||||
engine, _ = _make_engine()
|
||||
from plugin.archivar.subagent_tracker import _get_subagent_state_path
|
||||
path = _get_subagent_state_path()
|
||||
try:
|
||||
os.unlink(path)
|
||||
except OSError:
|
||||
pass
|
||||
assert engine._read_subagent_count() == 0
|
||||
@@ -0,0 +1,320 @@
|
||||
"""
|
||||
V8.6 Phase 5: SubagentTracker — Tests.
|
||||
|
||||
Testet register, complete, list, count, atomic write, thread-safety.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
||||
|
||||
from plugin.archivar.subagent_tracker import (
|
||||
SubagentTracker,
|
||||
_get_subagent_state_path,
|
||||
_read_subagent_state,
|
||||
_write_subagent_state,
|
||||
get_tracker,
|
||||
SUBAGENT_STATE_DIR,
|
||||
SUBAGENT_STATE_FILENAME,
|
||||
)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Fixtures
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
@pytest.fixture
|
||||
def tmp_state_path():
|
||||
"""Create a temporary subagent_status.json for isolated testing."""
|
||||
fd, path = tempfile.mkstemp(suffix=".json", prefix="subagent_test_")
|
||||
os.close(fd)
|
||||
# Start with clean state
|
||||
_write_subagent_state(path, {
|
||||
"active": [],
|
||||
"last_change_iso": "",
|
||||
"schema_version": 1,
|
||||
"source": "plugin_internal",
|
||||
})
|
||||
yield path
|
||||
try:
|
||||
os.unlink(path)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def tracker(tmp_state_path):
|
||||
"""Create a SubagentTracker with isolated state file."""
|
||||
return SubagentTracker(state_path=tmp_state_path)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 1: register schreibt atomic JSON
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestRegisterWritesAtomicJson:
|
||||
"""Test 1: register() schreibt korrekt in subagent_status.json."""
|
||||
|
||||
def test_register_creates_entry(self, tracker, tmp_state_path):
|
||||
"""Nach register() ist ein Eintrag in der Datei."""
|
||||
entry = tracker.register("delegate_task", room_name="user:bernd")
|
||||
|
||||
# In-memory check
|
||||
active = tracker.list()
|
||||
assert len(active) == 1
|
||||
assert active[0]["type"] == "delegate_task"
|
||||
assert active[0]["owner_room"] == "user:bernd"
|
||||
assert "task_id" in active[0]
|
||||
assert "started_at" in active[0]
|
||||
|
||||
# File check
|
||||
state = _read_subagent_state(tmp_state_path)
|
||||
assert len(state["active"]) == 1
|
||||
assert state["active"][0]["type"] == "delegate_task"
|
||||
|
||||
def test_register_multiple_entries(self, tracker):
|
||||
"""Mehrere register() Aufrufe erzeugen mehrere Einträge."""
|
||||
tracker.register("delegate_task", room_name="user:bernd")
|
||||
tracker.register("terminal_background", room_name="user:alice")
|
||||
tracker.register("delegate_task", room_name="user:bernd")
|
||||
|
||||
active = tracker.list()
|
||||
assert len(active) == 3
|
||||
types = [e["type"] for e in active]
|
||||
assert types.count("delegate_task") == 2
|
||||
assert types.count("terminal_background") == 1
|
||||
|
||||
def test_register_auto_generates_task_id(self, tracker):
|
||||
"""Wenn kein task_id übergeben wird, wird eins generiert."""
|
||||
entry = tracker.register("delegate_task")
|
||||
assert entry["task_id"].startswith("t_")
|
||||
assert len(entry["task_id"]) > 5
|
||||
|
||||
def test_register_custom_task_id(self, tracker):
|
||||
"""Custom task_id wird übernommen."""
|
||||
entry = tracker.register("delegate_task", task_id="my_custom_id")
|
||||
assert entry["task_id"] == "my_custom_id"
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 2: complete entfernt Eintrag
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestCompleteRemovesEntry:
|
||||
"""Test 2: complete() entfernt Einträge korrekt."""
|
||||
|
||||
def test_complete_by_type_removes_all_of_type(self, tracker):
|
||||
"""complete(type) entfernt ALLE Einträge dieses Typs."""
|
||||
tracker.register("delegate_task", room_name="user:bernd")
|
||||
tracker.register("delegate_task", room_name="user:alice")
|
||||
tracker.register("terminal_background", room_name="user:bernd")
|
||||
|
||||
remaining = tracker.complete("delegate_task")
|
||||
assert remaining == 1
|
||||
|
||||
active = tracker.list()
|
||||
assert len(active) == 1
|
||||
assert active[0]["type"] == "terminal_background"
|
||||
|
||||
def test_complete_by_task_id_removes_specific(self, tracker):
|
||||
"""complete(type, task_id) entfernt nur den spezifischen Eintrag."""
|
||||
e1 = tracker.register("delegate_task", task_id="id_1")
|
||||
e2 = tracker.register("delegate_task", task_id="id_2")
|
||||
|
||||
remaining = tracker.complete("delegate_task", task_id="id_1")
|
||||
assert remaining == 1
|
||||
|
||||
active = tracker.list()
|
||||
assert len(active) == 1
|
||||
assert active[0]["task_id"] == "id_2"
|
||||
|
||||
def test_complete_nonexistent_type_no_error(self, tracker):
|
||||
"""complete() eines nicht existierenden Typs wirft keinen Fehler."""
|
||||
remaining = tracker.complete("nonexistent")
|
||||
assert remaining == 0
|
||||
|
||||
def test_complete_nonexistent_task_id_no_error(self, tracker):
|
||||
"""complete() mit nicht existierender task_id wirft keinen Fehler."""
|
||||
tracker.register("delegate_task", task_id="real_id")
|
||||
remaining = tracker.complete("delegate_task", task_id="fake_id")
|
||||
assert remaining == 1 # real_id bleibt
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 3: list und count
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestListAndCount:
|
||||
"""Test 3: list() und count() liefern korrekte Werte."""
|
||||
|
||||
def test_list_empty_initially(self, tracker):
|
||||
"""Frischer Tracker hat leere Liste."""
|
||||
assert tracker.list() == []
|
||||
assert tracker.count() == 0
|
||||
|
||||
def test_count_matches_list_length(self, tracker):
|
||||
"""count() == len(list())."""
|
||||
tracker.register("delegate_task")
|
||||
tracker.register("terminal_background")
|
||||
tracker.register("delegate_task")
|
||||
|
||||
assert tracker.count() == 3
|
||||
assert tracker.count() == len(tracker.list())
|
||||
|
||||
def test_list_returns_copy_not_reference(self, tracker):
|
||||
"""list() gibt eine Kopie zurück, Mutation ändert nicht den State."""
|
||||
tracker.register("delegate_task")
|
||||
active = tracker.list()
|
||||
active.append({"fake": "entry"})
|
||||
|
||||
# Interner State unverändert
|
||||
assert tracker.count() == 1
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 4: Atomic write
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestAtomicWrite:
|
||||
"""Test 4: Atomic write verhindert Corruption."""
|
||||
|
||||
def test_write_then_read_is_consistent(self, tracker, tmp_state_path):
|
||||
"""Nach write → read ist der State konsistent."""
|
||||
tracker.register("delegate_task", room_name="user:bernd")
|
||||
tracker.register("terminal_background", room_name="user:alice")
|
||||
|
||||
# Re-read from file
|
||||
state = _read_subagent_state(tmp_state_path)
|
||||
assert len(state["active"]) == 2
|
||||
assert state["schema_version"] == 1
|
||||
assert state["source"] == "plugin_internal"
|
||||
assert state["last_change_iso"] != ""
|
||||
|
||||
def test_no_temp_files_left_behind(self, tracker, tmp_state_path):
|
||||
"""Nach write gibt es keine .tmp-Dateien im Verzeichnis."""
|
||||
tracker.register("delegate_task")
|
||||
|
||||
state_dir = os.path.dirname(tmp_state_path)
|
||||
tmp_files = [f for f in os.listdir(state_dir) if f.endswith(".tmp")]
|
||||
assert len(tmp_files) == 0, f"Temp files left behind: {tmp_files}"
|
||||
|
||||
def test_corrupt_file_returns_empty(self, tmp_state_path):
|
||||
"""Korrupte JSON-Datei → leere Liste (graceful degradation)."""
|
||||
with open(tmp_state_path, 'w') as f:
|
||||
f.write("this is not json {{{")
|
||||
|
||||
state = _read_subagent_state(tmp_state_path)
|
||||
assert state["active"] == []
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 5: clear_all
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestClearAll:
|
||||
"""Test 5: clear_all() entfernt alle Einträge."""
|
||||
|
||||
def test_clear_all_removes_everything(self, tracker):
|
||||
"""Nach clear_all() ist die Liste leer."""
|
||||
tracker.register("delegate_task")
|
||||
tracker.register("terminal_background")
|
||||
tracker.register("delegate_task")
|
||||
|
||||
assert tracker.count() == 3
|
||||
tracker.clear_all()
|
||||
assert tracker.count() == 0
|
||||
assert tracker.list() == []
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 6: Thread-safety
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestThreadSafety:
|
||||
"""Test 6: Thread-safety bei parallelen register/complete."""
|
||||
|
||||
def test_concurrent_registers(self, tracker):
|
||||
"""Parallele register() Aufrufe produzieren korrekte Anzahl."""
|
||||
errors = []
|
||||
|
||||
def register_many(n: int):
|
||||
try:
|
||||
for i in range(n):
|
||||
tracker.register("delegate_task", task_id=f"thread_{i}")
|
||||
except Exception as e:
|
||||
errors.append(e)
|
||||
|
||||
threads = []
|
||||
for _ in range(4):
|
||||
t = threading.Thread(target=register_many, args=(25,))
|
||||
threads.append(t)
|
||||
t.start()
|
||||
|
||||
for t in threads:
|
||||
t.join()
|
||||
|
||||
assert len(errors) == 0, f"Errors: {errors}"
|
||||
assert tracker.count() == 100
|
||||
|
||||
def test_concurrent_register_and_complete(self, tracker):
|
||||
"""Gleichzeitiges register() und complete() ist konsistent."""
|
||||
# Pre-populate
|
||||
for i in range(50):
|
||||
tracker.register("delegate_task", task_id=f"pre_{i}")
|
||||
|
||||
errors = []
|
||||
|
||||
def register_more():
|
||||
try:
|
||||
for i in range(25):
|
||||
tracker.register("delegate_task", task_id=f"new_{i}")
|
||||
except Exception as e:
|
||||
errors.append(e)
|
||||
|
||||
def complete_some():
|
||||
try:
|
||||
for i in range(25):
|
||||
tracker.complete("delegate_task", task_id=f"pre_{i}")
|
||||
except Exception as e:
|
||||
errors.append(e)
|
||||
|
||||
t1 = threading.Thread(target=register_more)
|
||||
t2 = threading.Thread(target=complete_some)
|
||||
t1.start()
|
||||
t2.start()
|
||||
t1.join()
|
||||
t2.join()
|
||||
|
||||
assert len(errors) == 0, f"Errors: {errors}"
|
||||
# 50 pre + 25 new - 25 completed = 50
|
||||
assert tracker.count() == 50
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 7: Singleton get_tracker
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestGetTracker:
|
||||
"""Test 7: get_tracker() Singleton."""
|
||||
|
||||
def test_get_tracker_returns_same_instance(self):
|
||||
"""get_tracker() gibt immer dieselbe Instanz zurück."""
|
||||
t1 = get_tracker()
|
||||
t2 = get_tracker()
|
||||
assert t1 is t2
|
||||
|
||||
def test_get_tracker_is_subagent_tracker(self):
|
||||
"""get_tracker() gibt SubagentTracker-Instanz zurück."""
|
||||
t = get_tracker()
|
||||
assert isinstance(t, SubagentTracker)
|
||||
@@ -836,6 +836,8 @@ class TestRoomContextCrossContamination(unittest.TestCase):
|
||||
# _user_rooms hat einen Fallback-Raum (nächste Priorität nach _room_context)
|
||||
self.adapter._user_rooms = {chat_id: [fallback_room]}
|
||||
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(
|
||||
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
|
||||
self.adapter._user_rooms = {chat_id: [user_rooms_room]}
|
||||
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(
|
||||
self.adapter.send(chat_id=chat_id, content="Test response")
|
||||
|
||||
@@ -94,10 +94,10 @@ class RateLimiter:
|
||||
"""Simple token-bucket rate limiter.
|
||||
|
||||
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.window_seconds = window_seconds
|
||||
self.tokens = float(max_tokens)
|
||||
@@ -138,7 +138,7 @@ _rate_limiter: RateLimiter | None = None
|
||||
def _get_rate_limiter() -> RateLimiter:
|
||||
global _rate_limiter
|
||||
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
|
||||
|
||||
|
||||
|
||||
@@ -24,13 +24,13 @@ from .rc_rest import RCRestClient
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 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.
|
||||
_DEFAULT_BACKOFF_INTERVALS = [2.0, 3.0, 5.0, 8.0]
|
||||
_MAX_TOTAL_WAIT = 18.0 # seconds
|
||||
_DEFAULT_BACKOFF_INTERVALS = [5.0, 8.0, 12.0, 20.0]
|
||||
_MAX_TOTAL_WAIT = 45.0 # seconds
|
||||
|
||||
# 429 exponential backoff: 3s -> 6s -> 12s -> 20s -> 30s (max)
|
||||
_MAX_429_BACKOFF = 30.0
|
||||
# 429 exponential backoff: 5s -> 10s -> 20s -> 40s (max)
|
||||
_MAX_429_BACKOFF = 40.0
|
||||
# After 5 consecutive 429s, abort with SKIP instead of retrying forever
|
||||
_MAX_CONSECUTIVE_429 = 5
|
||||
|
||||
@@ -89,7 +89,7 @@ def wait_for_bot_message(
|
||||
cached_messages: list = [] # Cursor caching: reuse fetched batch
|
||||
|
||||
# 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:
|
||||
# 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 "
|
||||
"reducing concurrent test load."
|
||||
)
|
||||
# Exponential backoff on rate-limit errors: 3s -> 6s -> 12s -> 20s -> 30s
|
||||
backoff = min(3.0 * (2 ** (consecutive_429 - 1)), _MAX_429_BACKOFF)
|
||||
# Exponential backoff on rate-limit errors: 5s -> 10s -> 20s -> 40s
|
||||
backoff = min(5.0 * (2 ** (consecutive_429 - 1)), _MAX_429_BACKOFF)
|
||||
logger.warning(
|
||||
"Poll: HTTP 429 (consecutive=%d/%d) -- backing off %ds",
|
||||
consecutive_429, _MAX_CONSECUTIVE_429, backoff,
|
||||
@@ -170,12 +170,12 @@ def wait_for_bot_message(
|
||||
)
|
||||
return msg
|
||||
|
||||
# Progressive backoff: initial_interval -> 3s -> 5s -> 8s
|
||||
# Progressive backoff: initial_interval -> 8s -> 12s -> 20s
|
||||
if interval_idx < len(backoff_intervals):
|
||||
delay = backoff_intervals[interval_idx]
|
||||
interval_idx += 1
|
||||
else:
|
||||
delay = 8.0
|
||||
delay = 20.0
|
||||
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
|
||||
@@ -77,9 +77,9 @@ class RCRestClient:
|
||||
|
||||
req = urllib.request.Request(url, data=body, headers=headers, method=method)
|
||||
|
||||
# 429 retry with exponential backoff: 3s → 6s → 12s → 20s → 30s (max 5 retries)
|
||||
# Total possible wait: 71s — gives RC enough time to reset its rate-limit window.
|
||||
_429_BACKOFFS = [3.0, 6.0, 12.0, 20.0, 30.0]
|
||||
# 429 retry with exponential backoff: 5s → 10s → 20s → 40s (max 4 retries)
|
||||
# Total possible wait: 75s — gives RC enough time to reset its rate-limit window.
|
||||
_429_BACKOFFS = [5.0, 10.0, 20.0, 40.0]
|
||||
max_429_retries = len(_429_BACKOFFS)
|
||||
for attempt in range(max_429_retries + 1):
|
||||
# Rate-limit before every API call (protects post, history, delete, etc.)
|
||||
|
||||
Reference in New Issue
Block a user