fix(critical): Event-Loop-Blockade — ThreadPool-Saturation + Pulse-Interval + Classifier-Timeout
Root-Cause (Rainer): Pulse-Thread + Adapter-Calls + DDP-Fallback-Lawine sättigen den ThreadPool (asyncio.to_thread). Der Loop-Selector kann Watchdog-Probes nicht ausführen → 3 Strikes → Kill. Änderungen: - adapter.py: classify_and_route in asyncio.wait_for(4s), Timeout → STAY - adapter.py: ThreadPoolExecutor max_workers=32 in on_connected_cb - presence_engine.py: pulse_interval 1.5→5.0, sync-default, 2-stufiger CB - classifier.py: _llm_raw/_llm_classify/verify_confidence in wait_for(25s)
This commit is contained in:
+32
-2
@@ -151,7 +151,7 @@ if _MULTIROOM():
|
||||
from archivar.adapter_integration import ArchivarMessageHandler
|
||||
from archivar.conversation_history import ConversationHistory
|
||||
from archivar.multiroom_context import MultiRoomContextRing
|
||||
from archivar.router import room_name_to_topic
|
||||
from archivar.router import room_name_to_topic, RoutingDecision
|
||||
|
||||
# Routing-Counter: immer importieren (keine schweren Abhängigkeiten)
|
||||
from archivar.routing_counter import routing_counter
|
||||
@@ -1232,6 +1232,19 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
P1b: Starts DetectionTimer after DDP connection is established
|
||||
to prevent race condition with gateway_state.json.
|
||||
"""
|
||||
# P0-CRITICAL: ThreadPoolExecutor mit 32 Workers — verhindert
|
||||
# Event-Loop-Blockade durch ThreadPool-Saturation (Pulse + Adapter
|
||||
# + DDP-Fallback-Lawine). Der Default-Executor hat nur
|
||||
# min(32, os.cpu_count()+4) Workers, was bei vielen concurrent
|
||||
# to_thread-Calls zur Sättigung führt.
|
||||
try:
|
||||
_loop = asyncio.get_event_loop()
|
||||
_executor = concurrent.futures.ThreadPoolExecutor(max_workers=32)
|
||||
_loop.set_default_executor(_executor)
|
||||
logger.info("[rocketchat] ThreadPoolExecutor max_workers=32 gesetzt (on_connected_cb)")
|
||||
except Exception as e:
|
||||
logger.warning("[rocketchat] ThreadPoolExecutor set_default_executor failed: %s", e)
|
||||
|
||||
if self.ddp:
|
||||
# B3: Bewusst sync — first status after connect does not need
|
||||
# await-confirmation. PulseController takes over with
|
||||
@@ -3104,7 +3117,24 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
# room_type wird in L1579 aus self._room_info gelesen.
|
||||
_is_dm = (room_type == "d")
|
||||
# P0: routing_text (ohne Quote) für Klassifikation verwenden
|
||||
decision = await self.archivar.classify_and_route(routing_text, origin_room_id=room_id, is_dm=_is_dm)
|
||||
# P0-CRITICAL: asyncio.wait_for(4s) — verhindert Event-Loop-Blockade
|
||||
# durch ThreadPool-Saturation (Pulse + Adapter + DDP-Fallback-Lawine).
|
||||
try:
|
||||
decision = await asyncio.wait_for(
|
||||
self.archivar.classify_and_route(routing_text, origin_room_id=room_id, is_dm=_is_dm),
|
||||
timeout=4.0,
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
logger.warning("[rocketchat] Archivar classify_and_route() timed out (4s) — STAY fallback")
|
||||
global _question_counter
|
||||
decision = RoutingDecision(
|
||||
category='direct_question',
|
||||
target_room=room_id,
|
||||
confidence=0.0,
|
||||
stay_in_room=True,
|
||||
)
|
||||
with _question_counter_lock:
|
||||
_question_counter += 1
|
||||
# V8.3.3: Telemetrie nach jeder Routing-Entscheidung flushen
|
||||
routing_telemetry.flush()
|
||||
if decision and decision.category:
|
||||
|
||||
@@ -469,7 +469,15 @@ class IntentClassifier:
|
||||
|
||||
async def _llm_classify(self, text: str, scores: Dict[str, float]) -> Optional[Tuple[str, float]]:
|
||||
import asyncio
|
||||
return await asyncio.to_thread(self._llm_classify_sync, text, scores)
|
||||
try:
|
||||
# P0-CRITICAL: asyncio.wait_for(25s) — verhindert ThreadPool-Saturation.
|
||||
return await asyncio.wait_for(
|
||||
asyncio.to_thread(self._llm_classify_sync, text, scores),
|
||||
timeout=25.0,
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
logger.warning("LLM classify timed out (25s) — returning None")
|
||||
return None
|
||||
|
||||
def _llm_classify_sync(self, text: str, scores: Dict[str, float]) -> Optional[Tuple[str, float]]:
|
||||
try:
|
||||
@@ -500,7 +508,15 @@ class IntentClassifier:
|
||||
try:
|
||||
if not self._llm_client or not self._llm_enabled:
|
||||
return None
|
||||
return await asyncio.to_thread(self._llm_client.generate, prompt)
|
||||
# P0-CRITICAL: asyncio.wait_for(25s) — verhindert ThreadPool-Saturation.
|
||||
# Bei Timeout: return None → Router wählt STAY-Fallback (router.py Z.1583).
|
||||
return await asyncio.wait_for(
|
||||
asyncio.to_thread(self._llm_client.generate, prompt),
|
||||
timeout=25.0,
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
logger.warning("LLM raw call timed out (25s) — returning None for STAY fallback")
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.warning("LLM raw call failed: %s", e)
|
||||
return None
|
||||
@@ -632,7 +648,16 @@ class IntentClassifier:
|
||||
best_score >= CONFIDENCE_THRESHOLDS["CLARIFY_NEEDED"] and
|
||||
best_score < CONFIDENCE_THRESHOLDS["AUTO_ROUTE"]
|
||||
):
|
||||
llm_result = self._llm_classify_sync(text, scores)
|
||||
# P0-CRITICAL: Timeout 25s — verhindert ThreadPool-Saturation
|
||||
# durch hängende verify_confidence-Calls.
|
||||
import concurrent.futures
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as _exec:
|
||||
_future = _exec.submit(self._llm_classify_sync, text, scores)
|
||||
try:
|
||||
llm_result = _future.result(timeout=25.0)
|
||||
except concurrent.futures.TimeoutError:
|
||||
logger.warning("LLM verify_confidence timed out (25s) — skipping verification")
|
||||
llm_result = None
|
||||
if llm_result:
|
||||
final_category, final_score = llm_result
|
||||
llm_verified = True
|
||||
|
||||
@@ -162,7 +162,7 @@ class PresenceEngine:
|
||||
rest=None,
|
||||
enabled: bool = True,
|
||||
coalesce_ms: int = 2000,
|
||||
pulse_interval: float = 1.5,
|
||||
pulse_interval: float = 5.0,
|
||||
gateway_state_path: str = "",
|
||||
_clamp_pulse: bool = True,
|
||||
):
|
||||
@@ -719,13 +719,13 @@ class PulseController:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
pulse_interval: float = 1.5,
|
||||
pulse_interval: float = 5.0,
|
||||
_clamp_pulse: bool = True,
|
||||
):
|
||||
"""Initialize PulseController.
|
||||
|
||||
Args:
|
||||
pulse_interval: Pulse interval in seconds (default 1.5).
|
||||
pulse_interval: Pulse interval in seconds (default 5.0).
|
||||
_clamp_pulse: If True, clamp to 0.5-30s. Set False for testing.
|
||||
"""
|
||||
if _clamp_pulse:
|
||||
@@ -745,6 +745,12 @@ class PulseController:
|
||||
# P1-2 O-2: Async-await bridge
|
||||
self._loop: Optional[asyncio.AbstractEventLoop] = None
|
||||
self._await_timeout: float = 2.0
|
||||
# P0-CRITICAL: Default sync — async-Pfad nur wenn explizit aktiviert.
|
||||
# Verhindert ThreadPool-Saturation durch run_coroutine_threadsafe.
|
||||
self._use_async_tick: bool = False
|
||||
# P0-CRITICAL: Circuit-Breaker — zweistufiges Backoff bei Fehlern.
|
||||
self._consecutive_failures: int = 0
|
||||
self._current_interval: Optional[float] = None # None = use _pulse_interval
|
||||
|
||||
# ── Public API ───────────────────────────────────────────────────────
|
||||
|
||||
@@ -882,7 +888,10 @@ class PulseController:
|
||||
self._pulse_tick()
|
||||
|
||||
# Sleep for pulse interval, checking running flag periodically
|
||||
for _ in range(int(self._pulse_interval * 10)):
|
||||
# P0-CRITICAL: Circuit-Breaker — _current_interval überschreibt
|
||||
# _pulse_interval bei Fehlern (Stufe 1: 10s, Stufe 2: 30s).
|
||||
effective_interval = self._current_interval if self._current_interval is not None else self._pulse_interval
|
||||
for _ in range(int(effective_interval * 10)):
|
||||
if not self._running.is_set():
|
||||
break
|
||||
if self._paused.is_set():
|
||||
@@ -923,8 +932,10 @@ class PulseController:
|
||||
)
|
||||
return
|
||||
|
||||
# P1-2 O-2: Delegate to async path if loop is bound and running
|
||||
if self._loop is not None and self._loop.is_running():
|
||||
# P0-CRITICAL: Default sync — async-Pfad nur wenn explizit aktiviert.
|
||||
# run_coroutine_threadsafe sättigt den ThreadPool und blockiert den
|
||||
# Event-Loop-Selector → Watchdog-Probes schlagen fehl → Kill.
|
||||
if self._use_async_tick and self._loop is not None and self._loop.is_running():
|
||||
try:
|
||||
future = asyncio.run_coroutine_threadsafe(
|
||||
self._pulse_tick_async(),
|
||||
@@ -959,10 +970,12 @@ class PulseController:
|
||||
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)
|
||||
self._record_failure()
|
||||
|
||||
# REST fallback for message text
|
||||
if self._rest is not None and getattr(self._rest, 'auth_token', None):
|
||||
@@ -980,9 +993,11 @@ 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:
|
||||
logger.info("[pulse] _pulse_tick REST setStatus failed: %s", e)
|
||||
self._record_failure()
|
||||
else:
|
||||
logger.debug(
|
||||
"[pulse] _pulse_tick skip: no DDP and no REST available (ddp=%s, rest=%s)",
|
||||
@@ -1007,6 +1022,7 @@ 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:
|
||||
@@ -1015,6 +1031,7 @@ class PulseController:
|
||||
"falling back to REST",
|
||||
e,
|
||||
)
|
||||
self._record_failure()
|
||||
|
||||
# REST fallback for message text
|
||||
if self._rest is not None and getattr(self._rest, 'auth_token', None):
|
||||
@@ -1032,14 +1049,47 @@ 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:
|
||||
logger.info("[pulse] _pulse_tick_async REST setStatus failed: %s", e)
|
||||
self._record_failure()
|
||||
else:
|
||||
logger.debug(
|
||||
"[pulse] _pulse_tick_async skip: no DDP and no REST available",
|
||||
)
|
||||
|
||||
def _record_failure(self) -> None:
|
||||
"""P0-CRITICAL: Zweistufiger Circuit-Breaker.
|
||||
|
||||
Stufe 1: ab 2 consecutive_failures → _current_interval = 10.0s
|
||||
Stufe 2: ab 4 consecutive_failures → _current_interval = 30.0s
|
||||
Bei Erfolg (_record_success) wird zurückgesetzt.
|
||||
"""
|
||||
self._consecutive_failures += 1
|
||||
if self._consecutive_failures >= 4:
|
||||
self._current_interval = 30.0
|
||||
logger.warning(
|
||||
"[pulse] Circuit-Breaker Stufe 2: interval=30.0s (failures=%d)",
|
||||
self._consecutive_failures,
|
||||
)
|
||||
elif self._consecutive_failures >= 2:
|
||||
self._current_interval = 10.0
|
||||
logger.warning(
|
||||
"[pulse] Circuit-Breaker Stufe 1: interval=10.0s (failures=%d)",
|
||||
self._consecutive_failures,
|
||||
)
|
||||
|
||||
def _record_success(self) -> None:
|
||||
"""Reset circuit breaker on successful pulse."""
|
||||
if self._consecutive_failures > 0:
|
||||
logger.info(
|
||||
"[pulse] Circuit-Breaker reset: failures=%d → 0, interval restored",
|
||||
self._consecutive_failures,
|
||||
)
|
||||
self._consecutive_failures = 0
|
||||
self._current_interval = None
|
||||
|
||||
def _increment_telemetry(self) -> None:
|
||||
"""Increment the heartbeat_pulse telemetry counter.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user