fix(archivar): Multi-Request-Resilienz — threading.Lock, asyncio.Semaphore, Catch-All-Schutz + try/except
This commit is contained in:
@@ -50,7 +50,9 @@ _THEMATIC_TARGET_ROOM: contextvars.ContextVar[str] = contextvars.ContextVar(
|
||||
)
|
||||
|
||||
# Globaler Monoton-Zähler für Archivar-Fragen
|
||||
import threading
|
||||
_question_counter: int = 0
|
||||
_question_counter_lock: threading.Lock = threading.Lock()
|
||||
|
||||
try:
|
||||
from gateway.platforms.base import (
|
||||
@@ -810,6 +812,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
if hasattr(decision, 'target_room') and decision.target_room:
|
||||
_THEMATIC_TARGET_ROOM.set(decision.target_room)
|
||||
global _question_counter
|
||||
with _question_counter_lock:
|
||||
_question_counter += 1
|
||||
# ── Ende Kontext-Weitergabe ──────────────────────────────
|
||||
# Archivar v4 Move-Request: _pending_move_requests befüllen, damit
|
||||
@@ -836,6 +839,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
}
|
||||
except asyncio.TimeoutError:
|
||||
logger.warning("[rocketchat] Archivar classify_and_route() timed out")
|
||||
with _question_counter_lock:
|
||||
_question_counter += 1
|
||||
# _THEMATIC_TARGET_ROOM bleibt leer → Prompt sagt "Timeout"
|
||||
except Exception as e:
|
||||
@@ -954,12 +958,14 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
target_room_id = _THEMATIC_TARGET_ROOM.get()
|
||||
if target_room_id:
|
||||
target_name = self._room_info.get(target_room_id, {}).get("name", target_room_id[:12] + "…")
|
||||
with _question_counter_lock:
|
||||
archivar_suffix = f" [Frage {_question_counter}, {room_name} -> {target_name}]"
|
||||
else:
|
||||
# Timeout-Fallback: Agent braucht Raumliste für autonome Entscheidung
|
||||
room_names = [info.get("name", "?") for rid, info in self._room_info.items()
|
||||
if info.get("type") in ("c", "p") and rid != room_id]
|
||||
rooms_str = ", ".join(room_names) if room_names else "keine weiteren Räume"
|
||||
with _question_counter_lock:
|
||||
archivar_suffix = f" [Frage {_question_counter}, Timeout — Räume: {rooms_str}]"
|
||||
# ── Ende Kontext-Weitergabe ──────────────────────────────────────
|
||||
source = SessionSource(
|
||||
|
||||
@@ -8,6 +8,7 @@ und Zusammenfassung nach Abschluss.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
@@ -209,6 +210,10 @@ class BidirectionalRouter:
|
||||
self._room_index: Optional[RoomIndexManager] = room_index
|
||||
self._booster: Optional[KeywordBooster] = booster
|
||||
self._subscribed_room_ids: Optional[set] = None
|
||||
# Semaphore für Ollama-Concurrency: qwen2.5:7b kann nur 1 Request
|
||||
# parallel verarbeiten. Ohne diesen Schutz führen parallele Aufrufe
|
||||
# zu Timeout-Kaskaden.
|
||||
self._llm_semaphore: asyncio.Semaphore = asyncio.Semaphore(1)
|
||||
|
||||
# ── Public API ──────────────────────────────────────────────────────
|
||||
|
||||
@@ -248,6 +253,7 @@ class BidirectionalRouter:
|
||||
|
||||
text = text.strip()
|
||||
|
||||
try:
|
||||
# ── Schritt 0: Excluded rooms check ──────────────────────────
|
||||
if origin_room_id and self._room_map.is_excluded(origin_room_id):
|
||||
logger.debug(
|
||||
@@ -261,6 +267,20 @@ class BidirectionalRouter:
|
||||
stay_in_room=True,
|
||||
)
|
||||
|
||||
# ── Schritt 0.5: Check if origin room is catch-all ───────────
|
||||
origin_room = self._room_map.get_room_by_id(origin_room_id) if origin_room_id else None
|
||||
if origin_room and origin_room.catch_all:
|
||||
logger.debug(
|
||||
"Message from catch-all room %s — ignoring", origin_room_id[:8]
|
||||
)
|
||||
return RoutingDecision(
|
||||
category="direct_question",
|
||||
target_room=origin_room_id,
|
||||
confidence=0.0,
|
||||
is_catch_all=True,
|
||||
stay_in_room=True,
|
||||
)
|
||||
|
||||
# ── Schritt 1: Raum-Zustand prüfen ───────────────────────────
|
||||
room_state_decision = self._state.should_stay_in_room(origin_room_id)
|
||||
if room_state_decision is True:
|
||||
@@ -430,7 +450,7 @@ class BidirectionalRouter:
|
||||
# ── Schritt 5: LLM-Raum-Router (zentraler Prompt) ────────────
|
||||
# LLM_ROOM_PROMPT erhält Nachricht + Raumliste mit Keywords,
|
||||
# liefert room_id direkt (keine Kategorien, kein Name-Matching)
|
||||
llm_room, llm_failed = self._llm_room_lookup(text)
|
||||
llm_room, llm_failed = await self._llm_room_lookup(text)
|
||||
if llm_room is not None:
|
||||
room_name = llm_room.name.replace("#", "") if llm_room.name.startswith("#") else llm_room.name
|
||||
logger.info(
|
||||
@@ -479,6 +499,21 @@ class BidirectionalRouter:
|
||||
stay_in_room=True,
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
# ── Catch-All-Schutz: unerwarteter Fehler → Fallback ──────
|
||||
logger.error(
|
||||
"route(): Unerwarteter Fehler für '%.80s...' — Fallback auf Catch-All: %s",
|
||||
text, e, exc_info=True,
|
||||
)
|
||||
catch_all = self._room_map.catch_all_room
|
||||
return RoutingDecision(
|
||||
category="direct_question",
|
||||
target_room=catch_all.room_id if catch_all else "",
|
||||
confidence=0.0,
|
||||
is_catch_all=True,
|
||||
stay_in_room=True,
|
||||
)
|
||||
|
||||
def _check_unrouteable(self, decision: RoutingDecision) -> None:
|
||||
"""Validate target_room against subscribed IDs.
|
||||
|
||||
@@ -517,13 +552,17 @@ class BidirectionalRouter:
|
||||
|
||||
return catch_all.room_id
|
||||
|
||||
def _llm_room_lookup(self, text: str) -> Tuple[Optional[RoomEntry], bool]:
|
||||
async def _llm_room_lookup(self, text: str) -> Tuple[Optional[RoomEntry], bool]:
|
||||
"""Fragt das LLM: „In welchen Raum gehört diese Nachricht?“
|
||||
|
||||
Baut eine Raum-Liste mit IDs, Namen und ALLEN Keywords aus der RoomMap
|
||||
und nutzt den LLM_ROOM_PROMPT für kontextbasiertes Routing.
|
||||
Das LLM liefert die Raum-ID direkt zurück (kein Name-Matching nötig).
|
||||
|
||||
Der LLM-Aufruf wird durch einen asyncio.Semaphore(1) geschützt, weil
|
||||
qwen2.5:7b nur einen parallelen Request verarbeiten kann. Ohne diesen
|
||||
Schutz führen parallele Aufrufe zu Timeout-Kaskaden.
|
||||
|
||||
Args:
|
||||
text: Der Nachrichtentext.
|
||||
|
||||
@@ -557,7 +596,11 @@ class BidirectionalRouter:
|
||||
prompt = LLM_ROOM_PROMPT.format(room_list=room_list, text=text)
|
||||
|
||||
# Try LLM — expects room ID directly
|
||||
llm_result = self._classifier._llm_raw_sync(prompt)
|
||||
# Semaphore schützt vor parallelen Ollama-Aufrufen (qwen2.5:7b = single-request)
|
||||
async with self._llm_semaphore:
|
||||
llm_result = await asyncio.to_thread(
|
||||
self._classifier._llm_raw_sync, prompt
|
||||
)
|
||||
if llm_result is None:
|
||||
return None, True # LLM-Aufruf fehlgeschlagen
|
||||
|
||||
|
||||
Reference in New Issue
Block a user