feat(F072,F544): Welle 3 — Prozess-Isolation POC + Context-Curator im multiroom=false @implements: [F-072] [F-544]
This commit is contained in:
@@ -1489,6 +1489,11 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
# HOTFIX 2: Muss VOR dem Archivar-Handler-Block initialisiert werden,
|
||||
# da set_recent_auto_routes() das Dict bereits dort bindet.
|
||||
self._recent_auto_routes: Dict[str, Dict[str, Any]] = {}
|
||||
# F544: Archivar als Context-Curator — sammelt Raum-Kontext in JEDEM
|
||||
# Modus (multiroom true/false). Eigenständig, unabhängig von den
|
||||
# Multi-Room-Komponenten und dem ArchivarMessageHandler.
|
||||
from archivar.context_curator import ContextCurator
|
||||
self._context_curator = ContextCurator()
|
||||
# Archivar: Embedding-basierte Nachrichten-Klassifikation
|
||||
if _MULTIROOM():
|
||||
self._conversation_history = ConversationHistory(max_size=10)
|
||||
@@ -3290,6 +3295,17 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
if topic:
|
||||
await self._multiroom_context.add(room_id, room_name, topic)
|
||||
|
||||
# ── F544: Context-Curator — Raum-Kontext in JEDEM Modus sammeln ──
|
||||
# Auch im Single-Room-Modus (multiroom=false) sammelt der Archivar
|
||||
# als Context-Curator: letzte Themen, aktive User, häufige Keywords.
|
||||
# (Eigenständig, unabhängig von _conversation_history/_multiroom_context.)
|
||||
cc = getattr(self, "_context_curator", None)
|
||||
if cc is not None:
|
||||
try:
|
||||
cc.record(room_id, room_name, username, display_text)
|
||||
except Exception: # noqa: BLE001 — Context-Sampling nie crashen
|
||||
logger.debug("[rocketchat] F544 ContextCurator.record skipped (exc)", exc_info=True)
|
||||
|
||||
# ── Kontext-Reset: _THEMATIC_TARGET_ROOM pro Nachricht zurücksetzen ──
|
||||
# Verhindert dass der Zielraum der VORHERIGEN Nachricht an der
|
||||
# aktuellen klebt (z.B. DM nach Projektraum-Turn → Antwort im Projektraum).
|
||||
@@ -5360,6 +5376,17 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
category="Plugin",
|
||||
)
|
||||
|
||||
# F544: Context-Curator — Raum-Kontext abrufen (Archivar als
|
||||
# Context-Curator, funktioniert auch in multiroom=false).
|
||||
self._inline_commands.register(
|
||||
"context", self._cmd_context,
|
||||
help_text="Zeigt gesammelten Raum-Kontext (F544)",
|
||||
description="Zeigt den vom Archivar als Context-Curator gesammelten "
|
||||
"Raum-Kontext: letzte Themen, aktive User, häufige "
|
||||
"Keywords. Funktioniert in multiroom=true UND -false.",
|
||||
category="Plugin",
|
||||
)
|
||||
|
||||
async def _cmd_stability_test(self, room_id: str, args: str) -> str:
|
||||
"""::stability-test — Startet den 7-Tage-Stabilitätstest (F068)."""
|
||||
monitor = getattr(self, "_stability_monitor", None)
|
||||
@@ -5376,6 +5403,17 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
return "Kein Test aktiv. Start mit `::stability-test`."
|
||||
return monitor.generate_report_snapshot()
|
||||
|
||||
async def _cmd_context(self, room_id: str, args: str) -> str:
|
||||
"""::context — Zeigt gesammelten Raum-Kontext (F544 Context-Curator).
|
||||
|
||||
Wird vom Archivar als Context-Curator befüllt (letzte Themen, aktive
|
||||
User, häufige Keywords). Funktioniert in multiroom=true UND -false.
|
||||
"""
|
||||
cc = getattr(self, "_context_curator", None)
|
||||
if cc is None:
|
||||
return "⚠️ Context-Curator nicht verfügbar (Init-Fehler)."
|
||||
return cc.build_context_report(room_id)
|
||||
|
||||
async def _handle_inline_command(
|
||||
self, text: str, room_id: str, room_name: str, username: str
|
||||
) -> bool:
|
||||
|
||||
@@ -16,6 +16,7 @@ from .router import BidirectionalRouter, RoutingDecision
|
||||
from .adapter_integration import ArchivarMessageHandler
|
||||
from .archivar_state import ArchivarState
|
||||
from .conversation_history import ConversationHistory, MessageEntry
|
||||
from .context_curator import ContextCurator, RoomContext
|
||||
|
||||
__all__ = [
|
||||
"IntentClassifier",
|
||||
@@ -36,4 +37,6 @@ __all__ = [
|
||||
"ArchivarState",
|
||||
"ConversationHistory",
|
||||
"MessageEntry",
|
||||
"ContextCurator",
|
||||
"RoomContext",
|
||||
]
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
"""
|
||||
F544 — Archivar als Context-Curator im multiroom=false Szenario.
|
||||
|
||||
Im Single-Room-Modus (MULTIROOM_AGENT=false) werden die Multi-Room-Komponenten
|
||||
(_conversation_history, _multiroom_context, ArchivarMessageHandler) NICHT
|
||||
instanziiert (adapter.py Zeile ~1493-1508). Damit fehlt in diesem Modus jede
|
||||
Kontext-Sammlung — der Archivar fungiert nicht als Context-Curator.
|
||||
|
||||
Dieses Modul implementiert einen SELBSTSTÄNDIGEN ContextCurator, der auch im
|
||||
Single-Room-Modus funktioniert. Er ist unabhängig vom MultiRoomContextRing und
|
||||
sammelt pro Raum:
|
||||
- die zuletzt behandelten Themen (Topic-Ring pro Raum)
|
||||
- die aktiven User (Häufigkeit und letzte Aktivität)
|
||||
- häufige Keywords (Stoppwort-gefilterte Frequenz)
|
||||
|
||||
Bereitstellung der gesammelten Kontext-Informationen über: ::context
|
||||
(Inline-Command, registriert in adapter._register_inline_commands).
|
||||
|
||||
Design-Prinzipien:
|
||||
- Eigenständig (funktioniert bei jeder MULTIROOM-Einstellung, auch ohne
|
||||
ConversationHistory/MultiRoomContext).
|
||||
- Thread-sicher via threading.Lock (kein await im kritischen Pfad, die
|
||||
record()-Aufrufe kommen aus dem asyncio-Adapter-Kontext, sind aber kurz).
|
||||
- Kein toter Code: record() wird im Adapter-Aufruf aktiv verdrahtet und
|
||||
::context aktiv in der Inline-Command-Registry registriert (P-084).
|
||||
|
||||
@implements: [F-544]
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
import threading
|
||||
from collections import Counter, deque
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Stoppwort-Liste (klein — reicht für Frequenz-Keywörter; die eigentliche
|
||||
# Stoppwort-Filterung findet in keyword_extractor/stopwords_*.json statt).
|
||||
_STOPWORDS = {
|
||||
"der", "die", "das", "den", "dem", "des", "ein", "eine", "einer", "einem",
|
||||
"einen", "eines", "und", "oder", "aber", "auch", "nicht", "nichts", "ist",
|
||||
"sind", "war", "waren", "wird", "werden", "wurde", "wuerde", "auf", "in",
|
||||
"an", "zu", "mit", "von", "aus", "fuer", "fuer", "über", "ueber", "unter",
|
||||
"bei", "nach", "seit", "vor", "durch", "um", "als", "wie", "so", "dann",
|
||||
"denn", "doch", "noch", "nur", "auch", "schon", "immer", "man", "ich", "du",
|
||||
"er", "sie", "es", "wir", "ihr", "mein", "dein", "sein", "und", "hat",
|
||||
"haben", "kann", "können", "koennen", "muss", "müssen", "muessen", "gibt",
|
||||
"the", "and", "or", "but", "not", "a", "an", "of", "to", "in", "on", "with",
|
||||
"for", "from", "at", "by", "is", "are", "was", "were", "be", "been", "it",
|
||||
"this", "that", "we", "you", "i", "he", "she", "they",
|
||||
}
|
||||
|
||||
_WORD_RE = re.compile(r"[a-zA-ZäöüÄÖÜß]+", re.UNICODE)
|
||||
|
||||
|
||||
@dataclass
|
||||
class TopicEntry:
|
||||
"""Ein gesammeltes Topic für einen Raum (F544)."""
|
||||
|
||||
topic: str
|
||||
username: str
|
||||
timestamp: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
@dataclass
|
||||
class UserActivity:
|
||||
"""Aktive-User-Tracking pro Raum (F544)."""
|
||||
|
||||
message_count: int = 0
|
||||
last_seen: Optional[datetime] = None
|
||||
|
||||
def note_message(self) -> None:
|
||||
self.message_count += 1
|
||||
self.last_seen = datetime.now(timezone.utc)
|
||||
|
||||
|
||||
@dataclass
|
||||
class RoomContext:
|
||||
"""Gesammelter Kontext für einen einzelnen Raum (F544)."""
|
||||
|
||||
room_name: str = ""
|
||||
topics: deque = field(default_factory=lambda: deque(maxlen=8))
|
||||
users: Dict[str, UserActivity] = field(default_factory=dict)
|
||||
keywords: Counter = field(default_factory=Counter)
|
||||
|
||||
|
||||
class ContextCurator:
|
||||
"""Sammelt und bereitstellt Raum-Kontext — im multiroom=true UND -false.
|
||||
|
||||
Bewusst eigenständig implementiert (kein Rückgriff auf ConversationHistory
|
||||
oder MultiRoomContextRing), damit er auch läuft, wenn diese im
|
||||
Single-Room-Modus nicht instanziiert sind.
|
||||
"""
|
||||
|
||||
def __init__(self, max_topics_per_room: int = 8, max_keywords_per_room: int = 12) -> None:
|
||||
self._max_topics_per_room = max_topics_per_room
|
||||
self._max_keywords_per_room = max_keywords_per_room
|
||||
self._lock = threading.Lock()
|
||||
# room_id -> RoomContext
|
||||
self._rooms: Dict[str, RoomContext] = {}
|
||||
|
||||
# ── Collection-API -----------------------------------------------------
|
||||
|
||||
def record(self, room_id: str, room_name: str, username: str, text: str,
|
||||
topic_len: int = 120) -> None:
|
||||
"""Erfasst eine eingehende User-Nachricht als Kontext-Information.
|
||||
|
||||
Sammelt Topic, aktiven User und Keywords für den Raum. Läuft im
|
||||
Adapter-Aufrufpfad und ist kurz + thread-sicher (kein await).
|
||||
"""
|
||||
if not room_id or not text or not text.strip():
|
||||
return
|
||||
|
||||
username = username or "unknown"
|
||||
display_topic = text.strip().replace("\n", " ")[:topic_len]
|
||||
|
||||
with self._lock:
|
||||
rc = self._rooms.get(room_id) or RoomContext(room_name=room_name)
|
||||
if room_name:
|
||||
rc.room_name = room_name
|
||||
|
||||
# 1. Topic-Ring (dedupliziere fortlaufende Wiederholung gleicher kurz-Sätze)
|
||||
if display_topic and (not rc.topics or rc.topics[-1].topic != display_topic[:60]):
|
||||
rc.topics.append(TopicEntry(topic=display_topic, username=username))
|
||||
|
||||
# 2. Aktiver User
|
||||
user = rc.users.get(username)
|
||||
if user is None:
|
||||
user = UserActivity()
|
||||
rc.users[username] = user
|
||||
user.note_message()
|
||||
|
||||
# 3. Häufige Keywords (stoppwort-gefiltert)
|
||||
for word in _WORD_RE.findall(text.lower()):
|
||||
w = word.strip("-.")
|
||||
if len(w) < 3 or w in _STOPWORDS:
|
||||
continue
|
||||
rc.keywords[w] += 1
|
||||
|
||||
self._rooms[room_id] = rc
|
||||
|
||||
def room_context(self, room_id: str) -> Optional[RoomContext]:
|
||||
"""Liefere den gesammelten Kontext eines Raums (None wenn unbekannt)."""
|
||||
with self._lock:
|
||||
return self._rooms.get(room_id)
|
||||
|
||||
def known_rooms(self) -> int:
|
||||
"""Anzahl der Räume, für die Kontext gesammelt wurde."""
|
||||
with self._lock:
|
||||
return len(self._rooms)
|
||||
|
||||
# ── Bereitstellung (::context) ------------------------------------------
|
||||
|
||||
def build_context_report(self, room_id: str) -> str:
|
||||
"""Baut den ::context-Reports für einen Raum (mehrzeilige Antwort)."""
|
||||
rc = self.room_context(room_id)
|
||||
if rc is None or (not rc.topics and not rc.users and not rc.keywords):
|
||||
return (f"Noch kein Kontext für Raum {room_id} gesammelt. "
|
||||
"Sende einige Nachrichten, damit der Archivar Raum-Kontext "
|
||||
"aufbauen kann.")
|
||||
|
||||
room_label = rc.room_name or room_id
|
||||
lines: List[str] = [f"**Kontext-Raum: {room_label}**"]
|
||||
|
||||
# Aktive User
|
||||
if rc.users:
|
||||
users_sorted = sorted(rc.users.items(), key=lambda kv: kv[1].message_count, reverse=True)
|
||||
user_str = ", ".join(
|
||||
f"{u} ({a.message_count}x)" for u, a in users_sorted[:5]
|
||||
)
|
||||
lines.append(f"• Aktive User: {user_str}")
|
||||
else:
|
||||
lines.append("• Aktive User: —")
|
||||
|
||||
# Häufige Keywords (Top N, nur >1 Vorkommen)
|
||||
if rc.keywords:
|
||||
top_kw = [w for w, c in rc.keywords.most_common(self._max_keywords_per_room) if c > 1]
|
||||
if top_kw:
|
||||
lines.append(f"• Häufige Keywords: {', '.join(top_kw)}")
|
||||
|
||||
# Letzte Themen
|
||||
if rc.topics:
|
||||
lines.append("• Letzte Themen:")
|
||||
for t in list(rc.topics)[-5:]:
|
||||
time_str = t.timestamp.strftime("%H:%M")
|
||||
lines.append(f" – {time_str} {t.topic} ({t.username})")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
# ── Testing / Reset -----------------------------------------------------
|
||||
|
||||
def clear(self) -> None:
|
||||
"""Setzt den gesamten gesammelten Kontext zurück (Tests, ::reset)."""
|
||||
with self._lock:
|
||||
self._rooms.clear()
|
||||
@@ -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