feat(F072,F544): Welle 3 — Prozess-Isolation POC + Context-Curator im multiroom=false @implements: [F-072] [F-544]

This commit is contained in:
Bernd (Hermes)
2026-09-17 18:04:03 +02:00
parent 31ca0f2533
commit 32b560dfe3
7 changed files with 817 additions and 0 deletions
+88
View File
@@ -0,0 +1,88 @@
"""
F072 — Prozess-Isolation Plugin/Core.
Verifiziert den Proof-of-Concept (Stufe 1a) in plugin/isolation_worker.py:
1. Normale isolierte Ausführung liefert korrektes Ergebnis.
2. Timeout im Worker → IsolationError, Hauptprozess lebt weiter.
3. os._exit-Crash im Worker → Hauptprozess (Testprozess) überlebt UND der
Fehler wird als IsolationError abgefangen (Gateway verschont).
Der Proof-of-Concept beweist: Ein Worker-Subprozess kann hart crashen, ohne
den Core-/Gateway-Prozess mitzureißen.
@implements: [F-072]
"""
from __future__ import annotations
import os
from pathlib import Path
import sys
import pytest
_PLUGIN_DIR = str(Path(__file__).resolve().parent.parent / "plugin")
if _PLUGIN_DIR not in sys.path:
sys.path.insert(0, _PLUGIN_DIR)
import isolation_worker # noqa: E402
# ═══════════════════════════════════════════════════════════════════════════
# Test 1: Normale isolierte Ausführung (Roundtrip)
# ═══════════════════════════════════════════════════════════════════════════
def test_f072_isolated_keyword_extract_ok():
payload = {"texts": ["deployment status grün", "fehler firewall"]}
result = isolation_worker.submit_isolated("keyword_extract_batch", payload, timeout_s=30)
assert "doc1" in result
assert result["doc1"]["words"] == 3
# 'status' sollte unter top-3 sein (alle 3 Wörter eindeutig)
assert "status" in result["doc1"]["top"]
def test_f072_unknown_worker_raises_isolation_error():
with pytest.raises(isolation_worker.IsolationError) as excinfo:
isolation_worker.submit_isolated("nicht_existent", None)
assert "unbekannter Worker-Key" in str(excinfo.value.reason)
# ═══════════════════════════════════════════════════════════════════════════
# Test 2: Harte Timeout-Schranke → IsolationError, Hauptprozess lebt weiter
# ═══════════════════════════════════════════════════════════════════════════
def test_f072_timeout_isolated_does_not_kill_gateway():
# Nutzt den auf Modul-Ebene registrierten slow_sleeper-Worker, damit er
# im Subprozess verfügbar (picklbar) ist.
with pytest.raises(isolation_worker.IsolationError) as excinfo:
isolation_worker.submit_isolated("slow_sleeper", 60, timeout_s=1.0)
assert "Timeout" in excinfo.value.reason
# Wichtig: der Testprozess (stehen für den Gateway) lebt weiter:
assert os.getpid() > 0
# ═══════════════════════════════════════════════════════════════════════════
# Test 3: os._exit-Crash im Worker → Gateway überlebt, Fehler gefangen
# ═══════════════════════════════════════════════════════════════════════════
def test_f072_os_exit_crash_isolated_does_not_kill_gateway():
pid_before = os.getpid()
with pytest.raises(isolation_worker.IsolationError) as excinfo:
isolation_worker.submit_isolated("crash_via_exit", 3, timeout_s=15)
# Hauptprozess (Gateway-Stellvertreter) lebt weiter:
assert os.getpid() == pid_before
assert "SystemExit" in excinfo.value.reason or "Process" in str(excinfo.value)
# ═══════════════════════════════════════════════════════════════════════════
# Teardown
# ═══════════════════════════════════════════════════════════════════════════
@pytest.fixture(scope="module", autouse=True)
def _shutdown_executor():
yield
isolation_worker.shutdown()
+206
View File
@@ -0,0 +1,206 @@
"""
F544 — Archivar als Context-Curator im multiroom=false Szenario.
Verifiziert plugin/archivar/context_curator.py:
1. ContextCurator sammelt Raum-Kontext (Themen, aktive User, Keywords).
2. build_context_report erzeugt den ::context-Report für einen Raum.
3. Funktioniert auch OHNE Multi-Room-Komponenten (eigenständig, multiroom=false).
4. Leerer Raum → sinnvolle "Noch kein Kontext"-Meldung.
5. Thread-safety-Grundlage (Record + Report aus verschiedenen "Threads").
Kerneigenschaft F544: Der Context-Curator ist vom ARCHIVAR-Load in adapter.py
entkoppelt und läuft auch, wenn _MULTIROOM()=false (dort werden ConversationHistory,
MultiRoomContextRing und ArchivarMessageHandler auf None gesetzt). Dieses Modul
braucht keiner von ihnen.
@implements: [F-544]
"""
from __future__ import annotations
import threading
from pathlib import Path
import sys
import pytest
_ROOT = Path(__file__).resolve().parent.parent # tests/ -> Repo-Root
_PLUGIN_ARCHIVAR = _ROOT / "plugin" / "archivar"
if str(_PLUGIN_ARCHIVAR) not in sys.path:
sys.path.insert(0, str(_PLUGIN_ARCHIVAR))
from context_curator import ContextCurator # noqa: E402
def _make_cc() -> ContextCurator:
return ContextCurator(max_topics_per_room=8, max_keywords_per_room=12)
# ═══════════════════════════════════════════════════════════════════════════
# Test 1: Kontext-Sammlung (Themen, User, Keywords)
# ═══════════════════════════════════════════════════════════════════════════
def test_f544_collects_room_context():
cc = _make_cc()
room = "R-123"
cc.record(room, "#Entwicklung", "bernd", "Deployment status ist grün und stabil")
cc.record(room, "#Entwicklung", "andreas", "Firewall-Regel aktualisiert")
cc.record(room, "#Entwicklung", "bernd", "Firewall grün")
ctx = cc.room_context(room)
assert ctx is not None
assert len(ctx.topics) == 3 # drei verschiedene Topics
# Aktive User: bernd 2x, andreas 1x
assert ctx.users["bernd"].message_count == 2
assert ctx.users["andreas"].message_count == 1
# Keyword 'firewall' sollte >1 sein (2x vorgekommen)
assert ctx.keywords["firewall"] >= 2
# ═══════════════════════════════════════════════════════════════════════════
# Test 2: ::context-Report
# ═══════════════════════════════════════════════════════════════════════════
def test_f544_context_report_build():
cc = _make_cc()
room = "R-1"
cc.record(room, "#Dev", "bernd", "Deployment ist grün")
cc.record(room, "#Dev", "bernd", "Firewall konfiguriert")
report = cc.build_context_report(room)
assert "Kontext-Raum" in report
assert "#Dev" in report
assert "Aktive User" in report
assert "bernd" in report
assert "Letzte Themen" in report
def test_f544_context_report_empty_room():
cc = _make_cc()
report = cc.build_context_report("unbekannt")
assert "Noch kein Kontext" in report
assert "unbekannt" in report
# ═══════════════════════════════════════════════════════════════════════════
# Test 3: Eigenständigkeit bei multiroom=false (kein Abhängigkeits-Import)
# ═══════════════════════════════════════════════════════════════════════════
def test_f544_does_not_require_multiroom_deps():
"""Stellt sicher, dass context_curator NUR Standard-Lib/typing importiert.
Es darf nicht von ConversationHistory / MultiRoomContextRing /
adapter.py abhängen — denn diese existieren im multiroom=false-Runtime
nicht (werden auf None gesetzt).
"""
import inspect
import context_curator as mod
# Prüfe NUR die Import-Anweisungen (top-level), nicht Docstrings/Kommentare.
src = inspect.getsource(mod)
import_lines = []
in_docstring = False
for line in src.splitlines():
stripped = line.strip()
if stripped.startswith('"""') or stripped.startswith("'''"):
in_docstring = not in_docstring
continue
if in_docstring:
continue
if stripped.startswith("import ") or stripped.startswith("from "):
import_lines.append(line)
import_block = "\n".join(import_lines)
for forbidden in (
"ConversationHistory",
"MultiRoomContextRing",
"ArchivarMessageHandler",
"from adapter",
"import adapter",
"from .conversation_history",
"from .multiroom_context",
"from .adapter_integration",
):
assert forbidden not in import_block, (
f"F544 context_curator darf NICHT von '{forbidden}' abhängen"
)
# ═══════════════════════════════════════════════════════════════════════════
# Test 4: Stoppwort-Filter & Thread-Safety (Paralleles Record + Report)
# ═══════════════════════════════════════════════════════════════════════════
def test_f544_stopword_filter():
cc = _make_cc()
cc.record("R", "#Dev", "bernd", "der und die das ist mit Firewall grün")
ctx = cc.room_context("R")
# Kein einziges Stoppwort darf als Keyword gezählt werden
assert "der" not in ctx.keywords
assert "und" not in ctx.keywords
assert "ist" not in ctx.keywords
assert "firewall" in ctx.keywords
def test_f544_thread_safe_record_report():
cc = _make_cc()
room = "R-T"
def writer():
for i in range(50):
cc.record(room, "#Thread", "alice", f"Nachricht Nummer {i} firewall")
threads = [threading.Thread(target=writer) for _ in range(4)]
for t in threads:
t.start()
for t in threads:
t.join()
report = cc.build_context_report(room)
assert "firewall" in report
assert cc.known_rooms() >= 1
# ═══════════════════════════════════════════════════════════════════════════
# Test 5: Clear / Reset
# ═══════════════════════════════════════════════════════════════════════════
def test_f544_clear():
cc = _make_cc()
cc.record("R", "#Dev", "bernd", "Deployment grün")
assert cc.known_rooms() == 1
cc.clear()
assert cc.known_rooms() == 0
# ═══════════════════════════════════════════════════════════════════════════
# Test 6: Verdrahtung in adapter.py (kein toter Code — P-084)
# ═══════════════════════════════════════════════════════════════════════════
def test_f544_wired_in_adapter():
"""Stellt sicher, dass ::context in adapter.py registriert UND verdrahtet ist.
- ContextCurator wird in adapter.py instanziiert (_context_curator).
- record() wird im Nachrichten-Eingangspfad aufgerufen.
- 'context' ist in der Inline-Command-Registry registriert.
- _cmd_context-Handler existiert.
"""
adapter_src = (_ROOT / "plugin" / "adapter.py").read_text()
# 1. Instantiation (in jedem Modus, nicht nur _MULTIROOM())
assert "self._context_curator = ContextCurator()" in adapter_src
assert "from archivar.context_curator import ContextCurator" in adapter_src
# 2. record()-Verdrahtung im Eingangspfad
assert "cc.record(room_id, room_name, username, display_text)" in adapter_src
# 3. Registry-Registrierung
assert '"context", self._cmd_context' in adapter_src
# 4. Handler existiert
assert "async def _cmd_context(self, room_id: str, args: str) -> str:" in adapter_src