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:
Bernd (Hermes)
2026-07-27 17:03:00 +02:00
parent 4bfac6a689
commit d265624f1c
3 changed files with 156 additions and 39 deletions
+100 -14
View File
@@ -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