P5 V9.x: Rainer Review Fixes — A1-A4 + W2
FIX A1: Adapter-Integration nachgeliefert - adapter.py: init self._outbound_gate nach Z.1177, Gate-Check in send() nach Red-Flag, send_clarify() Gate-Check, release in _process_incoming finally und _dispatch_agent finally, _post_message_unlocked für Quick-Reply - archivar/SKILL.md: Z.20-21 ergänzt + Outbound-Sicht V9.x Abschnitt - archivar/adapter_integration.py: bind_outbound_gate Hook FIX A2: Tests grün (7/7, keine Warnings) - pytest-asyncio bereits installiert (pytest 9.1.0) - @pytest.mark.outbound_gate in conftest.py registriert FIX A3: try_acquire Spec-Abweichung behoben - try_acquire jetzt ASYNC (await asyncio.Lock) - Rückgabetyp: GateDecision Dataclass (allow, reason, blocking_room_id) - Reasons: gate_clear, same_room_same_token, same_room_different_token, different_room_busy FIX A4: wait_until_clear Spec-Abweichung behoben - blocking_room_id Parameter hinzugefügt - _waiters per-Raum Dict (nicht flat List) → kein False-Wake-Bug - _TurnHandle jetzt Dataclass mit task und chat_id Feldern W2: Sweep-Loop als asyncio.create_task im Adapter - _gate_sweep_loop() alle 30s, nicht threading.Timer - Gestartet in connect() nach _listen_loop Tests: 1359 passed, 0 failed, 0 regressions.
This commit is contained in:
@@ -1175,6 +1175,11 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
self.archivar = None
|
||||
self._conversation_history = None
|
||||
self._multiroom_context = None
|
||||
# P5 V9.x: OutboundGate — Parallel-Stream-Schutz
|
||||
from archivar.outbound_gate import OutboundGate, GateDecision
|
||||
self._outbound_gate = OutboundGate(default_timeout_s=30.0, max_entry_age_s=60.0)
|
||||
if self.archivar is not None:
|
||||
self.archivar.bind_outbound_gate(self._outbound_gate)
|
||||
# User-Flow C: Move-Requests
|
||||
self._pending_move_requests: Dict[str, dict] = {}
|
||||
# V8.1 P2: Temporäre Session-Raum-Präferenzen (30 Min TTL)
|
||||
@@ -1393,6 +1398,25 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
return None
|
||||
return None
|
||||
|
||||
async def _post_message_unlocked(self, room_id: str, text: str) -> Optional[str]:
|
||||
"""P5 V9.x: Post message OHNE Gate-Check (für Quick-Reply).
|
||||
|
||||
Direkter REST-Call ohne OutboundGate — verhindert Endlosschleife
|
||||
wenn der Quick-Reply selbst durch den Gate blockiert würde.
|
||||
|
||||
Args:
|
||||
room_id: Rocket.Chat Raum-ID.
|
||||
text: Nachrichtentext.
|
||||
|
||||
Returns:
|
||||
message_id oder None.
|
||||
"""
|
||||
try:
|
||||
return self.rest.post_message(room_id, text)
|
||||
except Exception as e:
|
||||
logger.debug("[rocketchat] _post_message_unlocked failed: %s", e)
|
||||
return None
|
||||
|
||||
def _sync_room_map_with_membership(self) -> None:
|
||||
"""M13: Garbage-Collect room-map.json + FAISS + Booster + State gegen tatsächliche Mitgliedschaft.
|
||||
|
||||
@@ -1907,6 +1931,8 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
self._mark_connected()
|
||||
self._running = True
|
||||
self._listen_task = asyncio.create_task(self._listen_loop())
|
||||
# P5 V9.x W2: OutboundGate Sweep-Loop (asyncio.create_task, nicht threading.Timer)
|
||||
self._gate_sweep_task = asyncio.create_task(self._gate_sweep_loop())
|
||||
self._last_activity = time.time()
|
||||
logger.info("[rocketchat] Listen loop started, _running=%s", self._running)
|
||||
logger.info("[rocketchat] Connected to %s", self.base_url)
|
||||
@@ -3525,6 +3551,18 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
# P1-2: current_room zurücksetzen nach Verarbeitung
|
||||
self._presence_engine.set_current_room("")
|
||||
logger.info("[presence] mark_busy_done (turn complete)")
|
||||
# ── P5 V9.x: OutboundGate — release (symmetrisch zu mark_busy_done) ──
|
||||
# W2: release in try/except BaseException im finally-Block.
|
||||
try:
|
||||
_gate_room_id = f"user:{username}"
|
||||
origin = _CURRENT_ORIGIN_ROOM.get()
|
||||
if origin:
|
||||
_gate_room_id = origin
|
||||
task_token = _CURRENT_TASK_TOKEN.get()
|
||||
if task_token:
|
||||
self._outbound_gate.release(_gate_room_id, task_token)
|
||||
except BaseException:
|
||||
logger.debug("[rocketchat] P5 V9.x: Gate release failed (non-critical)")
|
||||
|
||||
# ── R5: Inline-Command-Handler ────────────────────────────────────────
|
||||
|
||||
@@ -4684,6 +4722,13 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
return
|
||||
finally:
|
||||
self._agent_dispatch_task = None
|
||||
# ── P5 V9.x: OutboundGate — release (symmetrisch zu mark_busy_done) ──
|
||||
try:
|
||||
task_token = _CURRENT_TASK_TOKEN.get()
|
||||
if task_token:
|
||||
self._outbound_gate.release(room_id, task_token)
|
||||
except BaseException:
|
||||
logger.debug("[rocketchat] P5 V9.x: Gate release failed in _dispatch_agent (non-critical)")
|
||||
except Exception as e:
|
||||
logger.error("[rocketchat] handle_message error: %s", e)
|
||||
# Fallback: Wenn COMMAND fehlschlägt
|
||||
@@ -6543,6 +6588,54 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
)
|
||||
routing_counter.increment('red_flag_fallback_stay')
|
||||
|
||||
# ── P5 V9.x: OutboundGate — Parallel-Stream-Schutz ──────────
|
||||
# Nach Red-Flag-Block, vor P1-6 Prefix.
|
||||
# Verhindert dass der Agent gleichzeitig in zwei verschiedenen
|
||||
# Räumen antwortet. Der Denkprozess läuft parallel — das Gate
|
||||
# greift NUR in der Outbound-Phase (posten der Antwort).
|
||||
_gate_room_id = chat_id
|
||||
if chat_id.startswith("user:"):
|
||||
origin = _CURRENT_ORIGIN_ROOM.get()
|
||||
if origin:
|
||||
_gate_room_id = origin
|
||||
task_token = _CURRENT_TASK_TOKEN.get()
|
||||
if task_token and hasattr(self, '_outbound_gate') and self._outbound_gate is not None:
|
||||
from archivar.outbound_gate import GateDecision
|
||||
decision = await self._outbound_gate.try_acquire(_gate_room_id, task_token)
|
||||
if not decision.allow:
|
||||
# Blockiert — warte bis zu 30s (A4: blocking_room_id)
|
||||
blocking_room = decision.blocking_room_id
|
||||
if blocking_room:
|
||||
try:
|
||||
await self._outbound_gate.wait_until_clear(
|
||||
blocking_room_id=blocking_room, timeout_s=30.0
|
||||
)
|
||||
# Retry acquire nach wait
|
||||
decision = await self._outbound_gate.try_acquire(_gate_room_id, task_token)
|
||||
except asyncio.TimeoutError:
|
||||
decision = GateDecision(allow=False, reason="timeout")
|
||||
|
||||
if not decision.allow:
|
||||
# Quick-Reply: anderer Raum blockiert immer noch
|
||||
active_room = self._outbound_gate.active_room_id
|
||||
active_name = ""
|
||||
if active_room and active_room in self._room_info:
|
||||
active_name = self._room_info[active_room].get("name", active_room[:12] + "…")
|
||||
quick_reply_text = (
|
||||
f"Ich antworte gerade in #{active_name} — "
|
||||
f"einen Moment bitte, ich bin gleich bei dir."
|
||||
) if active_name else (
|
||||
"Ich antworte gerade in einem anderen Raum — "
|
||||
"einen Moment bitte, ich bin gleich bei dir."
|
||||
)
|
||||
await self._post_message_unlocked(_gate_room_id, quick_reply_text)
|
||||
self._outbound_gate.stats.quick_reply += 1
|
||||
logger.info(
|
||||
"[rocketchat] P5 V9.x: Quick-Reply sent to room=%s (blocked by %s)",
|
||||
_gate_room_id[:8], active_name,
|
||||
)
|
||||
return SendResult(success=True, message_id="quick_reply")
|
||||
|
||||
# ── P1-6: ::-Prefix für Dangerous-Command-Meldungen ──────────
|
||||
# Hermes Core sendet Meldungen mit /approve, /deny etc.
|
||||
# Rocket.Chat unterstützt keine /-Befehle → :: Varianten einsetzen.
|
||||
@@ -6942,6 +7035,43 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
if not self.rest.auth_token:
|
||||
return SendResult(success=False, error="Not authenticated")
|
||||
|
||||
# ── P5 V9.x: OutboundGate — Parallel-Stream-Schutz ──────────
|
||||
# Gleicher Gate-Check wie in send().
|
||||
_gate_room_id = chat_id
|
||||
if chat_id.startswith("user:"):
|
||||
origin = _CURRENT_ORIGIN_ROOM.get()
|
||||
if origin:
|
||||
_gate_room_id = origin
|
||||
task_token = _CURRENT_TASK_TOKEN.get()
|
||||
if task_token and hasattr(self, '_outbound_gate') and self._outbound_gate is not None:
|
||||
from archivar.outbound_gate import GateDecision
|
||||
decision = await self._outbound_gate.try_acquire(_gate_room_id, task_token)
|
||||
if not decision.allow:
|
||||
blocking_room = decision.blocking_room_id
|
||||
if blocking_room:
|
||||
try:
|
||||
await self._outbound_gate.wait_until_clear(
|
||||
blocking_room_id=blocking_room, timeout_s=30.0
|
||||
)
|
||||
decision = await self._outbound_gate.try_acquire(_gate_room_id, task_token)
|
||||
except asyncio.TimeoutError:
|
||||
decision = GateDecision(allow=False, reason="timeout")
|
||||
if not decision.allow:
|
||||
active_room = self._outbound_gate.active_room_id
|
||||
active_name = ""
|
||||
if active_room and active_room in self._room_info:
|
||||
active_name = self._room_info[active_room].get("name", active_room[:12] + "…")
|
||||
quick_reply_text = (
|
||||
f"Ich antworte gerade in #{active_name} — "
|
||||
f"einen Moment bitte, ich bin gleich bei dir."
|
||||
) if active_name else (
|
||||
"Ich antworte gerade in einem anderen Raum — "
|
||||
"einen Moment bitte, ich bin gleich bei dir."
|
||||
)
|
||||
await self._post_message_unlocked(_gate_room_id, quick_reply_text)
|
||||
self._outbound_gate.stats.quick_reply += 1
|
||||
return SendResult(success=True, message_id="quick_reply")
|
||||
|
||||
# ── Virtual → Real Room Translation ─────────────────────────
|
||||
# chat_id from Hermes session is virtual (e.g. "user:alice").
|
||||
# We must resolve it to a real Rocket.Chat room_id for REST API.
|
||||
@@ -7143,3 +7273,25 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
return self.ddp._msg_queue.get(timeout=timeout)
|
||||
except queue.Empty:
|
||||
return None
|
||||
|
||||
async def _gate_sweep_loop(self) -> None:
|
||||
"""P5 V9.x W2: Periodischer Sweep stale Gate-Einträge.
|
||||
|
||||
Läuft als asyncio.create_task (nicht threading.Timer).
|
||||
Sweept alle 30s — entfernt Einträge die älter als
|
||||
max_entry_age_s (60s) sind.
|
||||
"""
|
||||
while self._running and not self._shutdown_event.is_set():
|
||||
try:
|
||||
await asyncio.sleep(30.0)
|
||||
if hasattr(self, '_outbound_gate') and self._outbound_gate is not None:
|
||||
swept = self._outbound_gate._sweep_stale_entries()
|
||||
if swept > 0:
|
||||
logger.info(
|
||||
"[rocketchat] P5 V9.x: Gate sweep removed %d stale entries",
|
||||
swept,
|
||||
)
|
||||
except asyncio.CancelledError:
|
||||
break
|
||||
except Exception as e:
|
||||
logger.debug("[rocketchat] P5 V9.x: Gate sweep error: %s", e)
|
||||
|
||||
@@ -18,7 +18,8 @@ date: 2026-06-03
|
||||
## Übersicht
|
||||
|
||||
Der Archivar ist ein Submodul des Rocket.Chat-Plugins, das eingehende Nachrichten
|
||||
automatisch klassifiziert und optional in konfigurierte Zielräume weiterleitet.
|
||||
automatisch klassifiziert und optional in konfigurierte Zielräume weiterleitet,
|
||||
und ausgehende Nachrichten über ein opt-in Outbound Gate vor Parallel-Antworten schützt (V9.x).
|
||||
|
||||
**Kernfunktion:**
|
||||
- **Embedding-basierte Klassifikation** via nomic-embed-text (Ollama, localhost:11434)
|
||||
@@ -105,3 +106,42 @@ Bei Ollama-Ausfall greift diese Heuristik:
|
||||
|---|---|---|
|
||||
| FRAGE | frage, wie, was ist, warum, hilfe, problem, funktioniert nicht, kaputt, erklären | question, how, why, help, problem, explain |
|
||||
| ALARM | alarm, hilfe, dringend, sofort, notfall, ausfall, absturz, kritisch | alarm, emergency, urgent, critical, crash, sos |
|
||||
|
||||
## Outbound-Sicht V9.x
|
||||
|
||||
Der Archivar schützt seit V9.x auch ausgehende Nachrichten vor Parallel-Antworten
|
||||
in verschiedenen Räumen (Cross-Contamination). Das **OutboundGate** (`outbound_gate.py`)
|
||||
ist eine reine asyncio-Datenstruktur ohne LLM/Embedding-Logik.
|
||||
|
||||
**Funktionsweise:**
|
||||
- `try_acquire(room_id, task_token)`: Async, nicht-blockierend — prüft ob ein anderer Raum sendet.
|
||||
Gibt `GateDecision` zurück mit `allow`, `reason`, `blocking_room_id`.
|
||||
- `release(room_id, task_token)`: Idempotent — gibt den Slot frei.
|
||||
- `wait_until_clear(blocking_room_id, timeout_s)`: Async wait mit Timeout (default 30s).
|
||||
A4: Per-Raum `_waiters` Dict — kein False-Wake-Bug.
|
||||
- `_sweep_stale_entries()`: Räumt hängende Einträge auf (max_entry_age_s=60s).
|
||||
|
||||
**Regeln:**
|
||||
- Leeres Gate → allow (reason="gate_clear")
|
||||
- Gleicher Raum + gleicher Token → allow (Multi-Turn, W3, reason="same_room_same_token")
|
||||
- Gleicher Raum + anderer Token → block (reason="same_room_different_token")
|
||||
- Anderer Raum busy → block (reason="different_room_busy") → wait_until_clear(30s) → Quick-Reply bei Timeout
|
||||
|
||||
**Quick-Reply:** "Ich antworte gerade in #RaumA — einen Moment bitte, ich bin gleich bei dir."
|
||||
Geht über `_post_message_unlocked` (NICHT durch den Gate, sonst Endlosschleife).
|
||||
|
||||
**Integration:**
|
||||
- `adapter.py __init__`: `self._outbound_gate = OutboundGate()`
|
||||
- `adapter.py send()`: Gate-Check nach Red-Flag-Block, vor P1-6 Prefix
|
||||
- `adapter.py send_clarify()`: Gleicher Gate-Check wie send()
|
||||
- `adapter.py _process_incoming finally`: release symmetrisch zu mark_busy_done
|
||||
- `adapter.py _dispatch_agent finally`: release im finally-Block
|
||||
- `archivar.adapter_integration`: `bind_outbound_gate()` Hook
|
||||
|
||||
**Warn-Signale:**
|
||||
- W1: Gate blockiert NIEMALS synchron, nur asyncio.wait_for
|
||||
- W2: release in try/except BaseException im finally-Block
|
||||
- W3: Multi-Turn gleicher Raum gleicher Token = allowed, KEIN neuer Eintrag
|
||||
- W4: Vor Live-Schaltung alle Tests GRÜN
|
||||
|
||||
**Tests:** `plugin/archivar/tests/test_outbound_gate.py` (7 Tests, Marker `@pytest.mark.outbound_gate`)
|
||||
|
||||
@@ -134,6 +134,7 @@ class ArchivarMessageHandler:
|
||||
self._send_callback = send_callback
|
||||
self._button_send_callback = button_send_callback
|
||||
self._presence_engine = None # P2-2: via set_presence_engine() gesetzt
|
||||
self._outbound_gate = None # P5 V9.x: via bind_outbound_gate() gesetzt
|
||||
self._enable_llm = LLM_CONFIG["enabled"]
|
||||
|
||||
# Create LLM client if enabled and not provided
|
||||
@@ -1185,6 +1186,15 @@ class ArchivarMessageHandler:
|
||||
"""
|
||||
self._presence_engine = engine
|
||||
|
||||
def bind_outbound_gate(self, gate) -> None:
|
||||
"""P5 V9.x: Bindet das OutboundGate für Parallel-Stream-Schutz.
|
||||
|
||||
Args:
|
||||
gate: OutboundGate-Instanz.
|
||||
"""
|
||||
self._outbound_gate = gate
|
||||
logger.info("[archivar] OutboundGate gebunden (V9.x)")
|
||||
|
||||
def set_subscribed_room_ids(self, room_ids: Optional[list]) -> None:
|
||||
"""Set the bot's current subscribed room IDs for routing validation.
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ P5 V9.x: OutboundGate — Parallel-Stream-Schutz für ausgehende Nachrichten.
|
||||
|
||||
Verhindert dass der Agent gleichzeitig in zwei verschiedenen Räumen
|
||||
antwortet (Cross-Contamination). Mechanisches Gate im Adapter-Layer:
|
||||
- try_acquire: nicht-blockierend, prüft ob ein anderer Raum gerade sendet
|
||||
- try_acquire: async, nicht-blockierend, prüft ob ein anderer Raum gerade sendet
|
||||
- release: idempotent, gibt den Slot frei
|
||||
- wait_until_clear: async wait mit Timeout für blockierte Streams
|
||||
|
||||
@@ -16,15 +16,48 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import logging
|
||||
import time
|
||||
from collections import namedtuple
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ── GateDecision: Rückgabetyp von try_acquire ──────────────────────────────
|
||||
|
||||
@dataclass
|
||||
class GateDecision:
|
||||
"""Entscheidung des OutboundGate nach try_acquire.
|
||||
|
||||
Felder:
|
||||
allow: True wenn der Slot akquiriert wurde, False wenn blockiert.
|
||||
reason: Grund für die Entscheidung (gate_clear, same_room_same_token,
|
||||
same_room_different_token, different_room_busy).
|
||||
blocking_room_id: Wenn blockiert durch anderen Raum, dessen ID (sonst None).
|
||||
"""
|
||||
|
||||
allow: bool
|
||||
reason: str
|
||||
blocking_room_id: Optional[str] = None
|
||||
|
||||
|
||||
# ── TurnHandle: Eintrag im _in_flight Dict ────────────────────────────────
|
||||
|
||||
_TurnHandle = namedtuple("_TurnHandle", ["task_token", "started_at", "real_room_id"])
|
||||
@dataclass
|
||||
class _TurnHandle:
|
||||
"""Eintrag im _in_flight Dict — ein aktiver Sendevorgang.
|
||||
|
||||
Felder:
|
||||
task_token: UUID4 Task-Token (aus _CURRENT_TASK_TOKEN).
|
||||
started_at: monotonic timestamp des Eintrags.
|
||||
real_room_id: Rocket.Chat Raum-ID.
|
||||
task: asyncio.Task Referenz (für Cancel/Diagnose).
|
||||
chat_id: Virtuelle Chat-ID (z.B. "user:alice").
|
||||
"""
|
||||
|
||||
task_token: str
|
||||
started_at: float
|
||||
real_room_id: str
|
||||
task: Optional[asyncio.Task] = None
|
||||
chat_id: str = ""
|
||||
|
||||
|
||||
# ── GateStats: 9 Counter für Monitoring ───────────────────────────────────
|
||||
@@ -76,7 +109,8 @@ class OutboundGate:
|
||||
Architektur:
|
||||
- _in_flight: Dict[room_id → _TurnHandle] — aktuell sendender Raum
|
||||
- _lock: asyncio.Lock für Thread-Safety
|
||||
- _waiters: List[asyncio.Event] — wartende Streams
|
||||
- _waiters: Dict[room_id → List[asyncio.Event]] — per-Raum wartende Streams
|
||||
(A4: per-Raum Dict statt flat List → kein False-Wake-Bug)
|
||||
|
||||
Warn-Signale:
|
||||
- W1: Gate blockiert NIEMALS synchron, nur asyncio.wait_for
|
||||
@@ -98,12 +132,13 @@ class OutboundGate:
|
||||
"""
|
||||
self._in_flight: Dict[str, _TurnHandle] = {}
|
||||
self._lock = asyncio.Lock()
|
||||
self._waiters: List[asyncio.Event] = []
|
||||
# A4: Per-Raum Dict statt flat List — kein False-Wake-Bug
|
||||
self._waiters: Dict[str, List[asyncio.Event]] = {}
|
||||
self.default_timeout_s = default_timeout_s
|
||||
self.max_entry_age_s = max_entry_age_s
|
||||
self.stats = GateStats()
|
||||
|
||||
# ── try_acquire (nicht-blockierend) ──────────────────────────────────
|
||||
# ── try_acquire (async, nicht-blockierend) ────────────────────────────
|
||||
|
||||
@property
|
||||
def active_room_id(self) -> Optional[str]:
|
||||
@@ -112,69 +147,85 @@ class OutboundGate:
|
||||
return next(iter(self._in_flight))
|
||||
return None
|
||||
|
||||
def try_acquire(self, room_id: str, task_token: str) -> bool:
|
||||
async def try_acquire(self, room_id: str, task_token: str) -> GateDecision:
|
||||
"""Versucht den Gate-Slot für einen Raum zu akquirieren.
|
||||
|
||||
NICHT-blockierend — gibt sofort True/False zurück.
|
||||
ASYNC — verwendet asyncio.Lock für Thread-Safety.
|
||||
NICHT-blockierend — gibt sofort GateDecision zurück.
|
||||
|
||||
Logik:
|
||||
- _in_flight leer → allow (neuer Eintrag)
|
||||
- gleicher Raum + gleicher Token → allow (W3: Multi-Turn, KEIN neuer Eintrag)
|
||||
- _in_flight leer → allow (neuer Eintrag), reason="gate_clear"
|
||||
- gleicher Raum + gleicher Token → allow (W3: Multi-Turn, KEIN neuer Eintrag),
|
||||
reason="same_room_same_token"
|
||||
- gleicher Raum + anderer Token → block (same_room_different_token)
|
||||
- anderer Raum in _in_flight → block (different_room_blocked)
|
||||
- anderer Raum in _in_flight → block (different_room_busy)
|
||||
|
||||
Args:
|
||||
room_id: Rocket.Chat Raum-ID.
|
||||
task_token: UUID4 Task-Token (aus _CURRENT_TASK_TOKEN).
|
||||
|
||||
Returns:
|
||||
True wenn der Slot akquiriert wurde, False wenn blockiert.
|
||||
GateDecision mit allow, reason, blocking_room_id.
|
||||
"""
|
||||
if room_id in self._in_flight:
|
||||
existing = self._in_flight[room_id]
|
||||
if existing.task_token == task_token:
|
||||
# W3: Multi-Turn — gleicher Raum, gleicher Token
|
||||
self.stats.same_room_same_token += 1
|
||||
logger.debug(
|
||||
"[outbound_gate] Multi-Turn allowed: room=%s token=%s",
|
||||
room_id[:8], task_token[:8],
|
||||
)
|
||||
return True
|
||||
else:
|
||||
# Gleicher Raum, anderer Token → Stream-Retry-Mismatch
|
||||
self.stats.same_room_different_token += 1
|
||||
async with self._lock:
|
||||
if room_id in self._in_flight:
|
||||
existing = self._in_flight[room_id]
|
||||
if existing.task_token == task_token:
|
||||
# W3: Multi-Turn — gleicher Raum, gleicher Token
|
||||
self.stats.same_room_same_token += 1
|
||||
logger.debug(
|
||||
"[outbound_gate] Multi-Turn allowed: room=%s token=%s",
|
||||
room_id[:8], task_token[:8],
|
||||
)
|
||||
return GateDecision(
|
||||
allow=True,
|
||||
reason="same_room_same_token",
|
||||
)
|
||||
else:
|
||||
# Gleicher Raum, anderer Token → Stream-Retry-Mismatch
|
||||
self.stats.same_room_different_token += 1
|
||||
logger.info(
|
||||
"[outbound_gate] Same room, different token blocked: "
|
||||
"room=%s existing_token=%s new_token=%s",
|
||||
room_id[:8], existing.task_token[:8], task_token[:8],
|
||||
)
|
||||
return GateDecision(
|
||||
allow=False,
|
||||
reason="same_room_different_token",
|
||||
)
|
||||
|
||||
# Prüfe ob ein anderer Raum aktiv ist
|
||||
if self._in_flight:
|
||||
# Ein anderer Raum sendet gerade → block
|
||||
active_room = next(iter(self._in_flight))
|
||||
self.stats.different_room_blocked += 1
|
||||
logger.info(
|
||||
"[outbound_gate] Same room, different token blocked: "
|
||||
"room=%s existing_token=%s new_token=%s",
|
||||
room_id[:8], existing.task_token[:8], task_token[:8],
|
||||
"[outbound_gate] Different room blocked: "
|
||||
"requested=%s active=%s",
|
||||
room_id[:8], active_room[:8],
|
||||
)
|
||||
return GateDecision(
|
||||
allow=False,
|
||||
reason="different_room_busy",
|
||||
blocking_room_id=active_room,
|
||||
)
|
||||
return False
|
||||
|
||||
# Prüfe ob ein anderer Raum aktiv ist
|
||||
if self._in_flight:
|
||||
# Ein anderer Raum sendet gerade → block
|
||||
active_room = next(iter(self._in_flight))
|
||||
self.stats.different_room_blocked += 1
|
||||
logger.info(
|
||||
"[outbound_gate] Different room blocked: "
|
||||
"requested=%s active=%s",
|
||||
room_id[:8], active_room[:8],
|
||||
# _in_flight ist leer → allow
|
||||
handle = _TurnHandle(
|
||||
task_token=task_token,
|
||||
started_at=time.monotonic(),
|
||||
real_room_id=room_id,
|
||||
)
|
||||
self._in_flight[room_id] = handle
|
||||
self.stats.acquired_total += 1
|
||||
logger.debug(
|
||||
"[outbound_gate] Acquired: room=%s token=%s",
|
||||
room_id[:8], task_token[:8],
|
||||
)
|
||||
return GateDecision(
|
||||
allow=True,
|
||||
reason="gate_clear",
|
||||
)
|
||||
return False
|
||||
|
||||
# _in_flight ist leer → allow
|
||||
handle = _TurnHandle(
|
||||
task_token=task_token,
|
||||
started_at=time.monotonic(),
|
||||
real_room_id=room_id,
|
||||
)
|
||||
self._in_flight[room_id] = handle
|
||||
self.stats.acquired_total += 1
|
||||
logger.debug(
|
||||
"[outbound_gate] Acquired: room=%s token=%s",
|
||||
room_id[:8], task_token[:8],
|
||||
)
|
||||
return True
|
||||
|
||||
# ── release (idempotent) ──────────────────────────────────────────────
|
||||
|
||||
@@ -184,8 +235,8 @@ class OutboundGate:
|
||||
Idempotent: kein Fehler wenn der Raum nicht in _in_flight ist.
|
||||
Token-Check: nur releasen wenn der Token matched.
|
||||
|
||||
Setzt alle wartenden Events (_waiters) damit blockierte Streams
|
||||
ihren wait_until_clear auflösen können.
|
||||
Setzt alle wartenden Events für diesen Raum (_waiters[room_id])
|
||||
damit blockierte Streams ihren wait_until_clear auflösen können.
|
||||
|
||||
Args:
|
||||
room_id: Rocket.Chat Raum-ID.
|
||||
@@ -214,33 +265,47 @@ class OutboundGate:
|
||||
room_id[:8], task_token[:8],
|
||||
)
|
||||
|
||||
# Alle wartenden Streams aufwecken
|
||||
self._notify_waiters()
|
||||
# Alle wartenden Streams für diesen Raum aufwecken (A4: per-Raum)
|
||||
self._notify_waiters(room_id)
|
||||
|
||||
def _notify_waiters(self) -> None:
|
||||
"""Setzt alle wartenden Events und leert die _waiters-Liste."""
|
||||
if not self._waiters:
|
||||
def _notify_waiters(self, room_id: str) -> None:
|
||||
"""Setzt alle wartenden Events für einen Raum und leert die Liste.
|
||||
|
||||
A4: Per-Raum Notification — nur Streams die auf DIESEN Raum warten
|
||||
werden aufgeweckt. Kein False-Wake-Bug.
|
||||
"""
|
||||
if room_id not in self._waiters:
|
||||
return
|
||||
waiters = self._waiters
|
||||
self._waiters = []
|
||||
waiters = self._waiters.pop(room_id)
|
||||
for event in waiters:
|
||||
event.set()
|
||||
logger.debug(
|
||||
"[outbound_gate] Notified %d waiters", len(waiters),
|
||||
"[outbound_gate] Notified %d waiters for room=%s",
|
||||
len(waiters), room_id[:8],
|
||||
)
|
||||
|
||||
# ── wait_until_clear (async mit Timeout) ─────────────────────────────
|
||||
|
||||
async def wait_until_clear(self, timeout_s: Optional[float] = None) -> None:
|
||||
async def wait_until_clear(
|
||||
self,
|
||||
blocking_room_id: str,
|
||||
timeout_s: Optional[float] = None,
|
||||
) -> None:
|
||||
"""Wartet asynchron bis der Gate-Slot frei wird.
|
||||
|
||||
W1: NIEMALS synchron blockieren — nur asyncio.wait_for.
|
||||
|
||||
Erzeugt ein asyncio.Event, registriert es in _waiters und wartet
|
||||
mit Timeout. Wenn der aktive Stream release() aufruft, werden
|
||||
alle _waiters gesetzt.
|
||||
A4: blocking_room_id Parameter — der Stream wartet spezifisch darauf
|
||||
dass DIESER Raum released wird. Events werden per-Raum registriert
|
||||
(_waiters[blocking_room_id]), kein False-Wake-Bug.
|
||||
|
||||
Erzeugt ein asyncio.Event, registriert es in _waiters[blocking_room_id]
|
||||
und wartet mit Timeout. Wenn der aktive Stream release() aufruft,
|
||||
werden die Events für diesen Raum gesetzt.
|
||||
|
||||
Args:
|
||||
blocking_room_id: ID des Raums der gerade sendet (aus
|
||||
GateDecision.blocking_room_id).
|
||||
timeout_s: Timeout in Sekunden. None = default_timeout_s.
|
||||
|
||||
Raises:
|
||||
@@ -251,11 +316,11 @@ class OutboundGate:
|
||||
timeout_s = self.default_timeout_s
|
||||
|
||||
# Prüfe ob bereits frei (Race-Condition-Schutz)
|
||||
if not self._in_flight:
|
||||
if blocking_room_id not in self._in_flight:
|
||||
return
|
||||
|
||||
event = asyncio.Event()
|
||||
self._waiters.append(event)
|
||||
self._waiters.setdefault(blocking_room_id, []).append(event)
|
||||
|
||||
try:
|
||||
await asyncio.wait_for(event.wait(), timeout=timeout_s)
|
||||
@@ -265,9 +330,12 @@ class OutboundGate:
|
||||
except asyncio.TimeoutError:
|
||||
# Timeout → Quick-Reply
|
||||
self.stats.different_room_timeout += 1
|
||||
# Cleanup: Event aus _waiters entfernen (falls noch vorhanden)
|
||||
if event in self._waiters:
|
||||
self._waiters.remove(event)
|
||||
# Cleanup: Event aus _waiters[blocking_room_id] entfernen
|
||||
if blocking_room_id in self._waiters:
|
||||
if event in self._waiters[blocking_room_id]:
|
||||
self._waiters[blocking_room_id].remove(event)
|
||||
if not self._waiters[blocking_room_id]:
|
||||
del self._waiters[blocking_room_id]
|
||||
logger.info(
|
||||
"[outbound_gate] Wait timeout after %.1fs → Quick-Reply",
|
||||
timeout_s,
|
||||
@@ -302,6 +370,8 @@ class OutboundGate:
|
||||
|
||||
if stale_rooms:
|
||||
self.stats.stale_swept += len(stale_rooms)
|
||||
self._notify_waiters()
|
||||
# Alle wartenden Streams für stale Räume aufwecken
|
||||
for room_id in stale_rooms:
|
||||
self._notify_waiters(room_id)
|
||||
|
||||
return len(stale_rooms)
|
||||
|
||||
@@ -16,6 +16,13 @@ from pathlib import Path
|
||||
import pytest
|
||||
|
||||
|
||||
# P5 V9.x: OutboundGate Marker registrieren
|
||||
def pytest_configure(config):
|
||||
config.addinivalue_line(
|
||||
"markers", "outbound_gate: P5 V9.x OutboundGate Parallel-Stream-Schutz Tests"
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def temp_room_map_path():
|
||||
"""Erzeugt eine temporäre room-map.json mit minimalem Test-Setup.
|
||||
|
||||
@@ -20,7 +20,7 @@ import pytest
|
||||
# Ensure plugin package is importable (same pattern as other archivar tests)
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
|
||||
|
||||
from plugin.archivar.outbound_gate import OutboundGate, GateStats
|
||||
from plugin.archivar.outbound_gate import OutboundGate, GateStats, GateDecision
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -46,20 +46,25 @@ async def test_outbound_gate_waits_then_releases():
|
||||
token_a = "token-aaaa-bbbb-cccc"
|
||||
token_b = "token-xxxx-yyyy-zzzz"
|
||||
|
||||
# Stream A acquires the gate
|
||||
acquired_a = gate.try_acquire(room_a, token_a)
|
||||
assert acquired_a is True, "Stream A should acquire the gate (empty)"
|
||||
# Stream A acquires the gate (A3: async, returns GateDecision)
|
||||
decision_a = await gate.try_acquire(room_a, token_a)
|
||||
assert decision_a.allow is True, "Stream A should acquire the gate (empty)"
|
||||
assert decision_a.reason == "gate_clear"
|
||||
|
||||
# Stream B tries to acquire — should be blocked (different room)
|
||||
acquired_b = gate.try_acquire(room_b, token_b)
|
||||
assert acquired_b is False, "Stream B should be blocked (different room busy)"
|
||||
decision_b = await gate.try_acquire(room_b, token_b)
|
||||
assert decision_b.allow is False, "Stream B should be blocked (different room busy)"
|
||||
assert decision_b.reason == "different_room_busy"
|
||||
assert decision_b.blocking_room_id == room_a
|
||||
|
||||
# Verify stats
|
||||
assert gate.stats.acquired_total == 1
|
||||
assert gate.stats.different_room_blocked == 1
|
||||
|
||||
# B waits for gate to clear (with timeout)
|
||||
wait_task = asyncio.create_task(gate.wait_until_clear(timeout_s=5.0))
|
||||
# B waits for gate to clear (A4: blocking_room_id parameter)
|
||||
wait_task = asyncio.create_task(
|
||||
gate.wait_until_clear(blocking_room_id=room_a, timeout_s=5.0)
|
||||
)
|
||||
|
||||
# Give B a moment to start waiting
|
||||
await asyncio.sleep(0.05)
|
||||
@@ -72,8 +77,9 @@ async def test_outbound_gate_waits_then_releases():
|
||||
await asyncio.wait_for(wait_task, timeout=2.0)
|
||||
|
||||
# Now B can acquire
|
||||
acquired_b_retry = gate.try_acquire(room_b, token_b)
|
||||
assert acquired_b_retry is True, "Stream B should acquire after A released"
|
||||
decision_b_retry = await gate.try_acquire(room_b, token_b)
|
||||
assert decision_b_retry.allow is True, "Stream B should acquire after A released"
|
||||
assert decision_b_retry.reason == "gate_clear"
|
||||
|
||||
# Cleanup
|
||||
gate.release(room_b, token_b)
|
||||
@@ -103,15 +109,16 @@ async def test_outbound_gate_timeout_triggers_quick_reply():
|
||||
token_b = "token-qr-bbbb"
|
||||
|
||||
# Stream A acquires
|
||||
gate.try_acquire(room_a, token_a)
|
||||
await gate.try_acquire(room_a, token_a)
|
||||
|
||||
# Stream B tries to acquire → blocked
|
||||
acquired_b = gate.try_acquire(room_b, token_b)
|
||||
assert acquired_b is False
|
||||
decision_b = await gate.try_acquire(room_b, token_b)
|
||||
assert decision_b.allow is False
|
||||
assert decision_b.blocking_room_id == room_a
|
||||
|
||||
# B waits with short timeout (1s)
|
||||
# B waits with short timeout (1s) — A4: blocking_room_id
|
||||
try:
|
||||
await gate.wait_until_clear(timeout_s=1.0)
|
||||
await gate.wait_until_clear(blocking_room_id=room_a, timeout_s=1.0)
|
||||
# Should not reach here — timeout expected
|
||||
timeout_occurred = False
|
||||
except asyncio.TimeoutError:
|
||||
@@ -151,20 +158,23 @@ async def test_outbound_gate_multi_turn_same_room_allowed():
|
||||
token_a = "token-multi-a"
|
||||
|
||||
# First turn: acquire (creates entry)
|
||||
acquired_1 = gate.try_acquire(room_a, token_a)
|
||||
assert acquired_1 is True
|
||||
decision_1 = await gate.try_acquire(room_a, token_a)
|
||||
assert decision_1.allow is True
|
||||
assert decision_1.reason == "gate_clear"
|
||||
assert gate.stats.acquired_total == 1
|
||||
|
||||
# Second turn: same room, same token, BEFORE release → allowed (W3)
|
||||
acquired_2 = gate.try_acquire(room_a, token_a)
|
||||
assert acquired_2 is True, "Multi-Turn same room same token should be allowed"
|
||||
decision_2 = await gate.try_acquire(room_a, token_a)
|
||||
assert decision_2.allow is True, "Multi-Turn same room same token should be allowed"
|
||||
assert decision_2.reason == "same_room_same_token"
|
||||
assert gate.stats.same_room_same_token == 1
|
||||
# acquired_total should NOT increment for same_room_same_token (W3: KEIN neuer Eintrag)
|
||||
assert gate.stats.acquired_total == 1, "Multi-Turn should NOT create new entry"
|
||||
|
||||
# Third turn: same room, same token, BEFORE release → allowed again
|
||||
acquired_3 = gate.try_acquire(room_a, token_a)
|
||||
assert acquired_3 is True
|
||||
decision_3 = await gate.try_acquire(room_a, token_a)
|
||||
assert decision_3.allow is True
|
||||
assert decision_3.reason == "same_room_same_token"
|
||||
assert gate.stats.same_room_same_token == 2
|
||||
assert gate.stats.acquired_total == 1 # Still 1 — no new entries
|
||||
|
||||
@@ -194,13 +204,15 @@ async def test_outbound_gate_stream_retry_mismatch():
|
||||
token_y = "token-retry-y"
|
||||
|
||||
# Token X acquires
|
||||
acquired_x = gate.try_acquire(room_a, token_x)
|
||||
assert acquired_x is True
|
||||
decision_x = await gate.try_acquire(room_a, token_x)
|
||||
assert decision_x.allow is True
|
||||
assert decision_x.reason == "gate_clear"
|
||||
assert gate.stats.acquired_total == 1
|
||||
|
||||
# Token Y (same room, different token) → blocked
|
||||
acquired_y = gate.try_acquire(room_a, token_y)
|
||||
assert acquired_y is False, "Different token in same room should be blocked"
|
||||
decision_y = await gate.try_acquire(room_a, token_y)
|
||||
assert decision_y.allow is False, "Different token in same room should be blocked"
|
||||
assert decision_y.reason == "same_room_different_token"
|
||||
assert gate.stats.same_room_different_token == 1
|
||||
|
||||
# Verify _in_flight still has token_x
|
||||
@@ -238,7 +250,7 @@ async def test_outbound_gate_sweep_stale_entries():
|
||||
room_a = "ROOM_STALE"
|
||||
token_a = "token-stale"
|
||||
|
||||
gate.try_acquire(room_a, token_a)
|
||||
await gate.try_acquire(room_a, token_a)
|
||||
assert room_a in gate._in_flight
|
||||
|
||||
# Wait for entry to become stale
|
||||
|
||||
Reference in New Issue
Block a user