V9.0.1: Sync-Hooks — invoke_hook() limitation fix
Root Cause: invoke_hook() im Core ruft Callbacks synchron auf (ret = cb(**kwargs)). Async-Callbacks wurden als Coroutine-Objekt zurückgegeben aber nie awaited → Hook-Code wurde NIE ausgeführt. Symptom: Andreas sah immer nur GRÜN (Hooks registriert, feuerten nie). Änderungen: - presence_engine.py: Alle Hook-Callbacks synchron (kein async/await) - Counter-Mutation unter threading.Lock (statt asyncio.Lock) - REST-Calls via fire-and-forget Daemon-Threads (statt asyncio.create_task) - away-grace via threading.Timer (statt asyncio.Task) - _rest_set_status() synchron (urllib ist von Natur aus sync) - __init__.py: Wrapper-Funktionen synchron (kein async def) - adapter.py: bind_loop() für PresenceEngine entfernt (nicht mehr nötig) - Tests: Alle 39 V9-Tests auf sync umgestellt (kein asyncio, kein await) Tests: 39 passed, 82 skipped in 3.24s
This commit is contained in:
+24
-19
@@ -200,11 +200,16 @@ def _register_presence_hooks() -> None:
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
# ── Wrapper: Holt die PresenceEngine via _active_adapter ──────────
|
# ── Wrapper: Holt die PresenceEngine via _active_adapter ──────────
|
||||||
async def _get_engine_and_call(method_name: str, **kwargs):
|
# V9.0.1: SYNCHRON — invoke_hook() im Core ruft Callbacks via
|
||||||
|
# ret = cb(**kwargs) auf. Async-Callbacks würden als Coroutine-Objekt
|
||||||
|
# zurückgegeben aber nie awaited → Hook-Code wird NIE ausgeführt.
|
||||||
|
def _get_engine_and_call(method_name: str, **kwargs):
|
||||||
"""Hole PresenceEngine aus dem aktiven Adapter und rufe Methode auf.
|
"""Hole PresenceEngine aus dem aktiven Adapter und rufe Methode auf.
|
||||||
|
|
||||||
Nutzt die Modul-Level-Referenz _active_adapter (F1.1: offizielle
|
Nutzt die Modul-Level-Referenz _active_adapter (F1.1: offizielle
|
||||||
API statt privater ctx._adapter/ctx._platforms).
|
API statt privater ctx._adapter/ctx._platforms).
|
||||||
|
|
||||||
|
V9.0.1: Synchron — invoke_hook() erwartet sync-Callbacks.
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
adapter = _active_adapter
|
adapter = _active_adapter
|
||||||
@@ -215,35 +220,35 @@ def _register_presence_hooks() -> None:
|
|||||||
return
|
return
|
||||||
method = getattr(engine, method_name, None)
|
method = getattr(engine, method_name, None)
|
||||||
if method is not None:
|
if method is not None:
|
||||||
await method(**kwargs)
|
method(**kwargs)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.debug("[presence-v9] Hook %s fehlgeschlagen: %s", method_name, e)
|
logger.debug("[presence-v9] Hook %s fehlgeschlagen: %s", method_name, e)
|
||||||
|
|
||||||
# ── 6 Core-Hooks ──────────────────────────────────────────────────
|
# ── 6 Core-Hooks (V9.0.1: synchron) ──────────────────────────────
|
||||||
async def _on_pre_gateway_dispatch(**kwargs):
|
def _on_pre_gateway_dispatch(**kwargs):
|
||||||
await _get_engine_and_call("on_pre_gateway_dispatch", **kwargs)
|
_get_engine_and_call("on_pre_gateway_dispatch", **kwargs)
|
||||||
|
|
||||||
async def _on_post_llm_call(**kwargs):
|
def _on_post_llm_call(**kwargs):
|
||||||
await _get_engine_and_call("on_post_llm_call", **kwargs)
|
_get_engine_and_call("on_post_llm_call", **kwargs)
|
||||||
|
|
||||||
async def _on_subagent_start(**kwargs):
|
def _on_subagent_start(**kwargs):
|
||||||
await _get_engine_and_call("on_subagent_start", **kwargs)
|
_get_engine_and_call("on_subagent_start", **kwargs)
|
||||||
|
|
||||||
async def _on_subagent_stop(**kwargs):
|
def _on_subagent_stop(**kwargs):
|
||||||
await _get_engine_and_call("on_subagent_stop", **kwargs)
|
_get_engine_and_call("on_subagent_stop", **kwargs)
|
||||||
|
|
||||||
async def _on_session_start(**kwargs):
|
def _on_session_start(**kwargs):
|
||||||
await _get_engine_and_call("on_session_start", **kwargs)
|
_get_engine_and_call("on_session_start", **kwargs)
|
||||||
|
|
||||||
async def _on_session_end(**kwargs):
|
def _on_session_end(**kwargs):
|
||||||
await _get_engine_and_call("on_session_end", **kwargs)
|
_get_engine_and_call("on_session_end", **kwargs)
|
||||||
|
|
||||||
# ── 2 Tool-Filter-Hooks (O-1: Background-Terminal-Workaround) ─────
|
# ── 2 Tool-Filter-Hooks (O-1: Background-Terminal-Workaround) ─────
|
||||||
async def _on_pre_tool_call(**kwargs):
|
def _on_pre_tool_call(**kwargs):
|
||||||
await _get_engine_and_call("on_pre_tool_call", **kwargs)
|
_get_engine_and_call("on_pre_tool_call", **kwargs)
|
||||||
|
|
||||||
async def _on_post_tool_call(**kwargs):
|
def _on_post_tool_call(**kwargs):
|
||||||
await _get_engine_and_call("on_post_tool_call", **kwargs)
|
_get_engine_and_call("on_post_tool_call", **kwargs)
|
||||||
|
|
||||||
# ── Registrierung via offizielle API ──────────────────────────────
|
# ── Registrierung via offizielle API ──────────────────────────────
|
||||||
ctx.register_hook("pre_gateway_dispatch", _on_pre_gateway_dispatch)
|
ctx.register_hook("pre_gateway_dispatch", _on_pre_gateway_dispatch)
|
||||||
|
|||||||
+13
-17
@@ -1691,20 +1691,18 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
self._rooms = self.rest.get_rooms()
|
self._rooms = self.rest.get_rooms()
|
||||||
logger.info("[rocketchat] REST get_rooms returned %d rooms", len(self._rooms))
|
logger.info("[rocketchat] REST get_rooms returned %d rooms", len(self._rooms))
|
||||||
|
|
||||||
# V9: Bind asyncio loop to PresenceEngine
|
# V9: Bind asyncio loop to DDP (PresenceEngine braucht keinen Loop mehr — sync Hooks)
|
||||||
try:
|
try:
|
||||||
loop = asyncio.get_running_loop()
|
loop = asyncio.get_running_loop()
|
||||||
self.ddp.bind_loop(loop)
|
self.ddp.bind_loop(loop)
|
||||||
if hasattr(self, '_presence_engine') and self._presence_engine is not None:
|
logger.info(
|
||||||
self._presence_engine.bind_loop(loop)
|
"[rocketchat] V9: DDP loop-bound: yes (loop=%s)",
|
||||||
logger.info(
|
id(loop),
|
||||||
"[rocketchat] V9: PresenceEngine loop-bound: yes (loop=%s)",
|
)
|
||||||
id(loop),
|
|
||||||
)
|
|
||||||
except RuntimeError:
|
except RuntimeError:
|
||||||
# No running event loop (e.g., in tests) — graceful degradation
|
# No running event loop (e.g., in tests) — graceful degradation
|
||||||
logger.info(
|
logger.info(
|
||||||
"[rocketchat] V9: PresenceEngine loop-bound: no "
|
"[rocketchat] V9: DDP loop-bound: no "
|
||||||
"(no running event loop)"
|
"(no running event loop)"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -1991,20 +1989,18 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
self.user = resolved.lower()
|
self.user = resolved.lower()
|
||||||
logger.info("[rocketchat] Resolved self.user from login (reconnect): %s", self.user)
|
logger.info("[rocketchat] Resolved self.user from login (reconnect): %s", self.user)
|
||||||
|
|
||||||
# V9: Re-bind asyncio loop to PresenceEngine
|
# V9: Re-bind asyncio loop to DDP (PresenceEngine braucht keinen Loop mehr — sync Hooks)
|
||||||
try:
|
try:
|
||||||
loop = asyncio.get_running_loop()
|
loop = asyncio.get_running_loop()
|
||||||
self.ddp.bind_loop(loop)
|
self.ddp.bind_loop(loop)
|
||||||
if hasattr(self, '_presence_engine') and self._presence_engine is not None:
|
logger.info(
|
||||||
self._presence_engine.bind_loop(loop)
|
"[rocketchat] V9: DDP loop-bound: yes "
|
||||||
logger.info(
|
"(reconnect, loop=%s)",
|
||||||
"[rocketchat] V9: PresenceEngine loop-bound: yes "
|
id(loop),
|
||||||
"(reconnect, loop=%s)",
|
)
|
||||||
id(loop),
|
|
||||||
)
|
|
||||||
except RuntimeError:
|
except RuntimeError:
|
||||||
logger.info(
|
logger.info(
|
||||||
"[rocketchat] V9: PresenceEngine loop-bound: no "
|
"[rocketchat] V9: DDP loop-bound: no "
|
||||||
"(reconnect, no running event loop)"
|
"(reconnect, no running event loop)"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
+126
-142
@@ -7,14 +7,23 @@ Honeymoon-Timer durch eine reine Hook-basierte State-Maschine.
|
|||||||
Prinzip: Jeder Core-Hook inkrementiert/dekrementiert einen Counter.
|
Prinzip: Jeder Core-Hook inkrementiert/dekrementiert einen Counter.
|
||||||
Status = BUSY wenn sum(counters) > 0, sonst ONLINE (nach away-grace).
|
Status = BUSY wenn sum(counters) > 0, sonst ONLINE (nach away-grace).
|
||||||
|
|
||||||
|
WICHTIG — Sync-Hooks (V9.0.1):
|
||||||
|
invoke_hook() im Core ruft Callbacks SYNCHRON auf: ret = cb(**kwargs).
|
||||||
|
Async-Callbacks werden als Coroutine-Objekt zurückgegeben aber nie awaited
|
||||||
|
→ Hook-Code wird NIE ausgeführt (Root Cause für "Andreas sieht nur GRÜN").
|
||||||
|
Daher sind ALLE Hook-Callbacks dieser Engine SYNCHRON.
|
||||||
|
Counter-Mutation ist reine Dict-Operation unter threading.Lock.
|
||||||
|
REST-Calls (users.setStatus) laufen fire-and-forget in Daemon-Threads.
|
||||||
|
away-grace nutzt threading.Timer statt asyncio.Task.
|
||||||
|
|
||||||
Zero external dependencies — stdlib only.
|
Zero external dependencies — stdlib only.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import asyncio
|
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
|
import threading
|
||||||
import time
|
import time
|
||||||
import urllib.request
|
import urllib.request
|
||||||
import urllib.error
|
import urllib.error
|
||||||
@@ -42,12 +51,17 @@ class PresenceEngine:
|
|||||||
Invarianten:
|
Invarianten:
|
||||||
I1: Status = ONLINE wenn sum(counters) == 0, sonst BUSY.
|
I1: Status = ONLINE wenn sum(counters) == 0, sonst BUSY.
|
||||||
I2: Jede Transition ONLINE↔BUSY erzeugt GENAU EINEN REST-Call.
|
I2: Jede Transition ONLINE↔BUSY erzeugt GENAU EINEN REST-Call.
|
||||||
I3: REST-Calls sind asynchron (asyncio.create_task), nie parallel.
|
I3: REST-Calls sind fire-and-forget (Daemon-Threads), nie parallel.
|
||||||
I4: Bei REST-Fehler (nicht 429): ein Retry nach 2s, dann aufgeben.
|
I4: Bei REST-Fehler (nicht 429): ein Retry nach 2s, dann aufgeben.
|
||||||
Bei 429: kein Retry, Counter bleibt — nächster Hook behebt es.
|
Bei 429: kein Retry, Counter bleibt — nächster Hook behebt es.
|
||||||
|
|
||||||
Thread-Sicherheit: transition_lock (asyncio.Lock) serialisiert alle
|
Thread-Sicherheit: transition_lock (threading.Lock) serialisiert alle
|
||||||
Counter-Mutationen und Transition-Entscheidungen.
|
Counter-Mutationen und Transition-Entscheidungen.
|
||||||
|
|
||||||
|
Sync-Hooks (V9.0.1):
|
||||||
|
Alle Hook-Callbacks sind SYNCHRON weil invoke_hook() im Core
|
||||||
|
Callbacks synchron aufruft (ret = cb(**kwargs)). Async-Callbacks
|
||||||
|
würden als Coroutine-Objekt zurückgegeben aber nie awaited.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# ── Konfigurierbare Konstanten ────────────────────────────────────────
|
# ── Konfigurierbare Konstanten ────────────────────────────────────────
|
||||||
@@ -87,16 +101,12 @@ class PresenceEngine:
|
|||||||
|
|
||||||
# ── State-Maschine ────────────────────────────────────────────────
|
# ── State-Maschine ────────────────────────────────────────────────
|
||||||
self._status: str = "ONLINE" # ONLINE | BUSY
|
self._status: str = "ONLINE" # ONLINE | BUSY
|
||||||
# F1.3: asyncio.Lock lazy-created to avoid Python 3.14 deprecation.
|
# V9.0.1: threading.Lock statt asyncio.Lock — Hooks sind synchron,
|
||||||
# Creating asyncio.Lock() outside a running event loop is deprecated
|
# invoke_hook() ruft Callbacks im aufrufenden Thread auf.
|
||||||
# in 3.14+. We defer creation to first use (always inside async context).
|
self._transition_lock: threading.Lock = threading.Lock()
|
||||||
self._transition_lock: Optional[asyncio.Lock] = None
|
|
||||||
|
|
||||||
# ── away-grace: EIN async Task für ONLINE-Transition ──────────────
|
# ── away-grace: EIN threading.Timer für ONLINE-Transition ─────────
|
||||||
self._away_grace_task: Optional[asyncio.Future] = None
|
self._away_grace_timer: Optional[threading.Timer] = None
|
||||||
|
|
||||||
# ── last-wins: laufende Transition überschreiben ──────────────────
|
|
||||||
self._pending_transition_task: Optional[asyncio.Future] = None
|
|
||||||
|
|
||||||
# ── Caching: verhindert redundante REST-Calls ─────────────────────
|
# ── Caching: verhindert redundante REST-Calls ─────────────────────
|
||||||
self._last_sent_status: Optional[str] = None
|
self._last_sent_status: Optional[str] = None
|
||||||
@@ -108,12 +118,9 @@ class PresenceEngine:
|
|||||||
self._telemetry_rest_429: int = 0
|
self._telemetry_rest_429: int = 0
|
||||||
self._telemetry_rest_errors: int = 0
|
self._telemetry_rest_errors: int = 0
|
||||||
|
|
||||||
# ── asyncio-Loop-Referenz (wird von adapter.py gesetzt) ──────────
|
|
||||||
self._loop: Optional[asyncio.AbstractEventLoop] = None
|
|
||||||
|
|
||||||
logger.info(
|
logger.info(
|
||||||
"[presence-v9] PresenceEngine initialisiert "
|
"[presence-v9] PresenceEngine initialisiert "
|
||||||
"(enabled=%s, away_grace=%.1fs, counters=%s)",
|
"(enabled=%s, away_grace=%.1fs, counters=%s, sync_hooks=true)",
|
||||||
self._enabled, self._away_grace_s, self.counters,
|
self._enabled, self._away_grace_s, self.counters,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -129,16 +136,11 @@ class PresenceEngine:
|
|||||||
logger.info("[presence-v9] PresenceEngine enabled")
|
logger.info("[presence-v9] PresenceEngine enabled")
|
||||||
|
|
||||||
def disable(self) -> None:
|
def disable(self) -> None:
|
||||||
"""Deaktiviere Presence-Updates. Cancelt away-grace-Task."""
|
"""Deaktiviere Presence-Updates. Cancelt away-grace-Timer."""
|
||||||
self._enabled = False
|
self._enabled = False
|
||||||
self._cancel_away_grace()
|
self._cancel_away_grace()
|
||||||
logger.info("[presence-v9] PresenceEngine disabled")
|
logger.info("[presence-v9] PresenceEngine disabled")
|
||||||
|
|
||||||
def bind_loop(self, loop: asyncio.AbstractEventLoop) -> None:
|
|
||||||
"""Binde die asyncio-Event-Loop für create_task."""
|
|
||||||
self._loop = loop
|
|
||||||
logger.info("[presence-v9] Loop gebunden: %s", loop)
|
|
||||||
|
|
||||||
def get_status(self) -> str:
|
def get_status(self) -> str:
|
||||||
"""Liefere den aktuellen Status (ONLINE|BUSY)."""
|
"""Liefere den aktuellen Status (ONLINE|BUSY)."""
|
||||||
return self._status
|
return self._status
|
||||||
@@ -157,40 +159,41 @@ class PresenceEngine:
|
|||||||
}
|
}
|
||||||
|
|
||||||
def shutdown(self) -> None:
|
def shutdown(self) -> None:
|
||||||
"""Clean shutdown: away-grace-Task canceln."""
|
"""Clean shutdown: away-grace-Timer canceln."""
|
||||||
self._cancel_away_grace()
|
self._cancel_away_grace()
|
||||||
if self._pending_transition_task is not None:
|
|
||||||
self._pending_transition_task.cancel()
|
|
||||||
self._pending_transition_task = None
|
|
||||||
logger.info("[presence-v9] PresenceEngine shutdown")
|
logger.info("[presence-v9] PresenceEngine shutdown")
|
||||||
|
|
||||||
# ── Hook-Callbacks (6 Core-Hooks + 2 Tool-Filter) ────────────────────
|
# ── Hook-Callbacks (6 Core-Hooks + 2 Tool-Filter) ────────────────────
|
||||||
|
# V9.0.1: ALLE Callbacks sind SYNCHRON.
|
||||||
|
# invoke_hook() im Core ruft Callbacks via ret = cb(**kwargs) auf.
|
||||||
|
# Async-Callbacks würden als Coroutine-Objekt zurückgegeben aber nie
|
||||||
|
# awaited → Hook-Code wird NIE ausgeführt.
|
||||||
|
|
||||||
async def on_pre_gateway_dispatch(self, **kwargs) -> None:
|
def on_pre_gateway_dispatch(self, **kwargs) -> None:
|
||||||
"""Hook: pre_gateway_dispatch → main_agent += 1 (ROT Start)."""
|
"""Hook: pre_gateway_dispatch → main_agent += 1 (ROT Start)."""
|
||||||
await self._apply_counter_delta("main_agent", +1)
|
self._apply_counter_delta("main_agent", +1)
|
||||||
|
|
||||||
async def on_post_llm_call(self, **kwargs) -> None:
|
def on_post_llm_call(self, **kwargs) -> None:
|
||||||
"""Hook: post_llm_call → main_agent -= 1 (ROT Ende)."""
|
"""Hook: post_llm_call → main_agent -= 1 (ROT Ende)."""
|
||||||
await self._apply_counter_delta("main_agent", -1)
|
self._apply_counter_delta("main_agent", -1)
|
||||||
|
|
||||||
async def on_subagent_start(self, **kwargs) -> None:
|
def on_subagent_start(self, **kwargs) -> None:
|
||||||
"""Hook: subagent_start → delegate_subagent += 1 (GELB Start)."""
|
"""Hook: subagent_start → delegate_subagent += 1 (GELB Start)."""
|
||||||
await self._apply_counter_delta("delegate_subagent", +1)
|
self._apply_counter_delta("delegate_subagent", +1)
|
||||||
|
|
||||||
async def on_subagent_stop(self, **kwargs) -> None:
|
def on_subagent_stop(self, **kwargs) -> None:
|
||||||
"""Hook: subagent_stop → delegate_subagent -= 1 (GELB Ende)."""
|
"""Hook: subagent_stop → delegate_subagent -= 1 (GELB Ende)."""
|
||||||
await self._apply_counter_delta("delegate_subagent", -1)
|
self._apply_counter_delta("delegate_subagent", -1)
|
||||||
|
|
||||||
async def on_session_start(self, **kwargs) -> None:
|
def on_session_start(self, **kwargs) -> None:
|
||||||
"""Hook: on_session_start → chat_profile += 1 (GELB Start)."""
|
"""Hook: on_session_start → chat_profile += 1 (GELB Start)."""
|
||||||
await self._apply_counter_delta("chat_profile", +1)
|
self._apply_counter_delta("chat_profile", +1)
|
||||||
|
|
||||||
async def on_session_end(self, **kwargs) -> None:
|
def on_session_end(self, **kwargs) -> None:
|
||||||
"""Hook: on_session_end → chat_profile -= 1 (GELB Ende)."""
|
"""Hook: on_session_end → chat_profile -= 1 (GELB Ende)."""
|
||||||
await self._apply_counter_delta("chat_profile", -1)
|
self._apply_counter_delta("chat_profile", -1)
|
||||||
|
|
||||||
async def on_pre_tool_call(self, **kwargs) -> None:
|
def on_pre_tool_call(self, **kwargs) -> None:
|
||||||
"""Hook: pre_tool_call → background_term += 1 wenn terminal(background=true).
|
"""Hook: pre_tool_call → background_term += 1 wenn terminal(background=true).
|
||||||
|
|
||||||
Workaround für O-1: terminal(background=true) hat keinen eigenen Core-Hook.
|
Workaround für O-1: terminal(background=true) hat keinen eigenen Core-Hook.
|
||||||
@@ -199,31 +202,23 @@ class PresenceEngine:
|
|||||||
tool_name = kwargs.get("tool_name", "")
|
tool_name = kwargs.get("tool_name", "")
|
||||||
args = kwargs.get("args", {}) or {}
|
args = kwargs.get("args", {}) or {}
|
||||||
if tool_name == "terminal" and args.get("background") is True:
|
if tool_name == "terminal" and args.get("background") is True:
|
||||||
await self._apply_counter_delta("background_term", +1)
|
self._apply_counter_delta("background_term", +1)
|
||||||
|
|
||||||
async def on_post_tool_call(self, **kwargs) -> None:
|
def on_post_tool_call(self, **kwargs) -> None:
|
||||||
"""Hook: post_tool_call → background_term -= 1 wenn terminal(background=true)."""
|
"""Hook: post_tool_call → background_term -= 1 wenn terminal(background=true)."""
|
||||||
tool_name = kwargs.get("tool_name", "")
|
tool_name = kwargs.get("tool_name", "")
|
||||||
args = kwargs.get("args", {}) or {}
|
args = kwargs.get("args", {}) or {}
|
||||||
if tool_name == "terminal" and args.get("background") is True:
|
if tool_name == "terminal" and args.get("background") is True:
|
||||||
await self._apply_counter_delta("background_term", -1)
|
self._apply_counter_delta("background_term", -1)
|
||||||
|
|
||||||
# ── Interne State-Maschine ───────────────────────────────────────────
|
# ── Interne State-Maschine ───────────────────────────────────────────
|
||||||
|
|
||||||
def _get_lock(self) -> asyncio.Lock:
|
def _apply_counter_delta(self, counter_name: str, delta: int) -> None:
|
||||||
"""Lazy-create asyncio.Lock (F1.3: Python 3.14 forward-compat).
|
|
||||||
|
|
||||||
Creating asyncio.Lock() outside a running event loop is deprecated
|
|
||||||
in Python 3.14+. This method defers creation to first use, which
|
|
||||||
always happens inside an async context (Hook-Callback).
|
|
||||||
"""
|
|
||||||
if self._transition_lock is None:
|
|
||||||
self._transition_lock = asyncio.Lock()
|
|
||||||
return self._transition_lock
|
|
||||||
|
|
||||||
async def _apply_counter_delta(self, counter_name: str, delta: int) -> None:
|
|
||||||
"""Atomar: Counter mutieren, Summe prüfen, ggf. Transition auslösen.
|
"""Atomar: Counter mutieren, Summe prüfen, ggf. Transition auslösen.
|
||||||
|
|
||||||
|
V9.0.1: Synchron unter threading.Lock. invoke_hook() ruft Callbacks
|
||||||
|
synchron auf — kein asyncio-Kontext verfügbar.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
counter_name: Schlüssel im counters-Dict.
|
counter_name: Schlüssel im counters-Dict.
|
||||||
delta: +1 oder -1.
|
delta: +1 oder -1.
|
||||||
@@ -231,7 +226,7 @@ class PresenceEngine:
|
|||||||
if not self._enabled:
|
if not self._enabled:
|
||||||
return
|
return
|
||||||
|
|
||||||
async with self._get_lock():
|
with self._transition_lock:
|
||||||
# ── Counter mutieren ─────────────────────────────────────────
|
# ── Counter mutieren ─────────────────────────────────────────
|
||||||
old_value = self.counters[counter_name]
|
old_value = self.counters[counter_name]
|
||||||
new_value = old_value + delta
|
new_value = old_value + delta
|
||||||
@@ -255,7 +250,7 @@ class PresenceEngine:
|
|||||||
self._status = "BUSY"
|
self._status = "BUSY"
|
||||||
# away-grace canceln (falls aktiv)
|
# away-grace canceln (falls aktiv)
|
||||||
self._cancel_away_grace()
|
self._cancel_away_grace()
|
||||||
# Transition sofort auslösen
|
# Transition sofort auslösen (fire-and-forget)
|
||||||
self._schedule_transition("busy", self._build_busy_message())
|
self._schedule_transition("busy", self._build_busy_message())
|
||||||
elif total == 0 and self._status == "BUSY":
|
elif total == 0 and self._status == "BUSY":
|
||||||
# BUSY → ONLINE (mit away-grace)
|
# BUSY → ONLINE (mit away-grace)
|
||||||
@@ -285,39 +280,17 @@ class PresenceEngine:
|
|||||||
else:
|
else:
|
||||||
return f"beschaeftigt — {len(active)} Aufgaben"
|
return f"beschaeftigt — {len(active)} Aufgaben"
|
||||||
|
|
||||||
# ── schedule_transition: last-wins, asyncio.create_task ──────────────
|
# ── schedule_transition: fire-and-forget via Daemon-Thread ────────────
|
||||||
|
|
||||||
def _schedule_transition(self, status: str, message: str) -> None:
|
def _schedule_transition(self, status: str, message: str) -> None:
|
||||||
"""Plane einen REST-Status-Call. Last-wins: überschreibt vorherigen.
|
"""Plane einen REST-Status-Call via fire-and-forget Daemon-Thread.
|
||||||
|
|
||||||
Args:
|
V9.0.1: Statt asyncio.create_task() nutzen wir threading.Thread(daemon=True).
|
||||||
status: 'online' oder 'busy'.
|
invoke_hook() ist synchron — es gibt keinen asyncio-Loop im Hook-Kontext.
|
||||||
message: Status-Message-Text.
|
|
||||||
"""
|
|
||||||
if self._loop is None:
|
|
||||||
logger.warning(
|
|
||||||
"[presence-v9] Kein asyncio-Loop gebunden — "
|
|
||||||
"Transition %s verworfen", status
|
|
||||||
)
|
|
||||||
return
|
|
||||||
|
|
||||||
# Vorherige pending Transition canceln (last-wins)
|
Last-wins: Caching (_last_sent_status/_last_sent_message) verhindert
|
||||||
if self._pending_transition_task is not None:
|
redundante REST-Calls. Der letzte Thread der durchkommt setzt den
|
||||||
self._pending_transition_task.cancel()
|
finalen Status.
|
||||||
self._pending_transition_task = None
|
|
||||||
|
|
||||||
# Neue Transition als asyncio-Task starten
|
|
||||||
self._pending_transition_task = asyncio.run_coroutine_threadsafe(
|
|
||||||
self._send_transition(status, message),
|
|
||||||
self._loop,
|
|
||||||
)
|
|
||||||
logger.debug(
|
|
||||||
"[presence-v9] Transition geplant: %s (message=%s)",
|
|
||||||
status, message[:50] if message else "",
|
|
||||||
)
|
|
||||||
|
|
||||||
async def _send_transition(self, status: str, message: str) -> None:
|
|
||||||
"""Sende REST-Status-Call (async, auf dem Event-Loop).
|
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
status: 'online' oder 'busy'.
|
status: 'online' oder 'busy'.
|
||||||
@@ -330,59 +303,79 @@ class PresenceEngine:
|
|||||||
)
|
)
|
||||||
return
|
return
|
||||||
|
|
||||||
success = await self._rest_set_status(status, message)
|
# Fire-and-forget: REST-Call in Daemon-Thread
|
||||||
|
thread = threading.Thread(
|
||||||
|
target=self._send_transition,
|
||||||
|
args=(status, message),
|
||||||
|
daemon=True,
|
||||||
|
name=f"presence-transition-{status}",
|
||||||
|
)
|
||||||
|
thread.start()
|
||||||
|
logger.debug(
|
||||||
|
"[presence-v9] Transition geplant: %s (message=%s)",
|
||||||
|
status, message[:50] if message else "",
|
||||||
|
)
|
||||||
|
|
||||||
|
def _send_transition(self, status: str, message: str) -> None:
|
||||||
|
"""Sende REST-Status-Call (synchron, läuft in Daemon-Thread).
|
||||||
|
|
||||||
|
V9.0.1: Läuft in einem fire-and-forget Daemon-Thread.
|
||||||
|
Kein asyncio — urllib.request ist synchron.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
status: 'online' oder 'busy'.
|
||||||
|
message: Status-Message-Text.
|
||||||
|
"""
|
||||||
|
success = self._rest_set_status(status, message)
|
||||||
if success:
|
if success:
|
||||||
self._last_sent_status = status
|
self._last_sent_status = status
|
||||||
self._last_sent_message = message
|
self._last_sent_message = message
|
||||||
|
|
||||||
# ── away-grace: EIN async Task (2s), gecancelt bei nächstem BUSY ─────
|
# ── away-grace: threading.Timer (2s), gecancelt bei nächstem BUSY ─────
|
||||||
|
|
||||||
def _schedule_away_grace(self) -> None:
|
def _schedule_away_grace(self) -> None:
|
||||||
"""Starte away-grace-Task: nach N Sekunden auf ONLINE setzen.
|
"""Starte away-grace-Timer: nach N Sekunden auf ONLINE setzen.
|
||||||
|
|
||||||
|
V9.0.1: threading.Timer statt asyncio.Task.
|
||||||
Wird gecancelt wenn vor Ablauf ein neuer BUSY-Hook feuert.
|
Wird gecancelt wenn vor Ablauf ein neuer BUSY-Hook feuert.
|
||||||
"""
|
"""
|
||||||
if self._loop is None:
|
|
||||||
logger.warning("[presence-v9] Kein Loop — away-grace übersprungen")
|
|
||||||
return
|
|
||||||
|
|
||||||
# Vorherigen away-grace canceln
|
# Vorherigen away-grace canceln
|
||||||
self._cancel_away_grace()
|
self._cancel_away_grace()
|
||||||
|
|
||||||
# Neuen away-grace starten
|
# Neuen away-grace starten
|
||||||
self._away_grace_task = asyncio.run_coroutine_threadsafe(
|
self._away_grace_timer = threading.Timer(
|
||||||
self._away_grace_timer(),
|
self._away_grace_s,
|
||||||
self._loop,
|
self._on_away_grace_expired,
|
||||||
)
|
)
|
||||||
|
self._away_grace_timer.daemon = True
|
||||||
|
self._away_grace_timer.start()
|
||||||
logger.debug(
|
logger.debug(
|
||||||
"[presence-v9] away-grace gestartet (%.1fs)", self._away_grace_s
|
"[presence-v9] away-grace gestartet (%.1fs)", self._away_grace_s
|
||||||
)
|
)
|
||||||
|
|
||||||
def _cancel_away_grace(self) -> None:
|
def _cancel_away_grace(self) -> None:
|
||||||
"""Cancel den laufenden away-grace-Task."""
|
"""Cancel den laufenden away-grace-Timer."""
|
||||||
if self._away_grace_task is not None:
|
if self._away_grace_timer is not None:
|
||||||
self._away_grace_task.cancel()
|
self._away_grace_timer.cancel()
|
||||||
self._away_grace_task = None
|
self._away_grace_timer = None
|
||||||
logger.debug("[presence-v9] away-grace gecancelt")
|
logger.debug("[presence-v9] away-grace gecancelt")
|
||||||
|
|
||||||
async def _away_grace_timer(self) -> None:
|
def _on_away_grace_expired(self) -> None:
|
||||||
"""away-grace: warte N Sekunden, dann sende ONLINE-Transition.
|
"""Callback für away-grace-Timer: sende ONLINE-Transition.
|
||||||
|
|
||||||
Läuft auf dem asyncio-Event-Loop. Wird von _cancel_away_grace()
|
V9.0.1: Wird vom threading.Timer im Timer-Thread aufgerufen.
|
||||||
gecancelt wenn vor Ablauf ein BUSY-Hook feuert.
|
|
||||||
"""
|
"""
|
||||||
try:
|
logger.debug("[presence-v9] away-grace abgelaufen — sende ONLINE")
|
||||||
await asyncio.sleep(self._away_grace_s)
|
self._schedule_transition("online", "")
|
||||||
# Nach Ablauf: ONLINE-Transition senden
|
|
||||||
self._schedule_transition("online", "")
|
|
||||||
except asyncio.CancelledError:
|
|
||||||
logger.debug("[presence-v9] away-grace-Task gecancelt")
|
|
||||||
raise
|
|
||||||
|
|
||||||
# ── REST-API-Call ────────────────────────────────────────────────────
|
# ── REST-API-Call ────────────────────────────────────────────────────
|
||||||
|
|
||||||
async def _rest_set_status(self, status: str, message: str) -> bool:
|
def _rest_set_status(self, status: str, message: str) -> bool:
|
||||||
"""Sende users.setStatus via REST (async).
|
"""Sende users.setStatus via REST (synchron).
|
||||||
|
|
||||||
|
V9.0.1: Synchron — wird aus einem fire-and-forget Daemon-Thread
|
||||||
|
aufgerufen. Kein asyncio nötig, urllib.request ist von Natur aus
|
||||||
|
synchron.
|
||||||
|
|
||||||
POST /api/v1/users.setStatus
|
POST /api/v1/users.setStatus
|
||||||
Body: {"status": "...", "message": "..."}
|
Body: {"status": "...", "message": "..."}
|
||||||
@@ -402,24 +395,19 @@ class PresenceEngine:
|
|||||||
|
|
||||||
self._telemetry_rest_calls += 1
|
self._telemetry_rest_calls += 1
|
||||||
|
|
||||||
try:
|
data = {"status": status}
|
||||||
data = {"status": status}
|
if message:
|
||||||
if message:
|
data["message"] = message
|
||||||
data["message"] = message
|
|
||||||
|
|
||||||
# REST-Call in einem Thread ausführen (urllib ist synchron)
|
try:
|
||||||
loop = asyncio.get_running_loop()
|
self._rest._request(
|
||||||
await loop.run_in_executor(
|
"POST",
|
||||||
None,
|
"/api/v1/users.setStatus",
|
||||||
lambda: self._rest._request(
|
headers={
|
||||||
"POST",
|
"X-Auth-Token": self._rest.auth_token,
|
||||||
"/api/v1/users.setStatus",
|
"X-User-Id": self._rest.user_id,
|
||||||
headers={
|
},
|
||||||
"X-Auth-Token": self._rest.auth_token,
|
data=data,
|
||||||
"X-User-Id": self._rest.user_id,
|
|
||||||
},
|
|
||||||
data=data,
|
|
||||||
),
|
|
||||||
)
|
)
|
||||||
|
|
||||||
self._telemetry_rest_success += 1
|
self._telemetry_rest_success += 1
|
||||||
@@ -447,19 +435,15 @@ class PresenceEngine:
|
|||||||
|
|
||||||
# Ein Retry nach 2s
|
# Ein Retry nach 2s
|
||||||
try:
|
try:
|
||||||
await asyncio.sleep(self.RETRY_DELAY_S)
|
time.sleep(self.RETRY_DELAY_S)
|
||||||
loop = asyncio.get_running_loop()
|
self._rest._request(
|
||||||
await loop.run_in_executor(
|
"POST",
|
||||||
None,
|
"/api/v1/users.setStatus",
|
||||||
lambda: self._rest._request(
|
headers={
|
||||||
"POST",
|
"X-Auth-Token": self._rest.auth_token,
|
||||||
"/api/v1/users.setStatus",
|
"X-User-Id": self._rest.user_id,
|
||||||
headers={
|
},
|
||||||
"X-Auth-Token": self._rest.auth_token,
|
data=data,
|
||||||
"X-User-Id": self._rest.user_id,
|
|
||||||
},
|
|
||||||
data=data,
|
|
||||||
),
|
|
||||||
)
|
)
|
||||||
self._telemetry_rest_success += 1
|
self._telemetry_rest_success += 1
|
||||||
logger.info(
|
logger.info(
|
||||||
|
|||||||
@@ -6,17 +6,20 @@ Tests für die ereignisgesteuerte V9 PresenceEngine:
|
|||||||
- 4 Counter-Tests (inkrement, dekrement, sum, transition)
|
- 4 Counter-Tests (inkrement, dekrement, sum, transition)
|
||||||
- 3 Race-Tests (parallel Hooks, last-wins, away-grace cancel)
|
- 3 Race-Tests (parallel Hooks, last-wins, away-grace cancel)
|
||||||
|
|
||||||
|
V9.0.1: Alle Tests sind SYNCHRON — invoke_hook() ruft Callbacks synchron auf.
|
||||||
|
Kein asyncio, kein loop.run_until_complete(), kein await.
|
||||||
|
|
||||||
V8.x-Tests sind am Ende als skipped markiert (V8.x removed in V9).
|
V8.x-Tests sind am Ende als skipped markiert (V8.x removed in V9).
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import asyncio
|
|
||||||
import sys
|
import sys
|
||||||
import os
|
import os
|
||||||
import time
|
import time
|
||||||
|
import threading
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from unittest.mock import MagicMock, patch, AsyncMock
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
@@ -38,15 +41,15 @@ def _make_mock_rest():
|
|||||||
|
|
||||||
|
|
||||||
def _make_engine(rest=None, enabled=True, away_grace_s=0.1):
|
def _make_engine(rest=None, enabled=True, away_grace_s=0.1):
|
||||||
"""Erzeuge eine PresenceEngine V9 für Tests (mit kurzem away-grace)."""
|
"""Erzeuge eine PresenceEngine V9 für Tests (mit kurzem away-grace).
|
||||||
|
|
||||||
|
V9.0.1: Kein asyncio-Loop nötig — Hooks sind synchron.
|
||||||
|
"""
|
||||||
from plugin.archivar.presence_engine import PresenceEngine
|
from plugin.archivar.presence_engine import PresenceEngine
|
||||||
if rest is None:
|
if rest is None:
|
||||||
rest = _make_mock_rest()
|
rest = _make_mock_rest()
|
||||||
engine = PresenceEngine(rest=rest, enabled=enabled, away_grace_s=away_grace_s)
|
engine = PresenceEngine(rest=rest, enabled=enabled, away_grace_s=away_grace_s)
|
||||||
# Binde eine echte asyncio-Loop für Tests
|
return engine
|
||||||
loop = asyncio.new_event_loop()
|
|
||||||
engine.bind_loop(loop)
|
|
||||||
return engine, loop
|
|
||||||
|
|
||||||
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
@@ -58,32 +61,22 @@ class TestHookPreGatewayDispatch:
|
|||||||
|
|
||||||
def test_pre_gateway_dispatch_increments_main_agent(self):
|
def test_pre_gateway_dispatch_increments_main_agent(self):
|
||||||
"""Hook feuert → main_agent-Counter steigt auf 1."""
|
"""Hook feuert → main_agent-Counter steigt auf 1."""
|
||||||
engine, loop = _make_engine()
|
engine = _make_engine()
|
||||||
|
engine.on_pre_gateway_dispatch()
|
||||||
async def run():
|
counters = engine.get_counters()
|
||||||
await engine.on_pre_gateway_dispatch()
|
|
||||||
return engine.get_counters()
|
|
||||||
|
|
||||||
counters = loop.run_until_complete(run())
|
|
||||||
assert counters["main_agent"] == 1
|
assert counters["main_agent"] == 1
|
||||||
assert counters["delegate_subagent"] == 0
|
assert counters["delegate_subagent"] == 0
|
||||||
assert counters["chat_profile"] == 0
|
assert counters["chat_profile"] == 0
|
||||||
assert counters["background_term"] == 0
|
assert counters["background_term"] == 0
|
||||||
assert engine.get_status() == "BUSY"
|
assert engine.get_status() == "BUSY"
|
||||||
loop.close()
|
|
||||||
|
|
||||||
def test_pre_gateway_dispatch_disabled_engine_noop(self):
|
def test_pre_gateway_dispatch_disabled_engine_noop(self):
|
||||||
"""Deaktivierte Engine → Hook ist No-Op."""
|
"""Deaktivierte Engine → Hook ist No-Op."""
|
||||||
engine, loop = _make_engine(enabled=False)
|
engine = _make_engine(enabled=False)
|
||||||
|
engine.on_pre_gateway_dispatch()
|
||||||
async def run():
|
counters = engine.get_counters()
|
||||||
await engine.on_pre_gateway_dispatch()
|
|
||||||
return engine.get_counters()
|
|
||||||
|
|
||||||
counters = loop.run_until_complete(run())
|
|
||||||
assert counters["main_agent"] == 0
|
assert counters["main_agent"] == 0
|
||||||
assert engine.get_status() == "ONLINE"
|
assert engine.get_status() == "ONLINE"
|
||||||
loop.close()
|
|
||||||
|
|
||||||
|
|
||||||
class TestHookPostLlmCall:
|
class TestHookPostLlmCall:
|
||||||
@@ -91,108 +84,73 @@ class TestHookPostLlmCall:
|
|||||||
|
|
||||||
def test_post_llm_call_decrements_main_agent(self):
|
def test_post_llm_call_decrements_main_agent(self):
|
||||||
"""Nach pre_gateway_dispatch + post_llm_call → Counter wieder 0."""
|
"""Nach pre_gateway_dispatch + post_llm_call → Counter wieder 0."""
|
||||||
engine, loop = _make_engine()
|
engine = _make_engine()
|
||||||
|
engine.on_pre_gateway_dispatch()
|
||||||
async def run():
|
engine.on_post_llm_call()
|
||||||
await engine.on_pre_gateway_dispatch()
|
# away-grace abwarten
|
||||||
await engine.on_post_llm_call()
|
time.sleep(engine._away_grace_s + 0.05)
|
||||||
# away-grace abwarten
|
counters = engine.get_counters()
|
||||||
await asyncio.sleep(engine._away_grace_s + 0.05)
|
|
||||||
return engine.get_counters(), engine.get_status()
|
|
||||||
|
|
||||||
counters, status = loop.run_until_complete(run())
|
|
||||||
assert counters["main_agent"] == 0
|
assert counters["main_agent"] == 0
|
||||||
assert status == "ONLINE"
|
assert engine.get_status() == "ONLINE"
|
||||||
loop.close()
|
|
||||||
|
|
||||||
def test_post_llm_call_without_pre_gateway_no_negative(self):
|
def test_post_llm_call_without_pre_gateway_no_negative(self):
|
||||||
"""post_llm_call ohne vorheriges pre_gateway → Counter bleibt 0 (kein negativ)."""
|
"""post_llm_call ohne vorheriges pre_gateway → Counter bleibt 0 (kein negativ)."""
|
||||||
engine, loop = _make_engine()
|
engine = _make_engine()
|
||||||
|
engine.on_post_llm_call()
|
||||||
async def run():
|
counters = engine.get_counters()
|
||||||
await engine.on_post_llm_call()
|
|
||||||
return engine.get_counters()
|
|
||||||
|
|
||||||
counters = loop.run_until_complete(run())
|
|
||||||
assert counters["main_agent"] == 0
|
assert counters["main_agent"] == 0
|
||||||
loop.close()
|
|
||||||
|
|
||||||
|
|
||||||
class TestHookSubagentStartStop:
|
class TestHookSubagentStartStop:
|
||||||
"""subagent_start/stop → delegate_subagent += 1 / -= 1 (GELB)."""
|
"""subagent_start/stop → delegate_subagent += 1 / -= 1 (GELB)."""
|
||||||
|
|
||||||
def test_subagent_start_increments_delegate(self):
|
def test_subagent_start_increments_delegate(self):
|
||||||
engine, loop = _make_engine()
|
engine = _make_engine()
|
||||||
|
engine.on_subagent_start()
|
||||||
async def run():
|
counters = engine.get_counters()
|
||||||
await engine.on_subagent_start()
|
|
||||||
return engine.get_counters()
|
|
||||||
|
|
||||||
counters = loop.run_until_complete(run())
|
|
||||||
assert counters["delegate_subagent"] == 1
|
assert counters["delegate_subagent"] == 1
|
||||||
assert engine.get_status() == "BUSY"
|
assert engine.get_status() == "BUSY"
|
||||||
loop.close()
|
|
||||||
|
|
||||||
def test_subagent_start_stop_balanced(self):
|
def test_subagent_start_stop_balanced(self):
|
||||||
engine, loop = _make_engine()
|
engine = _make_engine()
|
||||||
|
engine.on_subagent_start()
|
||||||
async def run():
|
engine.on_subagent_stop()
|
||||||
await engine.on_subagent_start()
|
time.sleep(engine._away_grace_s + 0.05)
|
||||||
await engine.on_subagent_stop()
|
counters = engine.get_counters()
|
||||||
await asyncio.sleep(engine._away_grace_s + 0.05)
|
|
||||||
return engine.get_counters(), engine.get_status()
|
|
||||||
|
|
||||||
counters, status = loop.run_until_complete(run())
|
|
||||||
assert counters["delegate_subagent"] == 0
|
assert counters["delegate_subagent"] == 0
|
||||||
assert status == "ONLINE"
|
assert engine.get_status() == "ONLINE"
|
||||||
loop.close()
|
|
||||||
|
|
||||||
def test_multiple_subagents_counter_accurate(self):
|
def test_multiple_subagents_counter_accurate(self):
|
||||||
"""3 Subagenten starten, 2 stoppen → Counter = 1, Status = BUSY."""
|
"""3 Subagenten starten, 2 stoppen → Counter = 1, Status = BUSY."""
|
||||||
engine, loop = _make_engine()
|
engine = _make_engine()
|
||||||
|
engine.on_subagent_start()
|
||||||
async def run():
|
engine.on_subagent_start()
|
||||||
await engine.on_subagent_start()
|
engine.on_subagent_start()
|
||||||
await engine.on_subagent_start()
|
engine.on_subagent_stop()
|
||||||
await engine.on_subagent_start()
|
engine.on_subagent_stop()
|
||||||
await engine.on_subagent_stop()
|
counters = engine.get_counters()
|
||||||
await engine.on_subagent_stop()
|
|
||||||
return engine.get_counters(), engine.get_status()
|
|
||||||
|
|
||||||
counters, status = loop.run_until_complete(run())
|
|
||||||
assert counters["delegate_subagent"] == 1
|
assert counters["delegate_subagent"] == 1
|
||||||
assert status == "BUSY"
|
assert engine.get_status() == "BUSY"
|
||||||
loop.close()
|
|
||||||
|
|
||||||
|
|
||||||
class TestHookSessionStartEnd:
|
class TestHookSessionStartEnd:
|
||||||
"""on_session_start/end → chat_profile += 1 / -= 1 (GELB)."""
|
"""on_session_start/end → chat_profile += 1 / -= 1 (GELB)."""
|
||||||
|
|
||||||
def test_session_start_increments_chat_profile(self):
|
def test_session_start_increments_chat_profile(self):
|
||||||
engine, loop = _make_engine()
|
engine = _make_engine()
|
||||||
|
engine.on_session_start()
|
||||||
async def run():
|
counters = engine.get_counters()
|
||||||
await engine.on_session_start()
|
|
||||||
return engine.get_counters()
|
|
||||||
|
|
||||||
counters = loop.run_until_complete(run())
|
|
||||||
assert counters["chat_profile"] == 1
|
assert counters["chat_profile"] == 1
|
||||||
assert engine.get_status() == "BUSY"
|
assert engine.get_status() == "BUSY"
|
||||||
loop.close()
|
|
||||||
|
|
||||||
def test_session_start_end_balanced(self):
|
def test_session_start_end_balanced(self):
|
||||||
engine, loop = _make_engine()
|
engine = _make_engine()
|
||||||
|
engine.on_session_start()
|
||||||
async def run():
|
engine.on_session_end()
|
||||||
await engine.on_session_start()
|
time.sleep(engine._away_grace_s + 0.05)
|
||||||
await engine.on_session_end()
|
counters = engine.get_counters()
|
||||||
await asyncio.sleep(engine._away_grace_s + 0.05)
|
|
||||||
return engine.get_counters(), engine.get_status()
|
|
||||||
|
|
||||||
counters, status = loop.run_until_complete(run())
|
|
||||||
assert counters["chat_profile"] == 0
|
assert counters["chat_profile"] == 0
|
||||||
assert status == "ONLINE"
|
assert engine.get_status() == "ONLINE"
|
||||||
loop.close()
|
|
||||||
|
|
||||||
|
|
||||||
class TestHookBackgroundTerminal:
|
class TestHookBackgroundTerminal:
|
||||||
@@ -200,70 +158,50 @@ class TestHookBackgroundTerminal:
|
|||||||
|
|
||||||
def test_pre_tool_call_terminal_bg_increments(self):
|
def test_pre_tool_call_terminal_bg_increments(self):
|
||||||
"""pre_tool_call mit tool_name='terminal' + background=True → Counter steigt."""
|
"""pre_tool_call mit tool_name='terminal' + background=True → Counter steigt."""
|
||||||
engine, loop = _make_engine()
|
engine = _make_engine()
|
||||||
|
engine.on_pre_tool_call(
|
||||||
async def run():
|
tool_name="terminal",
|
||||||
await engine.on_pre_tool_call(
|
args={"background": True, "command": "sleep 10"},
|
||||||
tool_name="terminal",
|
)
|
||||||
args={"background": True, "command": "sleep 10"},
|
counters = engine.get_counters()
|
||||||
)
|
|
||||||
return engine.get_counters()
|
|
||||||
|
|
||||||
counters = loop.run_until_complete(run())
|
|
||||||
assert counters["background_term"] == 1
|
assert counters["background_term"] == 1
|
||||||
assert engine.get_status() == "BUSY"
|
assert engine.get_status() == "BUSY"
|
||||||
loop.close()
|
|
||||||
|
|
||||||
def test_pre_tool_call_non_terminal_noop(self):
|
def test_pre_tool_call_non_terminal_noop(self):
|
||||||
"""pre_tool_call mit tool_name='read_file' → kein Counter-Change."""
|
"""pre_tool_call mit tool_name='read_file' → kein Counter-Change."""
|
||||||
engine, loop = _make_engine()
|
engine = _make_engine()
|
||||||
|
engine.on_pre_tool_call(
|
||||||
async def run():
|
tool_name="read_file",
|
||||||
await engine.on_pre_tool_call(
|
args={"path": "/tmp/test"},
|
||||||
tool_name="read_file",
|
)
|
||||||
args={"path": "/tmp/test"},
|
counters = engine.get_counters()
|
||||||
)
|
|
||||||
return engine.get_counters()
|
|
||||||
|
|
||||||
counters = loop.run_until_complete(run())
|
|
||||||
assert counters["background_term"] == 0
|
assert counters["background_term"] == 0
|
||||||
assert engine.get_status() == "ONLINE"
|
assert engine.get_status() == "ONLINE"
|
||||||
loop.close()
|
|
||||||
|
|
||||||
def test_pre_tool_call_terminal_no_background_noop(self):
|
def test_pre_tool_call_terminal_no_background_noop(self):
|
||||||
"""pre_tool_call mit terminal aber background=False → kein Counter-Change."""
|
"""pre_tool_call mit terminal aber background=False → kein Counter-Change."""
|
||||||
engine, loop = _make_engine()
|
engine = _make_engine()
|
||||||
|
engine.on_pre_tool_call(
|
||||||
async def run():
|
tool_name="terminal",
|
||||||
await engine.on_pre_tool_call(
|
args={"background": False, "command": "echo hi"},
|
||||||
tool_name="terminal",
|
)
|
||||||
args={"background": False, "command": "echo hi"},
|
counters = engine.get_counters()
|
||||||
)
|
|
||||||
return engine.get_counters()
|
|
||||||
|
|
||||||
counters = loop.run_until_complete(run())
|
|
||||||
assert counters["background_term"] == 0
|
assert counters["background_term"] == 0
|
||||||
loop.close()
|
|
||||||
|
|
||||||
def test_post_tool_call_terminal_bg_decrements(self):
|
def test_post_tool_call_terminal_bg_decrements(self):
|
||||||
engine, loop = _make_engine()
|
engine = _make_engine()
|
||||||
|
engine.on_pre_tool_call(
|
||||||
async def run():
|
tool_name="terminal",
|
||||||
await engine.on_pre_tool_call(
|
args={"background": True, "command": "sleep 10"},
|
||||||
tool_name="terminal",
|
)
|
||||||
args={"background": True, "command": "sleep 10"},
|
engine.on_post_tool_call(
|
||||||
)
|
tool_name="terminal",
|
||||||
await engine.on_post_tool_call(
|
args={"background": True, "command": "sleep 10"},
|
||||||
tool_name="terminal",
|
)
|
||||||
args={"background": True, "command": "sleep 10"},
|
time.sleep(engine._away_grace_s + 0.05)
|
||||||
)
|
counters = engine.get_counters()
|
||||||
await asyncio.sleep(engine._away_grace_s + 0.05)
|
|
||||||
return engine.get_counters(), engine.get_status()
|
|
||||||
|
|
||||||
counters, status = loop.run_until_complete(run())
|
|
||||||
assert counters["background_term"] == 0
|
assert counters["background_term"] == 0
|
||||||
assert status == "ONLINE"
|
assert engine.get_status() == "ONLINE"
|
||||||
loop.close()
|
|
||||||
|
|
||||||
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
@@ -274,146 +212,86 @@ class TestCounterIncrement:
|
|||||||
"""Counter-Inkrement: +1 auf jeden Counter-Typ."""
|
"""Counter-Inkrement: +1 auf jeden Counter-Typ."""
|
||||||
|
|
||||||
def test_main_agent_increment(self):
|
def test_main_agent_increment(self):
|
||||||
engine, loop = _make_engine()
|
engine = _make_engine()
|
||||||
|
engine.on_pre_gateway_dispatch()
|
||||||
async def run():
|
assert engine.get_counters()["main_agent"] == 1
|
||||||
await engine.on_pre_gateway_dispatch()
|
|
||||||
return engine.get_counters()["main_agent"]
|
|
||||||
|
|
||||||
val = loop.run_until_complete(run())
|
|
||||||
assert val == 1
|
|
||||||
loop.close()
|
|
||||||
|
|
||||||
def test_delegate_subagent_increment(self):
|
def test_delegate_subagent_increment(self):
|
||||||
engine, loop = _make_engine()
|
engine = _make_engine()
|
||||||
|
engine.on_subagent_start()
|
||||||
async def run():
|
assert engine.get_counters()["delegate_subagent"] == 1
|
||||||
await engine.on_subagent_start()
|
|
||||||
return engine.get_counters()["delegate_subagent"]
|
|
||||||
|
|
||||||
val = loop.run_until_complete(run())
|
|
||||||
assert val == 1
|
|
||||||
loop.close()
|
|
||||||
|
|
||||||
def test_chat_profile_increment(self):
|
def test_chat_profile_increment(self):
|
||||||
engine, loop = _make_engine()
|
engine = _make_engine()
|
||||||
|
engine.on_session_start()
|
||||||
async def run():
|
assert engine.get_counters()["chat_profile"] == 1
|
||||||
await engine.on_session_start()
|
|
||||||
return engine.get_counters()["chat_profile"]
|
|
||||||
|
|
||||||
val = loop.run_until_complete(run())
|
|
||||||
assert val == 1
|
|
||||||
loop.close()
|
|
||||||
|
|
||||||
def test_background_term_increment(self):
|
def test_background_term_increment(self):
|
||||||
engine, loop = _make_engine()
|
engine = _make_engine()
|
||||||
|
engine.on_pre_tool_call(
|
||||||
async def run():
|
tool_name="terminal",
|
||||||
await engine.on_pre_tool_call(
|
args={"background": True},
|
||||||
tool_name="terminal",
|
)
|
||||||
args={"background": True},
|
assert engine.get_counters()["background_term"] == 1
|
||||||
)
|
|
||||||
return engine.get_counters()["background_term"]
|
|
||||||
|
|
||||||
val = loop.run_until_complete(run())
|
|
||||||
assert val == 1
|
|
||||||
loop.close()
|
|
||||||
|
|
||||||
|
|
||||||
class TestCounterDecrement:
|
class TestCounterDecrement:
|
||||||
"""Counter-Dekrement: -1, kein negativ."""
|
"""Counter-Dekrement: -1, kein negativ."""
|
||||||
|
|
||||||
def test_decrement_to_zero(self):
|
def test_decrement_to_zero(self):
|
||||||
engine, loop = _make_engine()
|
engine = _make_engine()
|
||||||
|
engine.on_pre_gateway_dispatch()
|
||||||
async def run():
|
engine.on_post_llm_call()
|
||||||
await engine.on_pre_gateway_dispatch()
|
time.sleep(engine._away_grace_s + 0.05)
|
||||||
await engine.on_post_llm_call()
|
assert engine.get_counters()["main_agent"] == 0
|
||||||
await asyncio.sleep(engine._away_grace_s + 0.05)
|
|
||||||
return engine.get_counters()["main_agent"]
|
|
||||||
|
|
||||||
val = loop.run_until_complete(run())
|
|
||||||
assert val == 0
|
|
||||||
loop.close()
|
|
||||||
|
|
||||||
def test_decrement_below_zero_clamped(self):
|
def test_decrement_below_zero_clamped(self):
|
||||||
"""Dekrement ohne vorheriges Inkrement → bleibt 0 (kein negativ)."""
|
"""Dekrement ohne vorheriges Inkrement → bleibt 0 (kein negativ)."""
|
||||||
engine, loop = _make_engine()
|
engine = _make_engine()
|
||||||
|
engine.on_post_llm_call()
|
||||||
async def run():
|
assert engine.get_counters()["main_agent"] == 0
|
||||||
await engine.on_post_llm_call()
|
|
||||||
return engine.get_counters()["main_agent"]
|
|
||||||
|
|
||||||
val = loop.run_until_complete(run())
|
|
||||||
assert val == 0
|
|
||||||
loop.close()
|
|
||||||
|
|
||||||
|
|
||||||
class TestCounterSum:
|
class TestCounterSum:
|
||||||
"""Summe aller Counter bestimmt Status."""
|
"""Summe aller Counter bestimmt Status."""
|
||||||
|
|
||||||
def test_sum_zero_means_online(self):
|
def test_sum_zero_means_online(self):
|
||||||
engine, loop = _make_engine()
|
engine = _make_engine()
|
||||||
assert engine.get_status() == "ONLINE"
|
assert engine.get_status() == "ONLINE"
|
||||||
loop.close()
|
|
||||||
|
|
||||||
def test_sum_positive_means_busy(self):
|
def test_sum_positive_means_busy(self):
|
||||||
engine, loop = _make_engine()
|
engine = _make_engine()
|
||||||
|
engine.on_pre_gateway_dispatch()
|
||||||
async def run():
|
assert engine.get_status() == "BUSY"
|
||||||
await engine.on_pre_gateway_dispatch()
|
|
||||||
return engine.get_status()
|
|
||||||
|
|
||||||
status = loop.run_until_complete(run())
|
|
||||||
assert status == "BUSY"
|
|
||||||
loop.close()
|
|
||||||
|
|
||||||
def test_mixed_counters_sum_correct(self):
|
def test_mixed_counters_sum_correct(self):
|
||||||
"""main_agent=1 + delegate_subagent=2 → sum=3 → BUSY."""
|
"""main_agent=1 + delegate_subagent=2 → sum=3 → BUSY."""
|
||||||
engine, loop = _make_engine()
|
engine = _make_engine()
|
||||||
|
engine.on_pre_gateway_dispatch()
|
||||||
async def run():
|
engine.on_subagent_start()
|
||||||
await engine.on_pre_gateway_dispatch()
|
engine.on_subagent_start()
|
||||||
await engine.on_subagent_start()
|
total = sum(engine.get_counters().values())
|
||||||
await engine.on_subagent_start()
|
|
||||||
return sum(engine.get_counters().values()), engine.get_status()
|
|
||||||
|
|
||||||
total, status = loop.run_until_complete(run())
|
|
||||||
assert total == 3
|
assert total == 3
|
||||||
assert status == "BUSY"
|
assert engine.get_status() == "BUSY"
|
||||||
loop.close()
|
|
||||||
|
|
||||||
|
|
||||||
class TestCounterTransition:
|
class TestCounterTransition:
|
||||||
"""Transition ONLINE↔BUSY bei Counter-Änderungen."""
|
"""Transition ONLINE↔BUSY bei Counter-Änderungen."""
|
||||||
|
|
||||||
def test_online_to_busy_transition(self):
|
def test_online_to_busy_transition(self):
|
||||||
engine, loop = _make_engine()
|
engine = _make_engine()
|
||||||
|
assert engine.get_status() == "ONLINE"
|
||||||
async def run():
|
engine.on_pre_gateway_dispatch()
|
||||||
assert engine.get_status() == "ONLINE"
|
assert engine.get_status() == "BUSY"
|
||||||
await engine.on_pre_gateway_dispatch()
|
|
||||||
return engine.get_status()
|
|
||||||
|
|
||||||
status = loop.run_until_complete(run())
|
|
||||||
assert status == "BUSY"
|
|
||||||
loop.close()
|
|
||||||
|
|
||||||
def test_busy_to_online_transition_after_away_grace(self):
|
def test_busy_to_online_transition_after_away_grace(self):
|
||||||
engine, loop = _make_engine()
|
engine = _make_engine()
|
||||||
|
engine.on_pre_gateway_dispatch()
|
||||||
async def run():
|
assert engine.get_status() == "BUSY"
|
||||||
await engine.on_pre_gateway_dispatch()
|
engine.on_post_llm_call()
|
||||||
assert engine.get_status() == "BUSY"
|
# away-grace abwarten
|
||||||
await engine.on_post_llm_call()
|
time.sleep(engine._away_grace_s + 0.05)
|
||||||
# away-grace abwarten
|
assert engine.get_status() == "ONLINE"
|
||||||
await asyncio.sleep(engine._away_grace_s + 0.05)
|
|
||||||
return engine.get_status()
|
|
||||||
|
|
||||||
status = loop.run_until_complete(run())
|
|
||||||
assert status == "ONLINE"
|
|
||||||
loop.close()
|
|
||||||
|
|
||||||
def test_busy_stays_busy_during_away_grace(self):
|
def test_busy_stays_busy_during_away_grace(self):
|
||||||
"""Während away-grace läuft, ist interner Status ONLINE, REST-Call verzögert.
|
"""Während away-grace läuft, ist interner Status ONLINE, REST-Call verzögert.
|
||||||
@@ -421,19 +299,13 @@ class TestCounterTransition:
|
|||||||
Architektur 3.3: Status wechselt SOFORT auf ONLINE wenn total=0.
|
Architektur 3.3: Status wechselt SOFORT auf ONLINE wenn total=0.
|
||||||
Der away-grace verzögert nur den REST-Call, nicht den internen State.
|
Der away-grace verzögert nur den REST-Call, nicht den internen State.
|
||||||
"""
|
"""
|
||||||
engine, loop = _make_engine(away_grace_s=0.5)
|
engine = _make_engine(away_grace_s=0.5)
|
||||||
|
engine.on_pre_gateway_dispatch()
|
||||||
async def run():
|
engine.on_post_llm_call()
|
||||||
await engine.on_pre_gateway_dispatch()
|
# away-grace läuft noch (0.5s), interner Status ist bereits ONLINE
|
||||||
await engine.on_post_llm_call()
|
time.sleep(0.1)
|
||||||
# away-grace läuft noch (0.5s), interner Status ist bereits ONLINE
|
|
||||||
await asyncio.sleep(0.1)
|
|
||||||
return engine.get_status()
|
|
||||||
|
|
||||||
status = loop.run_until_complete(run())
|
|
||||||
# Interner Status ist ONLINE (total=0), REST-Call folgt nach away-grace
|
# Interner Status ist ONLINE (total=0), REST-Call folgt nach away-grace
|
||||||
assert status == "ONLINE"
|
assert engine.get_status() == "ONLINE"
|
||||||
loop.close()
|
|
||||||
|
|
||||||
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
@@ -445,37 +317,33 @@ class TestRaceParallelHooks:
|
|||||||
|
|
||||||
def test_parallel_increments_consistent(self):
|
def test_parallel_increments_consistent(self):
|
||||||
"""10 parallele pre_gateway_dispatch → main_agent == 10."""
|
"""10 parallele pre_gateway_dispatch → main_agent == 10."""
|
||||||
engine, loop = _make_engine()
|
engine = _make_engine()
|
||||||
|
threads = []
|
||||||
async def run():
|
for _ in range(10):
|
||||||
tasks = [
|
t = threading.Thread(target=engine.on_pre_gateway_dispatch)
|
||||||
engine.on_pre_gateway_dispatch()
|
threads.append(t)
|
||||||
for _ in range(10)
|
t.start()
|
||||||
]
|
for t in threads:
|
||||||
await asyncio.gather(*tasks)
|
t.join()
|
||||||
return engine.get_counters()["main_agent"]
|
assert engine.get_counters()["main_agent"] == 10
|
||||||
|
|
||||||
val = loop.run_until_complete(run())
|
|
||||||
assert val == 10
|
|
||||||
loop.close()
|
|
||||||
|
|
||||||
def test_parallel_mixed_operations_consistent(self):
|
def test_parallel_mixed_operations_consistent(self):
|
||||||
"""Parallel inkrement + dekrement → Counter konsistent."""
|
"""Parallel inkrement + dekrement → Counter konsistent."""
|
||||||
engine, loop = _make_engine()
|
engine = _make_engine()
|
||||||
|
threads = []
|
||||||
async def run():
|
# 5 Starts
|
||||||
# 5 Starts, 3 Stops parallel
|
for _ in range(5):
|
||||||
tasks = []
|
t = threading.Thread(target=engine.on_subagent_start)
|
||||||
for _ in range(5):
|
threads.append(t)
|
||||||
tasks.append(engine.on_subagent_start())
|
t.start()
|
||||||
for _ in range(3):
|
# 3 Stops
|
||||||
tasks.append(engine.on_subagent_stop())
|
for _ in range(3):
|
||||||
await asyncio.gather(*tasks)
|
t = threading.Thread(target=engine.on_subagent_stop)
|
||||||
return engine.get_counters()["delegate_subagent"]
|
threads.append(t)
|
||||||
|
t.start()
|
||||||
val = loop.run_until_complete(run())
|
for t in threads:
|
||||||
assert val == 2 # 5 - 3 = 2
|
t.join()
|
||||||
loop.close()
|
assert engine.get_counters()["delegate_subagent"] == 2 # 5 - 3 = 2
|
||||||
|
|
||||||
|
|
||||||
class TestRaceLastWins:
|
class TestRaceLastWins:
|
||||||
@@ -484,22 +352,17 @@ class TestRaceLastWins:
|
|||||||
def test_last_wins_overwrites_pending_transition(self):
|
def test_last_wins_overwrites_pending_transition(self):
|
||||||
"""Schnelle aufeinanderfolgende Hooks → nur letzter Status wird gesendet."""
|
"""Schnelle aufeinanderfolgende Hooks → nur letzter Status wird gesendet."""
|
||||||
rest = _make_mock_rest()
|
rest = _make_mock_rest()
|
||||||
engine, loop = _make_engine(rest=rest, away_grace_s=0.05)
|
engine = _make_engine(rest=rest, away_grace_s=0.05)
|
||||||
|
|
||||||
async def run():
|
# Schnell: BUSY → ONLINE → BUSY
|
||||||
# Schnell: BUSY → ONLINE → BUSY
|
engine.on_pre_gateway_dispatch() # BUSY
|
||||||
await engine.on_pre_gateway_dispatch() # BUSY
|
engine.on_post_llm_call() # ONLINE (away-grace startet)
|
||||||
await engine.on_post_llm_call() # ONLINE (away-grace startet)
|
engine.on_pre_gateway_dispatch() # BUSY (away-grace gecancelt)
|
||||||
await engine.on_pre_gateway_dispatch() # BUSY (away-grace gecancelt)
|
# Warten bis Transition gesendet
|
||||||
# Warten bis Transition gesendet
|
time.sleep(0.2)
|
||||||
await asyncio.sleep(0.2)
|
assert engine.get_status() == "BUSY"
|
||||||
return engine.get_status()
|
|
||||||
|
|
||||||
status = loop.run_until_complete(run())
|
|
||||||
assert status == "BUSY"
|
|
||||||
# REST sollte mindestens einmal aufgerufen worden sein
|
# REST sollte mindestens einmal aufgerufen worden sein
|
||||||
assert rest._request.call_count >= 1
|
assert rest._request.call_count >= 1
|
||||||
loop.close()
|
|
||||||
|
|
||||||
|
|
||||||
class TestRaceAwayGraceCancel:
|
class TestRaceAwayGraceCancel:
|
||||||
@@ -507,34 +370,22 @@ class TestRaceAwayGraceCancel:
|
|||||||
|
|
||||||
def test_away_grace_cancelled_by_busy_hook(self):
|
def test_away_grace_cancelled_by_busy_hook(self):
|
||||||
"""away-grace läuft → neuer Hook feuert → away-grace gecancelt → Status BUSY."""
|
"""away-grace läuft → neuer Hook feuert → away-grace gecancelt → Status BUSY."""
|
||||||
engine, loop = _make_engine(away_grace_s=0.5)
|
engine = _make_engine(away_grace_s=0.5)
|
||||||
|
engine.on_pre_gateway_dispatch() # BUSY
|
||||||
async def run():
|
engine.on_post_llm_call() # away-grace startet (0.5s)
|
||||||
await engine.on_pre_gateway_dispatch() # BUSY
|
time.sleep(0.1) # away-grace läuft noch
|
||||||
await engine.on_post_llm_call() # away-grace startet (0.5s)
|
engine.on_subagent_start() # neuer BUSY-Hook → cancel away-grace
|
||||||
await asyncio.sleep(0.1) # away-grace läuft noch
|
time.sleep(0.6) # away-grace wäre abgelaufen
|
||||||
await engine.on_subagent_start() # neuer BUSY-Hook → cancel away-grace
|
|
||||||
await asyncio.sleep(0.6) # away-grace wäre abgelaufen
|
|
||||||
return engine.get_status()
|
|
||||||
|
|
||||||
status = loop.run_until_complete(run())
|
|
||||||
# Sollte BUSY sein weil subagent_start den away-grace gecancelt hat
|
# Sollte BUSY sein weil subagent_start den away-grace gecancelt hat
|
||||||
assert status == "BUSY"
|
assert engine.get_status() == "BUSY"
|
||||||
loop.close()
|
|
||||||
|
|
||||||
def test_away_grace_completes_when_no_interrupt(self):
|
def test_away_grace_completes_when_no_interrupt(self):
|
||||||
"""away-grace läuft durch → Status wird ONLINE."""
|
"""away-grace läuft durch → Status wird ONLINE."""
|
||||||
engine, loop = _make_engine(away_grace_s=0.1)
|
engine = _make_engine(away_grace_s=0.1)
|
||||||
|
engine.on_pre_gateway_dispatch()
|
||||||
async def run():
|
engine.on_post_llm_call()
|
||||||
await engine.on_pre_gateway_dispatch()
|
time.sleep(0.3) # away-grace (0.1s) + Transition
|
||||||
await engine.on_post_llm_call()
|
assert engine.get_status() == "ONLINE"
|
||||||
await asyncio.sleep(0.3) # away-grace (0.1s) + Transition
|
|
||||||
return engine.get_status()
|
|
||||||
|
|
||||||
status = loop.run_until_complete(run())
|
|
||||||
assert status == "ONLINE"
|
|
||||||
loop.close()
|
|
||||||
|
|
||||||
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
@@ -545,88 +396,59 @@ class TestTelemetry:
|
|||||||
"""Telemetrie: REST-Calls, Erfolg, 429, Fehler."""
|
"""Telemetrie: REST-Calls, Erfolg, 429, Fehler."""
|
||||||
|
|
||||||
def test_telemetry_initial_zero(self):
|
def test_telemetry_initial_zero(self):
|
||||||
engine, loop = _make_engine()
|
engine = _make_engine()
|
||||||
t = engine.get_telemetry()
|
t = engine.get_telemetry()
|
||||||
assert t["rest_calls"] == 0
|
assert t["rest_calls"] == 0
|
||||||
assert t["rest_success"] == 0
|
assert t["rest_success"] == 0
|
||||||
assert t["rest_429"] == 0
|
assert t["rest_429"] == 0
|
||||||
assert t["rest_errors"] == 0
|
assert t["rest_errors"] == 0
|
||||||
loop.close()
|
|
||||||
|
|
||||||
|
|
||||||
class TestBusyMessage:
|
class TestBusyMessage:
|
||||||
"""_build_busy_message: korrekte Status-Messages."""
|
"""_build_busy_message: korrekte Status-Messages."""
|
||||||
|
|
||||||
def test_single_counter_message(self):
|
def test_single_counter_message(self):
|
||||||
engine, loop = _make_engine()
|
engine = _make_engine()
|
||||||
|
engine.on_pre_gateway_dispatch()
|
||||||
async def run():
|
msg = engine._build_busy_message()
|
||||||
await engine.on_pre_gateway_dispatch()
|
|
||||||
return engine._build_busy_message()
|
|
||||||
|
|
||||||
msg = loop.run_until_complete(run())
|
|
||||||
assert "Hauptagent" in msg
|
assert "Hauptagent" in msg
|
||||||
loop.close()
|
|
||||||
|
|
||||||
def test_multiple_counters_message(self):
|
def test_multiple_counters_message(self):
|
||||||
engine, loop = _make_engine()
|
engine = _make_engine()
|
||||||
|
engine.on_pre_gateway_dispatch()
|
||||||
async def run():
|
engine.on_subagent_start()
|
||||||
await engine.on_pre_gateway_dispatch()
|
msg = engine._build_busy_message()
|
||||||
await engine.on_subagent_start()
|
|
||||||
return engine._build_busy_message()
|
|
||||||
|
|
||||||
msg = loop.run_until_complete(run())
|
|
||||||
assert "2 Aufgaben" in msg
|
assert "2 Aufgaben" in msg
|
||||||
loop.close()
|
|
||||||
|
|
||||||
|
|
||||||
class TestEnableDisable:
|
class TestEnableDisable:
|
||||||
"""enable()/disable() — korrektes Verhalten."""
|
"""enable()/disable() — korrektes Verhalten."""
|
||||||
|
|
||||||
def test_disable_stops_processing(self):
|
def test_disable_stops_processing(self):
|
||||||
engine, loop = _make_engine()
|
engine = _make_engine()
|
||||||
|
engine.disable()
|
||||||
async def run():
|
engine.on_pre_gateway_dispatch()
|
||||||
engine.disable()
|
assert engine.get_counters()["main_agent"] == 0
|
||||||
await engine.on_pre_gateway_dispatch()
|
|
||||||
return engine.get_counters()["main_agent"]
|
|
||||||
|
|
||||||
val = loop.run_until_complete(run())
|
|
||||||
assert val == 0
|
|
||||||
loop.close()
|
|
||||||
|
|
||||||
def test_enable_re_enables_processing(self):
|
def test_enable_re_enables_processing(self):
|
||||||
engine, loop = _make_engine()
|
engine = _make_engine()
|
||||||
|
engine.disable()
|
||||||
async def run():
|
engine.enable()
|
||||||
engine.disable()
|
engine.on_pre_gateway_dispatch()
|
||||||
engine.enable()
|
assert engine.get_counters()["main_agent"] == 1
|
||||||
await engine.on_pre_gateway_dispatch()
|
|
||||||
return engine.get_counters()["main_agent"]
|
|
||||||
|
|
||||||
val = loop.run_until_complete(run())
|
|
||||||
assert val == 1
|
|
||||||
loop.close()
|
|
||||||
|
|
||||||
|
|
||||||
class TestShutdown:
|
class TestShutdown:
|
||||||
"""shutdown() — sauberes Aufräumen."""
|
"""shutdown() — sauberes Aufräumen."""
|
||||||
|
|
||||||
def test_shutdown_cancels_away_grace(self):
|
def test_shutdown_cancels_away_grace(self):
|
||||||
engine, loop = _make_engine(away_grace_s=10.0)
|
engine = _make_engine(away_grace_s=10.0)
|
||||||
|
engine.on_pre_gateway_dispatch()
|
||||||
async def run():
|
engine.on_post_llm_call()
|
||||||
await engine.on_pre_gateway_dispatch()
|
# away-grace läuft (10s)
|
||||||
await engine.on_post_llm_call()
|
engine.shutdown()
|
||||||
# away-grace läuft (10s)
|
# Kein Fehler, kein hängender Task
|
||||||
engine.shutdown()
|
assert True
|
||||||
# Kein Fehler, kein hängender Task
|
|
||||||
return True
|
|
||||||
|
|
||||||
result = loop.run_until_complete(run())
|
|
||||||
assert result is True
|
|
||||||
loop.close()
|
|
||||||
|
|
||||||
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
@@ -641,22 +463,16 @@ class TestHttp429Handling:
|
|||||||
rest = _make_mock_rest()
|
rest = _make_mock_rest()
|
||||||
# Simuliere 429: _request wirft Exception mit "429" im Text
|
# Simuliere 429: _request wirft Exception mit "429" im Text
|
||||||
rest._request.side_effect = Exception("HTTP 429 Too Many Requests")
|
rest._request.side_effect = Exception("HTTP 429 Too Many Requests")
|
||||||
engine, loop = _make_engine(rest=rest, away_grace_s=0.05)
|
engine = _make_engine(rest=rest, away_grace_s=0.05)
|
||||||
|
|
||||||
async def run():
|
# Setze Status auf BUSY
|
||||||
# Setze Status auf BUSY
|
engine.on_pre_gateway_dispatch()
|
||||||
await engine.on_pre_gateway_dispatch()
|
assert engine.get_status() == "BUSY"
|
||||||
assert engine.get_status() == "BUSY"
|
# Warte auf Transition (REST-Call schlägt fehl mit 429)
|
||||||
# Warte auf Transition (REST-Call schlägt fehl mit 429)
|
time.sleep(0.2)
|
||||||
await asyncio.sleep(0.2)
|
# Status bleibt BUSY — Counter wurde nicht zurückgesetzt
|
||||||
# Status bleibt BUSY — Counter wurde nicht zurückgesetzt
|
assert engine.get_status() == "BUSY"
|
||||||
return engine.get_status(), engine.get_counters()
|
assert engine.get_counters()["main_agent"] == 1
|
||||||
|
|
||||||
status, counters = loop.run_until_complete(run())
|
|
||||||
# Status bleibt BUSY weil Counter > 0 und REST-Call fehlschlug
|
|
||||||
assert status == "BUSY"
|
|
||||||
assert counters["main_agent"] == 1
|
|
||||||
loop.close()
|
|
||||||
|
|
||||||
def test_429_retry_on_next_hook(self):
|
def test_429_retry_on_next_hook(self):
|
||||||
"""Nach 429 wird bei nächstem Hook-Ereignis erneut gesendet."""
|
"""Nach 429 wird bei nächstem Hook-Ereignis erneut gesendet."""
|
||||||
@@ -671,42 +487,33 @@ class TestHttp429Handling:
|
|||||||
return {"success": True}
|
return {"success": True}
|
||||||
|
|
||||||
rest._request.side_effect = _side_effect
|
rest._request.side_effect = _side_effect
|
||||||
engine, loop = _make_engine(rest=rest, away_grace_s=0.05)
|
engine = _make_engine(rest=rest, away_grace_s=0.05)
|
||||||
|
|
||||||
async def run():
|
# Erster Hook: BUSY → REST-Call schlägt fehl (429)
|
||||||
# Erster Hook: BUSY → REST-Call schlägt fehl (429)
|
engine.on_pre_gateway_dispatch()
|
||||||
await engine.on_pre_gateway_dispatch()
|
time.sleep(0.15)
|
||||||
await asyncio.sleep(0.15)
|
# Zweiter Hook: post_llm_call → Counter=0 → ONLINE-Transition
|
||||||
# Zweiter Hook: post_llm_call → Counter=0 → ONLINE-Transition
|
# Der REST-Call sollte jetzt erfolgreich sein
|
||||||
# Der REST-Call sollte jetzt erfolgreich sein
|
engine.on_post_llm_call()
|
||||||
await engine.on_post_llm_call()
|
time.sleep(0.2)
|
||||||
await asyncio.sleep(0.2)
|
|
||||||
return engine.get_status(), call_count[0]
|
|
||||||
|
|
||||||
status, calls = loop.run_until_complete(run())
|
|
||||||
# Nach post_llm_call ist Counter=0, away-grace läuft durch,
|
# Nach post_llm_call ist Counter=0, away-grace läuft durch,
|
||||||
# ONLINE-Transition wird gesendet (zweiter REST-Call, erfolgreich)
|
# ONLINE-Transition wird gesendet (zweiter REST-Call, erfolgreich)
|
||||||
assert status == "ONLINE"
|
assert engine.get_status() == "ONLINE"
|
||||||
assert calls >= 2 # Mindestens 2 REST-Calls (429 + success)
|
assert call_count[0] >= 2 # Mindestens 2 REST-Calls (429 + success)
|
||||||
loop.close()
|
|
||||||
|
|
||||||
def test_429_telemetry_counted(self):
|
def test_429_telemetry_counted(self):
|
||||||
"""Telemetrie zählt 429 korrekt."""
|
"""Telemetrie zählt 429 korrekt."""
|
||||||
rest = _make_mock_rest()
|
rest = _make_mock_rest()
|
||||||
rest._request.side_effect = Exception("HTTP 429 Too Many Requests")
|
rest._request.side_effect = Exception("HTTP 429 Too Many Requests")
|
||||||
engine, loop = _make_engine(rest=rest, away_grace_s=0.05)
|
engine = _make_engine(rest=rest, away_grace_s=0.05)
|
||||||
|
|
||||||
async def run():
|
engine.on_pre_gateway_dispatch()
|
||||||
await engine.on_pre_gateway_dispatch()
|
time.sleep(0.2)
|
||||||
await asyncio.sleep(0.2)
|
telemetry = engine.get_telemetry()
|
||||||
return engine.get_telemetry()
|
|
||||||
|
|
||||||
telemetry = loop.run_until_complete(run())
|
|
||||||
assert telemetry["rest_429"] >= 1
|
assert telemetry["rest_429"] >= 1
|
||||||
assert telemetry["rest_calls"] >= 1
|
assert telemetry["rest_calls"] >= 1
|
||||||
# Kein success weil 429
|
# Kein success weil 429
|
||||||
assert telemetry["rest_success"] == 0
|
assert telemetry["rest_success"] == 0
|
||||||
loop.close()
|
|
||||||
|
|
||||||
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
@@ -999,58 +806,3 @@ class TestDetectionSourceTelemetry:
|
|||||||
pass
|
pass
|
||||||
def test_detection_source_gateway(self):
|
def test_detection_source_gateway(self):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@pytest.mark.skip(reason="V8.x removed in V9")
|
|
||||||
class TestPresenceEnginePluginStateIntegration:
|
|
||||||
def test_detection_timer_has_plugin_state_path(self):
|
|
||||||
pass
|
|
||||||
|
|
||||||
@pytest.mark.skip(reason="V8.x removed in V9")
|
|
||||||
class TestCircuitBreakerStateTransitions:
|
|
||||||
def test_breaker_starts_closed(self):
|
|
||||||
pass
|
|
||||||
def test_one_429_opens_breaker(self):
|
|
||||||
pass
|
|
||||||
def test_breaker_blocks_ticks_when_open(self):
|
|
||||||
pass
|
|
||||||
|
|
||||||
@pytest.mark.skip(reason="V8.x removed in V9")
|
|
||||||
class TestCircuitBreakerHalfOpen:
|
|
||||||
def test_half_open_success_returns_to_closed(self):
|
|
||||||
pass
|
|
||||||
def test_half_open_429_returns_to_open(self):
|
|
||||||
pass
|
|
||||||
|
|
||||||
@pytest.mark.skip(reason="V8.x removed in V9")
|
|
||||||
class TestCircuitBreakerSustained429:
|
|
||||||
def test_sustained_429_escalates_pulse_interval(self):
|
|
||||||
pass
|
|
||||||
def test_backoff_capped_at_max(self):
|
|
||||||
pass
|
|
||||||
|
|
||||||
@pytest.mark.skip(reason="V8.x removed in V9")
|
|
||||||
class TestCircuitBreakerDdpErrorClassification:
|
|
||||||
def test_server_returned_false_is_transient(self):
|
|
||||||
pass
|
|
||||||
def test_429_error_is_classified_as_429(self):
|
|
||||||
pass
|
|
||||||
def test_other_error_is_classified_as_other(self):
|
|
||||||
pass
|
|
||||||
def test_ddp_transient_does_not_trigger_rest_fallback(self):
|
|
||||||
pass
|
|
||||||
def test_429_ddp_error_does_not_trigger_rest_fallback(self):
|
|
||||||
pass
|
|
||||||
|
|
||||||
@pytest.mark.skip(reason="V8.x removed in V9")
|
|
||||||
class TestCircuitBreakerRecordSuccess:
|
|
||||||
def test_record_success_resets_everything(self):
|
|
||||||
pass
|
|
||||||
def test_success_after_open_resets_interval(self):
|
|
||||||
pass
|
|
||||||
|
|
||||||
@pytest.mark.skip(reason="V8.x removed in V9")
|
|
||||||
class TestCircuitBreakerRest429Return:
|
|
||||||
def test_rest_429_stops_execution(self):
|
|
||||||
pass
|
|
||||||
def test_rest_429_does_not_log_failure(self):
|
|
||||||
pass
|
|
||||||
|
|||||||
Reference in New Issue
Block a user