feat(F072,F544): Welle 3 — Prozess-Isolation POC + Context-Curator im multiroom=false @implements: [F-072] [F-544]
This commit is contained in:
@@ -0,0 +1,175 @@
|
||||
"""
|
||||
F072 — Prozess-Isolation Plugin/Core — Proof-of-Concept (Stufe 1a).
|
||||
|
||||
Isoliert nicht-kritische, CPU-/IO-gebundene Plugin-Arbeitslasten in separate
|
||||
Worker-Subprozesse, sodass ein Worker-Crash (Timeout, MemoryError, os._exit)
|
||||
den Gateway-/Core-Prozess NICHT mitreißt.
|
||||
|
||||
Konzept (siehe docs/F072_prozess_isolation.md):
|
||||
- Der kritische Pfad (Adapter-Ein-/Ausgang) bleibt im Core-Prozess, weil er
|
||||
Core-native Hooks braucht (P-064 / _active_adapter).
|
||||
- Heavy-Arbeitslasten (Keyword-Extraktion über große Batches, State-Compaction,
|
||||
CPU-lastige Vorverarbeitung) laufen via ProcessPoolExecutor im Subprozess.
|
||||
- Ein Worker-Crash wird abgefangen und als IsolationError gemeldet.
|
||||
|
||||
Garantie: Der Gateway-Prozess überlebt JEDEN Worker-Crash (härtester Fall
|
||||
getestet: os._exit im Worker).
|
||||
|
||||
@implements: [F-072]
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
from concurrent.futures import ProcessPoolExecutor, TimeoutError as FutTimeout
|
||||
from typing import Any, Callable, Dict, Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ── Registrierte, im isolierten Subprozess ausführbare Operationen ─────────
|
||||
# Ein Worker-Funktion läuft im Subprozess und MUSS selbständig alle Importe
|
||||
# laden (die Worker-Registry ist daher prozess-lokal aufgebaut).
|
||||
_WORKER_REGISTRY: Dict[str, Callable[..., Any]] = {}
|
||||
|
||||
|
||||
def _register_worker(key: str, fn: Callable[..., Any]) -> None:
|
||||
"""Registriert eine im Subprozess ausführbare Funktion unter einem Key."""
|
||||
_WORKER_REGISTRY[key] = fn
|
||||
|
||||
|
||||
def _run_worker(key: str, payload: Any) -> Any:
|
||||
"""Top-Level-Funktion, die im Subprozess ausgeführt wird (picklable)."""
|
||||
fn = _WORKER_REGISTRY.get(key)
|
||||
if fn is None:
|
||||
raise KeyError(f"Kein Worker '{key}' registriert")
|
||||
return fn(payload)
|
||||
|
||||
|
||||
# ── Der Executor wird lazy initialisiert und global geteilt ────────────────
|
||||
_executor: Optional[ProcessPoolExecutor] = None
|
||||
|
||||
|
||||
def _get_executor() -> ProcessPoolExecutor:
|
||||
global _executor
|
||||
if _executor is None:
|
||||
_executor = ProcessPoolExecutor(max_workers=1)
|
||||
return _executor
|
||||
|
||||
|
||||
class IsolationError(Exception):
|
||||
"""Fehlgeschlagene isolierte Ausführung (Timeout / Worker-Crash)."""
|
||||
|
||||
def __init__(self, key: str, reason: str) -> None:
|
||||
self.key = key
|
||||
self.reason = reason
|
||||
super().__init__(f"isolierter Worker '{key}' fehlgeschlagen: {reason}")
|
||||
|
||||
|
||||
def submit_isolated(
|
||||
key: str,
|
||||
payload: Any = None,
|
||||
timeout_s: float = 10.0,
|
||||
) -> Any:
|
||||
"""Führt eine registrierte Funktion in einem separaten Subprozess aus.
|
||||
|
||||
Args:
|
||||
key: Registry-Key der auszuführenden Funktion.
|
||||
payload: Pickle-fähiges Argument.
|
||||
timeout_s: Harte Timeout-Schranke in Sekunden.
|
||||
|
||||
Returns:
|
||||
Ergebnis des Workers.
|
||||
|
||||
Raises:
|
||||
IsolationError: bei Timeout, Worker-Crash oder unbekanntem Key.
|
||||
"""
|
||||
if key not in _WORKER_REGISTRY:
|
||||
raise IsolationError(key, "unbekannter Worker-Key")
|
||||
|
||||
try:
|
||||
future = _get_executor().submit(_run_worker, key, payload)
|
||||
return future.result(timeout=timeout_s)
|
||||
except FutTimeout:
|
||||
# Timeout — Worker hängt / zu langsam. Wir verwerfen den Executor neu,
|
||||
# damit ein noch laufender (z.B. schlafender) Worker-Prozess nicht den
|
||||
# Pool-Slot für spätere Submits blockiert.
|
||||
_reset_executor()
|
||||
raise IsolationError(key, f"Timeout nach {timeout_s}s")
|
||||
except Exception as exc: # noqa: BLE001 — harter Isolationsschutz
|
||||
# Jede Exception im Worker (auch SystemExit, MemoryError) landen hier.
|
||||
# Der HAUPTprozess bleibt am Leben.
|
||||
reason = _crash_reason(exc)
|
||||
logger.warning("F072 Isolations-Error (Worker überlebt als Subprozess, "
|
||||
"Gateway verschont): key=%s reason=%s", key, reason)
|
||||
_reset_executor()
|
||||
raise IsolationError(key, reason) from exc
|
||||
|
||||
|
||||
def _reset_executor() -> None:
|
||||
"""Entsorgt einen Executor (und dessen ggf. hängende Worker-Prozesse).
|
||||
|
||||
ProcessPoolExecutor beendet einen Worker-Subprozess, der einen Future
|
||||
nach Timeout noch weiterrechnet, NICHT automatisch. Durch shutdown(False)
|
||||
+ Neu-Initialisierung werden stale Worker-Worker verworfen.
|
||||
"""
|
||||
global _executor
|
||||
if _executor is not None:
|
||||
try:
|
||||
_executor.shutdown(wait=False, cancel_futures=True)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
_executor = None
|
||||
|
||||
|
||||
def _crash_reason(exc: BaseException) -> str:
|
||||
if isinstance(exc, MemoryError):
|
||||
return "MemoryError im Worker"
|
||||
if isinstance(exc, SystemExit):
|
||||
return f"SystemExit({exc.code}) im Worker"
|
||||
return f"{type(exc).__name__}: {exc}"
|
||||
|
||||
|
||||
# ── Beispieldaten registrieren (POC-Operationen) ────────────────────────────
|
||||
|
||||
def _op_keyword_extract_batch(payload: Any) -> Any:
|
||||
"""Beispiel: CPU-lastige Batch-Keyword-Extraktion."""
|
||||
texts = payload.get("texts", []) if isinstance(payload, dict) else []
|
||||
result = {}
|
||||
for i, text in enumerate(texts, 1):
|
||||
# Vereinfachte Häufigkeitsanalyse (POC). In Produktion würde hier
|
||||
# extract_thematic_keyword aus keyword_extractor.py laufen.
|
||||
words = [w.lower() for w in text.split() if w.strip()]
|
||||
counts: Dict[str, int] = {}
|
||||
for w in words:
|
||||
counts[w] = counts.get(w, 0) + 1
|
||||
result[f"doc{i}"] = {"words": len(words), "top": sorted(counts, key=counts.get, reverse=True)[:3]}
|
||||
return result
|
||||
|
||||
|
||||
def _op_crash_via_exit(payload: Any) -> Any:
|
||||
"""Härtester Crash-Fall: beendet den Worker-Subprozess bewusst via os._exit."""
|
||||
code = int(payload or 3)
|
||||
# os._exit umgeht Python-Cleanup — simuliert den schlimmsten Worker-Crash.
|
||||
os._exit(code) # noqa: S106 — absichtlich für den Isolations-Test
|
||||
|
||||
|
||||
def _op_slow_sleeper(payload: Any) -> Any:
|
||||
"""Worker der lange schläft — für den Timeout-Test (MUSS auf Modul-Ebene
|
||||
definiert sein, damit er in den Subprozess re-importierbar/picklbar ist)."""
|
||||
import time
|
||||
time.sleep(int(payload or 30))
|
||||
return "never"
|
||||
|
||||
|
||||
_register_worker("keyword_extract_batch", _op_keyword_extract_batch)
|
||||
_register_worker("crash_via_exit", _op_crash_via_exit)
|
||||
_register_worker("slow_sleeper", _op_slow_sleeper)
|
||||
|
||||
|
||||
def shutdown() -> None:
|
||||
"""Beendet den Executor sauber (optional, bei Gateway-Shutdown)."""
|
||||
global _executor
|
||||
if _executor is not None:
|
||||
_executor.shutdown(wait=False, cancel_futures=True)
|
||||
_executor = None
|
||||
Reference in New Issue
Block a user