fix(critical): Timeout-Hierarchie umkehren — innere Timeouts 3s < äußere 4s + Semaphore-Timeout + Embedding-Deadline
ROOT-CAUSE: Die Timeout-Hierarchie war umgekehrt. Der äußere wait_for(4s) in adapter.py konnte nie feuern, weil die inneren wait_for(25s) in classifier.py die Coroutine blockierten. AENDERUNGEN: - classifier.py: _llm_raw, _llm_classify, verify_confidence: 25.0s → 3.0s - classifier.py: OllamaEmbeddingClient.get_embedding: ThreadPoolExecutor mit .result(timeout=3.0) statt nacktem urllib.urlopen - router.py: _llm_semaphore.acquire() mit asyncio.wait_for(timeout=3.0) an 3 Stellen (_llm_room_lookup, _detect_recursive, _validate_sentence_marker_llm) - config.py: LLM_CONFIG timeout 10.0 → 3.0 - config.py: OLLAMA_CONFIG timeout 10.0 → 3.0 TIMEOUT-HIERARCHIE (nach Fix): adapter.py wait_for: 4.0s (äußerst) router.py semaphore acquire: 3.0s classifier.py LLM-Calls: 3.0s classifier.py Embedding-Calls: 3.0s config.py LLM_CONFIG timeout: 3.0s config.py OLLAMA_CONFIG timeout: 3.0s Der äußere 4s-Timeout gewinnt jetzt immer.
This commit is contained in:
+100
-14
@@ -10,6 +10,7 @@ ClassificationResult zurückgegeben — der Router übernimmt dann den Fallback.
|
||||
from __future__ import annotations
|
||||
|
||||
import abc
|
||||
import concurrent.futures
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
@@ -151,7 +152,36 @@ class OllamaEmbeddingClient(EmbeddingClient):
|
||||
self._timeout = timeout or OLLAMA_CONFIG["timeout"]
|
||||
|
||||
def get_embedding(self, text: str) -> Optional[List[float]]:
|
||||
"""Call Ollama embeddings API. Returns None on any failure."""
|
||||
"""Call Ollama embeddings API with a hard deadline timeout.
|
||||
|
||||
Uses ``concurrent.futures.ThreadPoolExecutor(max_workers=1)`` with
|
||||
``.result(timeout=self._timeout)`` to enforce a HARD deadline on the
|
||||
entire HTTP call — not just a socket-level timeout. If the embedding
|
||||
model takes longer than the deadline, the future is abandoned and
|
||||
``None`` is returned.
|
||||
|
||||
The executor is shut down with ``wait=False`` on timeout so the
|
||||
caller is never blocked by a hung worker thread.
|
||||
"""
|
||||
executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
|
||||
_shutdown = False
|
||||
try:
|
||||
future = executor.submit(self._get_embedding_sync, text)
|
||||
return future.result(timeout=self._timeout)
|
||||
except concurrent.futures.TimeoutError:
|
||||
logger.warning(
|
||||
"Ollama embedding timed out after %.1fs — returning None",
|
||||
self._timeout,
|
||||
)
|
||||
executor.shutdown(wait=False)
|
||||
_shutdown = True
|
||||
return None
|
||||
finally:
|
||||
if not _shutdown:
|
||||
executor.shutdown(wait=True)
|
||||
|
||||
def _get_embedding_sync(self, text: str) -> Optional[List[float]]:
|
||||
"""Synchronous embedding implementation (called inside ThreadPoolExecutor)."""
|
||||
url = f"{self._base_url}/api/embeddings"
|
||||
payload = json.dumps(
|
||||
{"model": self._model, "prompt": text}
|
||||
@@ -257,7 +287,36 @@ class OllamaLLMClient(LLMClient):
|
||||
self._timeout = timeout or LLM_CONFIG["timeout"]
|
||||
|
||||
def classify(self, text: str) -> Optional[str]:
|
||||
"""Call Ollama generate API. Returns category or None on any failure."""
|
||||
"""Call Ollama generate API with a real deadline timeout.
|
||||
|
||||
Uses ``concurrent.futures.ThreadPoolExecutor(max_workers=1)`` with
|
||||
``.result(timeout=self._timeout)`` to enforce a HARD deadline on the
|
||||
entire HTTP call — not just a socket-level timeout that resets on
|
||||
every token. If the LLM (e.g. qwen2.5:7b on CPU) takes longer than
|
||||
the deadline, the future is abandoned and ``None`` is returned.
|
||||
|
||||
The executor is shut down with ``wait=False`` on timeout so the
|
||||
caller is never blocked by a hung worker thread.
|
||||
"""
|
||||
executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
|
||||
_shutdown = False
|
||||
try:
|
||||
future = executor.submit(self._classify_sync, text)
|
||||
return future.result(timeout=self._timeout)
|
||||
except concurrent.futures.TimeoutError:
|
||||
logger.warning(
|
||||
"Ollama classify timed out after %.1fs — returning None",
|
||||
self._timeout,
|
||||
)
|
||||
executor.shutdown(wait=False)
|
||||
_shutdown = True
|
||||
return None
|
||||
finally:
|
||||
if not _shutdown:
|
||||
executor.shutdown(wait=True)
|
||||
|
||||
def _classify_sync(self, text: str) -> Optional[str]:
|
||||
"""Synchronous classify implementation (called inside ThreadPoolExecutor)."""
|
||||
url = f"{self._base_url}/api/generate"
|
||||
payload = json.dumps(
|
||||
{
|
||||
@@ -282,7 +341,7 @@ class OllamaLLMClient(LLMClient):
|
||||
if not response_text:
|
||||
logger.error("Ollama returned empty response")
|
||||
return None
|
||||
|
||||
|
||||
# Trim whitespace and normalize category
|
||||
category = response_text.strip().lower()
|
||||
if category in ("direct_question", "smalltalk", "work_order", "ambiguous"):
|
||||
@@ -327,8 +386,11 @@ direct_question, smalltalk, work_order, oder ambiguous"""
|
||||
def generate(self, prompt: str) -> Optional[str]:
|
||||
"""Generiere eine freie Antwort vom LLM (keine Kategorie-Validierung).
|
||||
|
||||
Sendet den Prompt an Ollama's /api/generate und gibt die Antwort
|
||||
unvalidiert zurück. Wird vom Raum-Router für LLM_ROOM_PROMPT verwendet.
|
||||
Uses ``concurrent.futures.ThreadPoolExecutor(max_workers=1)`` with
|
||||
``.result(timeout=self._timeout)`` to enforce a HARD deadline on the
|
||||
entire HTTP call — not just a socket-level timeout that resets on
|
||||
every token. If the LLM (e.g. qwen2.5:7b on CPU) takes longer than
|
||||
the deadline, the future is abandoned and ``None`` is returned.
|
||||
|
||||
Args:
|
||||
prompt: Der vollständige Prompt (z.B. LLM_ROOM_PROMPT).
|
||||
@@ -336,6 +398,25 @@ direct_question, smalltalk, work_order, oder ambiguous"""
|
||||
Returns:
|
||||
Die LLM-Antwort als String (getrimmt), oder None bei Fehler.
|
||||
"""
|
||||
executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
|
||||
_shutdown = False
|
||||
try:
|
||||
future = executor.submit(self._generate_sync, prompt)
|
||||
return future.result(timeout=self._timeout)
|
||||
except concurrent.futures.TimeoutError:
|
||||
logger.warning(
|
||||
"Ollama generate timed out after %.1fs — returning None",
|
||||
self._timeout,
|
||||
)
|
||||
executor.shutdown(wait=False)
|
||||
_shutdown = True
|
||||
return None
|
||||
finally:
|
||||
if not _shutdown:
|
||||
executor.shutdown(wait=True)
|
||||
|
||||
def _generate_sync(self, prompt: str) -> Optional[str]:
|
||||
"""Synchronous generate implementation (called inside ThreadPoolExecutor)."""
|
||||
url = f"{self._base_url}/api/generate"
|
||||
payload = json.dumps(
|
||||
{
|
||||
@@ -470,13 +551,15 @@ class IntentClassifier:
|
||||
async def _llm_classify(self, text: str, scores: Dict[str, float]) -> Optional[Tuple[str, float]]:
|
||||
import asyncio
|
||||
try:
|
||||
# P0-CRITICAL: asyncio.wait_for(25s) — verhindert ThreadPool-Saturation.
|
||||
# P0-CRITICAL: asyncio.wait_for(3s) — muss KLEINER sein als
|
||||
# der äußere 4s-Timeout in adapter.py, damit die Timeout-Hierarchie
|
||||
# korrekt ist: 4s (außen) > 3s (innen).
|
||||
return await asyncio.wait_for(
|
||||
asyncio.to_thread(self._llm_classify_sync, text, scores),
|
||||
timeout=25.0,
|
||||
timeout=3.0,
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
logger.warning("LLM classify timed out (25s) — returning None")
|
||||
logger.warning("LLM classify timed out (3s) — returning None")
|
||||
return None
|
||||
|
||||
def _llm_classify_sync(self, text: str, scores: Dict[str, float]) -> Optional[Tuple[str, float]]:
|
||||
@@ -508,14 +591,16 @@ class IntentClassifier:
|
||||
try:
|
||||
if not self._llm_client or not self._llm_enabled:
|
||||
return None
|
||||
# P0-CRITICAL: asyncio.wait_for(25s) — verhindert ThreadPool-Saturation.
|
||||
# P0-CRITICAL: asyncio.wait_for(3s) — muss KLEINER sein als
|
||||
# der äußere 4s-Timeout in adapter.py, damit die Timeout-Hierarchie
|
||||
# korrekt ist: 4s (außen) > 3s (innen).
|
||||
# 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,
|
||||
timeout=3.0,
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
logger.warning("LLM raw call timed out (25s) — returning None for STAY fallback")
|
||||
logger.warning("LLM raw call timed out (3s) — returning None for STAY fallback")
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.warning("LLM raw call failed: %s", e)
|
||||
@@ -648,15 +733,16 @@ class IntentClassifier:
|
||||
best_score >= CONFIDENCE_THRESHOLDS["CLARIFY_NEEDED"] and
|
||||
best_score < CONFIDENCE_THRESHOLDS["AUTO_ROUTE"]
|
||||
):
|
||||
# P0-CRITICAL: Timeout 25s — verhindert ThreadPool-Saturation
|
||||
# P0-CRITICAL: Timeout 3s — muss KLEINER sein als der äußere
|
||||
# 4s-Timeout in adapter.py. 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)
|
||||
llm_result = _future.result(timeout=3.0)
|
||||
except concurrent.futures.TimeoutError:
|
||||
logger.warning("LLM verify_confidence timed out (25s) — skipping verification")
|
||||
logger.warning("LLM verify_confidence timed out (3s) — skipping verification")
|
||||
llm_result = None
|
||||
if llm_result:
|
||||
final_category, final_score = llm_result
|
||||
|
||||
@@ -16,7 +16,8 @@ from typing import Dict
|
||||
OLLAMA_CONFIG: dict = {
|
||||
"base_url": os.getenv("ARCHIVAR_EMBEDDING_BASE_URL", "http://localhost:11434"),
|
||||
"model": "nomic-embed-text",
|
||||
"timeout": 10.0, # Sekunden — empirisch: Ø 2.4s, Cold-Start bis 7.8s
|
||||
"timeout": 3.0, # Sekunden — HARD deadline via ThreadPoolExecutor
|
||||
# Muss KLEINER sein als äußerer 4s-Timeout in adapter.py
|
||||
"embedding_dim": 768, # nomic-embed-text produziert 768-dimensionale Vektoren
|
||||
}
|
||||
|
||||
@@ -156,7 +157,8 @@ wird sie entsprechend klassifiziert. Alles andere → FAKT.
|
||||
LLM_CONFIG = {
|
||||
"enabled": os.getenv("ARCHIVAR_ENABLE_LLM", "").strip().lower() in ("1", "true", "yes"),
|
||||
"model": "qwen2.5:7b",
|
||||
"timeout": 30.0, # Iterative Optimierung: Start 30s (19.06.2026)
|
||||
"timeout": 3.0, # HARD deadline via ThreadPoolExecutor.result(timeout=X)
|
||||
# Muss KLEINER sein als äußerer 4s-Timeout in adapter.py
|
||||
"base_url": os.getenv(
|
||||
"ARCHIVAR_LLM_BASE_URL",
|
||||
os.getenv("OLLAMA_BASE_URL", "http://localhost:11434")
|
||||
|
||||
+52
-23
@@ -1578,8 +1578,17 @@ class BidirectionalRouter:
|
||||
|
||||
# Try LLM — expects room ID directly or "STAY"
|
||||
# Semaphore schützt vor parallelen Ollama-Aufrufen (qwen2.5:7b = single-request)
|
||||
async with self._llm_semaphore:
|
||||
# P0-CRITICAL: Semaphore-Acquire mit 3s Timeout — muss KLEINER sein als
|
||||
# der äußere 4s-Timeout in adapter.py.
|
||||
try:
|
||||
await asyncio.wait_for(self._llm_semaphore.acquire(), timeout=3.0)
|
||||
except asyncio.TimeoutError:
|
||||
logger.warning("LLM semaphore acquire timed out (3s) — skipping LLM room lookup")
|
||||
return None, False, True # LLM-Aufruf fehlgeschlagen
|
||||
try:
|
||||
llm_result = await self._classifier._llm_raw(prompt)
|
||||
finally:
|
||||
self._llm_semaphore.release()
|
||||
if llm_result is None:
|
||||
return None, False, True # LLM-Aufruf fehlgeschlagen
|
||||
|
||||
@@ -1839,19 +1848,28 @@ class BidirectionalRouter:
|
||||
old_topic=old_topic or "(kein altes Thema)",
|
||||
)
|
||||
|
||||
# LLM-Aufruf mit 5s Timeout
|
||||
# LLM-Aufruf mit 3s Timeout (Semaphore + LLM-Call)
|
||||
# P0-CRITICAL: Semaphore-Acquire mit 3s Timeout — muss KLEINER sein als
|
||||
# der äußere 4s-Timeout in adapter.py.
|
||||
try:
|
||||
async with self._llm_semaphore:
|
||||
await asyncio.wait_for(self._llm_semaphore.acquire(), timeout=3.0)
|
||||
except asyncio.TimeoutError:
|
||||
logger.warning("V7-4: LLM-Semaphore Timeout (3s) → Fallback: NEU")
|
||||
return None
|
||||
try:
|
||||
try:
|
||||
llm_result = await asyncio.wait_for(
|
||||
self._classifier._llm_raw(prompt),
|
||||
timeout=5.0,
|
||||
timeout=3.0,
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
logger.warning("V7-4: LLM-Check Timeout (5s) → Fallback: NEU")
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.warning("V7-4: LLM-Check fehlgeschlagen: %s → Fallback: NEU", e)
|
||||
return None
|
||||
except asyncio.TimeoutError:
|
||||
logger.warning("V7-4: LLM-Check Timeout (3s) → Fallback: NEU")
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.warning("V7-4: LLM-Check fehlgeschlagen: %s → Fallback: NEU", e)
|
||||
return None
|
||||
finally:
|
||||
self._llm_semaphore.release()
|
||||
|
||||
if llm_result is None:
|
||||
logger.warning("V7-4: LLM-Check returned None → Fallback: NEU")
|
||||
@@ -2189,24 +2207,35 @@ async def validate_sentence_marker(
|
||||
v7_3_state=v7_3_state,
|
||||
)
|
||||
|
||||
# ── LLM-Aufruf mit 5s Timeout ─────────────────────────────────────
|
||||
# ── LLM-Aufruf mit 3s Timeout (Semaphore + LLM-Call) ──────────────
|
||||
# P0-CRITICAL: Semaphore-Acquire mit 3s Timeout — muss KLEINER sein als
|
||||
# der äußere 4s-Timeout in adapter.py.
|
||||
try:
|
||||
async with llm_semaphore:
|
||||
llm_result = await asyncio.wait_for(
|
||||
classifier._llm_raw(prompt),
|
||||
timeout=5.0,
|
||||
)
|
||||
await asyncio.wait_for(llm_semaphore.acquire(), timeout=3.0)
|
||||
except asyncio.TimeoutError:
|
||||
logger.warning(
|
||||
"A1b Stufe 4/5: LLM-Validierung Timeout (5s) → Fallback: unentscheidbar"
|
||||
)
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.warning(
|
||||
"A1b Stufe 4/5: LLM-Validierung fehlgeschlagen: %s → Fallback: unentscheidbar",
|
||||
e,
|
||||
"A1b Stufe 4/5: LLM-Semaphore Timeout (3s) → Fallback: unentscheidbar"
|
||||
)
|
||||
return None
|
||||
try:
|
||||
try:
|
||||
llm_result = await asyncio.wait_for(
|
||||
classifier._llm_raw(prompt),
|
||||
timeout=3.0,
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
logger.warning(
|
||||
"A1b Stufe 4/5: LLM-Validierung Timeout (3s) → Fallback: unentscheidbar"
|
||||
)
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.warning(
|
||||
"A1b Stufe 4/5: LLM-Validierung fehlgeschlagen: %s → Fallback: unentscheidbar",
|
||||
e,
|
||||
)
|
||||
return None
|
||||
finally:
|
||||
llm_semaphore.release()
|
||||
|
||||
if llm_result is None:
|
||||
logger.warning("A1b Stufe 4/5: LLM returned None → Fallback: unentscheidbar")
|
||||
|
||||
Reference in New Issue
Block a user