feat(F169): Reset-Endpoint für adaptiven LLM-Timeout (Voraussetzung F172 Pacing)
@implements F-169 Reset der Welford-Kalibrierung auf Baseline, damit ein Test nicht auf Bot-Tempo statt Mensch-Tempo kalibriert (Rainers Veto für F172). - adaptive_timeout.py: reset_timeout(agent_name) — setzt n/mean/m2/streak/ escalated/accepted/rejected zurück; in-flight-Zähler (begin_call/end_call) für Race-Condition-Erkennung; in_flight-Property. - classifier.py: begin_call()/end_call() um den LLM-Call verdrahtet (finally garantiert Dekrement auch bei Exception). - adapter.py: ::reset-timeout Inline-Command (manueller Reset durch Andreas). - rc_tools.py: rocketchat_reset_timeout Tool (programmatischer Reset). - tests: test_f169_reset_timeout.py — 10 A1c-Tests (Reset setzt Statistik zurück, Reset während in-flight Call ist safe, in-flight nicht persistiert). Race-Condition-Schutz: Reset läuft unter self._lock (atomar gegenüber record/current_timeout). Laufender Call wird nicht blockiert, zählt als erste Messung der Neukalibrierung. Nach Reset: Failsafe 30s bis genug Samples.
This commit is contained in:
@@ -5221,6 +5221,18 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
category="Standard",
|
||||
)
|
||||
|
||||
# F169: ::reset-timeout — adaptiven LLM-Timeout auf Baseline zurücksetzen
|
||||
self._inline_commands.register(
|
||||
"reset-timeout", self._cmd_reset_timeout,
|
||||
help_text="Adaptiven LLM-Timeout auf Baseline zurücksetzen (F169)",
|
||||
description="Setzt die Welford-Kalibrierung des adaptiven LLM-Timeouts "
|
||||
"zurück (Mittelwert, Varianz, Call-Counter, Eskalations-Stufe). "
|
||||
"Der erste Call nach dem Reset kalibriert neu; bis genug Samples "
|
||||
"vorliegen, gilt wieder der Failsafe (30s). Nützlich vor Tests, "
|
||||
"damit die Kalibrierung nicht auf Bot-Tempo statt Mensch-Tempo läuft.",
|
||||
category="Plugin",
|
||||
)
|
||||
|
||||
async def _handle_inline_command(
|
||||
self, text: str, room_id: str, room_name: str, username: str
|
||||
) -> bool:
|
||||
@@ -5513,6 +5525,36 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
"- Raum-Map Summary aktualisiert"
|
||||
)
|
||||
|
||||
async def _cmd_reset_timeout(self, room_id: str, args: str) -> str:
|
||||
"""::reset-timeout — Setzt den adaptiven LLM-Timeout auf Baseline zurück (F169).
|
||||
|
||||
Setzt die Welford-Kalibrierung (Mittelwert + Varianz), den Call-Counter
|
||||
und die Eskalations-Stufe zurück. Der erste Call nach dem Reset
|
||||
kalibriert neu; bis genug Samples vorliegen, gilt wieder der Failsafe.
|
||||
"""
|
||||
from archivar.adaptive_timeout import adaptive_timeout
|
||||
|
||||
agent_name = getattr(self, "_last_inline_username", None) or "unknown"
|
||||
result = adaptive_timeout.reset_timeout(agent_name=agent_name)
|
||||
|
||||
in_flight = result.get("in_flight", 0)
|
||||
in_flight_note = ""
|
||||
if in_flight > 0:
|
||||
in_flight_note = (
|
||||
f"\n⚠️ {in_flight} LLM-Call(s) waren beim Reset in-flight — "
|
||||
f"sie zählen als erste Messung der Neukalibrierung."
|
||||
)
|
||||
|
||||
return (
|
||||
"✅ Adaptiver LLM-Timeout auf Baseline zurückgesetzt:\n"
|
||||
f"- Calls: {result['calls']}\n"
|
||||
f"- Mittelwert: {result['mean']:.2f}s\n"
|
||||
f"- Stddev: {result['stddev']:.2f}s\n"
|
||||
f"- Eskalations-Stufe: Basis\n"
|
||||
f"- Timeout: Failsafe (30s) bis genug Samples vorliegen"
|
||||
f"{in_flight_note}"
|
||||
)
|
||||
|
||||
# ── R5.1: Neue Standard-Hermes-::Befehle ───────────────────────────
|
||||
|
||||
async def _cmd_busy(self, room_id: str, args: str) -> str:
|
||||
|
||||
@@ -142,6 +142,13 @@ class AdaptiveLLMTimeout:
|
||||
self._accepted: int = 0
|
||||
self._rejected: int = 0
|
||||
|
||||
# F169: Anzahl aktuell laufender LLM-Calls (transient, nicht persistiert).
|
||||
# Dient der Race-Condition-Erkennung beim Reset: ein Reset während
|
||||
# eines laufenden Calls ist safe (Lock garantiert atomare Statistik),
|
||||
# wird aber geloggt, damit der Operator weiß, dass der laufende Call
|
||||
# als erste Messung der Neukalibrierung zählt.
|
||||
self._in_flight: int = 0
|
||||
|
||||
import threading
|
||||
self._lock = threading.Lock()
|
||||
|
||||
@@ -245,6 +252,51 @@ class AdaptiveLLMTimeout:
|
||||
with self._lock:
|
||||
self._reset_locked()
|
||||
|
||||
def reset_timeout(self, agent_name: str = "unknown") -> dict:
|
||||
"""F169: Reset der adaptiven Timeout-Kalibrierung auf Baseline.
|
||||
|
||||
Setzt Welford-Statistik (Mittelwert + Varianz), Call-Counter und
|
||||
Eskalations-Stufe auf die Initialwerte zurück. Der erste Call nach
|
||||
dem Reset kalibriert neu; bis genug Samples vorliegen, liefert
|
||||
``current_timeout()`` wieder den Failsafe (Default 30s).
|
||||
|
||||
Race-Condition-Schutz: Der Reset läuft unter ``self._lock`` und ist
|
||||
damit atomar gegenüber ``record()``/``current_timeout()``. Ein
|
||||
laufender LLM-Call (``_in_flight > 0``) wird NICHT blockiert — er
|
||||
wird als erste Messung der Neukalibrierung gewertet. Der Zustand
|
||||
wird geloggt, damit der Operator weiß, dass ein Call in-flight war.
|
||||
|
||||
Args:
|
||||
agent_name: Name des auslösenden Agenten (fürs Logging).
|
||||
|
||||
Returns:
|
||||
Dict mit dem Post-Reset-Zustand (calls, mean, stddev, in_flight).
|
||||
"""
|
||||
with self._lock:
|
||||
in_flight = self._in_flight
|
||||
self._reset_locked()
|
||||
logger.info(
|
||||
"F169 adaptive timeout reset by %s (in_flight_calls=%d)",
|
||||
agent_name, in_flight,
|
||||
)
|
||||
return {
|
||||
"calls": 0,
|
||||
"mean": 0.0,
|
||||
"stddev": 0.0,
|
||||
"in_flight": in_flight,
|
||||
}
|
||||
|
||||
def begin_call(self) -> None:
|
||||
"""F169: Markiert den Start eines LLM-Calls (in-flight-Zähler +1)."""
|
||||
with self._lock:
|
||||
self._in_flight += 1
|
||||
|
||||
def end_call(self) -> None:
|
||||
"""F169: Markiert das Ende eines LLM-Calls (in-flight-Zähler -1)."""
|
||||
with self._lock:
|
||||
if self._in_flight > 0:
|
||||
self._in_flight -= 1
|
||||
|
||||
def _reset_locked(self) -> None:
|
||||
"""Reset ohne Lock-Akquise (Caller hält ``self._lock``)."""
|
||||
self._n = 0.0
|
||||
@@ -299,6 +351,12 @@ class AdaptiveLLMTimeout:
|
||||
with self._lock:
|
||||
return self._model_key
|
||||
|
||||
@property
|
||||
def in_flight(self) -> int:
|
||||
"""F169: Anzahl aktuell laufender LLM-Calls."""
|
||||
with self._lock:
|
||||
return self._in_flight
|
||||
|
||||
# ── Intern ───────────────────────────────────────────────────────────
|
||||
|
||||
def _stddev_locked(self) -> float:
|
||||
|
||||
@@ -287,6 +287,8 @@ class OllamaLLMClient(LLMClient):
|
||||
|
||||
timeout = adaptive_timeout.current_timeout()
|
||||
t0 = time.monotonic()
|
||||
# F169: in-flight-Zähler für Race-Condition-Erkennung beim Reset.
|
||||
adaptive_timeout.begin_call()
|
||||
try:
|
||||
req = urllib.request.Request(
|
||||
url, data=payload, headers=headers, method="POST"
|
||||
@@ -315,6 +317,9 @@ class OllamaLLMClient(LLMClient):
|
||||
adaptive_timeout.record(duration, success=False)
|
||||
logger.error("Unexpected error in LLM call: %s", e)
|
||||
return None
|
||||
finally:
|
||||
# F169: in-flight-Zähler immer dekrementieren (auch bei Exception).
|
||||
adaptive_timeout.end_call()
|
||||
|
||||
def classify(self, text: str) -> Optional[str]:
|
||||
"""Call Ollama generate API. Returns category or None on any failure."""
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
"""
|
||||
F169 — Reset-Endpoint für adaptiven LLM-Timeout: A1c-Testkonzept.
|
||||
|
||||
@implements F-169
|
||||
|
||||
Testet die ``reset_timeout()``-Methode und den in-flight-Schutz:
|
||||
|
||||
1. Reset setzt Statistik zurück (n, mean, stddev, streak, escalated).
|
||||
2. Reset liefert Post-Reset-Zustand (calls=0, mean=0, stddev=0).
|
||||
3. Nach Reset: current_timeout() liefert wieder Failsafe (30s).
|
||||
4. Nach Reset: erster Call kalibriert neu (record akzeptiert).
|
||||
5. Reset während in-flight Call ist safe (Lock-Atomarität) — der
|
||||
in-flight-Zähler wird korrekt gemeldet, der Call zählt als erste
|
||||
Messung der Neukalibrierung.
|
||||
6. begin_call/end_call tracken den in-flight-Zähler korrekt
|
||||
(auch bei Exception via finally in classifier.py).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
||||
|
||||
from plugin.archivar.adaptive_timeout import AdaptiveLLMTimeout
|
||||
|
||||
|
||||
def _make(**kwargs):
|
||||
"""Frische Instanz ohne Persistenz für deterministische Tests."""
|
||||
kwargs.setdefault("state_path", None)
|
||||
kwargs.setdefault("failsafe_s", 30.0)
|
||||
kwargs.setdefault("sigma_band", 2.0)
|
||||
kwargs.setdefault("decay_tau_s", 7 * 24 * 3600)
|
||||
kwargs.setdefault("escalation_n", 2)
|
||||
kwargs.setdefault("min_samples", 3)
|
||||
return AdaptiveLLMTimeout(**kwargs)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# 1. Reset setzt Statistik zurück
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestResetTimeout:
|
||||
def test_reset_clears_statistics(self):
|
||||
t = _make()
|
||||
t.set_model("http://localhost:11434", "qwen2.5:7b")
|
||||
for s in [5.0, 5.0, 5.0, 5.0]:
|
||||
t.record(s)
|
||||
assert t.n == pytest.approx(4.0)
|
||||
assert t.mean == pytest.approx(5.0)
|
||||
|
||||
t.reset_timeout(agent_name="test-agent")
|
||||
|
||||
assert t.n == 0.0
|
||||
assert t.mean == 0.0
|
||||
assert t.stddev == 0.0
|
||||
assert t.streak == 0
|
||||
assert t.escalated is False
|
||||
assert t.accepted == 0
|
||||
assert t.rejected == 0
|
||||
|
||||
def test_reset_returns_post_reset_state(self):
|
||||
t = _make()
|
||||
t.record(5.0)
|
||||
result = t.reset_timeout(agent_name="test-agent")
|
||||
assert result == {
|
||||
"calls": 0,
|
||||
"mean": 0.0,
|
||||
"stddev": 0.0,
|
||||
"in_flight": 0,
|
||||
}
|
||||
|
||||
def test_reset_restores_failsafe(self):
|
||||
t = _make()
|
||||
for s in [5.0, 5.0, 5.0, 5.0]:
|
||||
t.record(s)
|
||||
assert t.current_timeout() == pytest.approx(5.0)
|
||||
|
||||
t.reset_timeout(agent_name="test-agent")
|
||||
assert t.current_timeout() == 30.0 # zurück auf Failsafe
|
||||
|
||||
def test_reset_clears_escalation(self):
|
||||
t = _make()
|
||||
for s in [4.9, 5.0, 5.1, 4.9, 5.0, 5.1]:
|
||||
t.record(s)
|
||||
t.record(50.0) # streak=1
|
||||
t.record(60.0) # streak=2 → Eskalation
|
||||
assert t.escalated is True
|
||||
|
||||
t.reset_timeout(agent_name="test-agent")
|
||||
assert t.escalated is False
|
||||
assert t.streak == 0
|
||||
|
||||
def test_first_call_after_reset_recalibrates(self):
|
||||
t = _make()
|
||||
for s in [5.0, 5.0, 5.0, 5.0]:
|
||||
t.record(s)
|
||||
t.reset_timeout(agent_name="test-agent")
|
||||
|
||||
# Erster Call nach Reset: n=0 → alles akzeptiert (Kalibrierung).
|
||||
t.record(7.0)
|
||||
assert t.n == pytest.approx(1.0)
|
||||
assert t.mean == pytest.approx(7.0)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# 2. Reset während in-flight Call ist safe (Race-Condition-Schutz)
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestResetDuringInFlightCall:
|
||||
def test_reset_reports_in_flight_calls(self):
|
||||
t = _make()
|
||||
t.begin_call()
|
||||
result = t.reset_timeout(agent_name="test-agent")
|
||||
assert result["in_flight"] == 1
|
||||
# Statistik ist trotzdem zurückgesetzt.
|
||||
assert result["calls"] == 0
|
||||
assert result["mean"] == 0.0
|
||||
|
||||
def test_reset_does_not_block_in_flight_call(self):
|
||||
"""Reset ist atomar unter Lock — der in-flight Call wird nicht blockiert.
|
||||
|
||||
Der laufende Call endet normal und zählt als erste Messung der
|
||||
Neukalibrierung (record() nach dem Reset).
|
||||
"""
|
||||
t = _make()
|
||||
for s in [5.0, 5.0, 5.0, 5.0]:
|
||||
t.record(s)
|
||||
|
||||
# Call beginnt (in-flight=1).
|
||||
t.begin_call()
|
||||
# Reset während der Call läuft.
|
||||
t.reset_timeout(agent_name="test-agent")
|
||||
assert t.n == 0.0 # Statistik zurückgesetzt
|
||||
|
||||
# Call endet und speist seine Messung als erste Neukalibrierung ein.
|
||||
t.record(6.0)
|
||||
t.end_call()
|
||||
assert t.n == pytest.approx(1.0)
|
||||
assert t.mean == pytest.approx(6.0)
|
||||
assert t.in_flight == 0
|
||||
|
||||
def test_end_call_never_goes_negative(self):
|
||||
t = _make()
|
||||
t.end_call() # kein begin_call vorher → bleibt 0
|
||||
assert t.in_flight == 0
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# 3. begin_call/end_call Tracking
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestInFlightTracking:
|
||||
def test_begin_end_roundtrip(self):
|
||||
t = _make()
|
||||
assert t.in_flight == 0
|
||||
t.begin_call()
|
||||
t.begin_call()
|
||||
assert t.in_flight == 2
|
||||
t.end_call()
|
||||
assert t.in_flight == 1
|
||||
t.end_call()
|
||||
assert t.in_flight == 0
|
||||
|
||||
def test_in_flight_not_persisted(self, tmp_path):
|
||||
"""in-flight ist transient — wird nicht in den State geschrieben."""
|
||||
state_path = str(tmp_path / "adaptive_timeout_state.json")
|
||||
t = _make(state_path=state_path)
|
||||
t.begin_call()
|
||||
t.record(5.0) # triggert _save_locked
|
||||
|
||||
# Neue Instanz lädt State — in_flight muss 0 sein (transient).
|
||||
t2 = _make(state_path=state_path)
|
||||
assert t2.in_flight == 0
|
||||
@@ -1050,6 +1050,62 @@ ROCKETCHAT_BROADCAST_SCHEMA = {
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# F169: rocketchat_reset_timeout — adaptiven LLM-Timeout auf Baseline zurücksetzen
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _handle_rocketchat_reset_timeout(args: dict, **kw) -> str:
|
||||
"""F169: Setzt die adaptive LLM-Timeout-Kalibrierung auf Baseline zurück.
|
||||
|
||||
@implements F-169
|
||||
|
||||
Setzt Welford-Statistik (Mittelwert + Varianz), Call-Counter und
|
||||
Eskalations-Stufe zurück. Der erste Call nach dem Reset kalibriert neu;
|
||||
bis genug Samples vorliegen, gilt wieder der Failsafe (30s).
|
||||
|
||||
Nützlich vor Tests (z.B. F172 Human-Tempo-Pacing), damit die Kalibrierung
|
||||
nicht auf Bot-Tempo statt Mensch-Tempo läuft.
|
||||
"""
|
||||
try:
|
||||
from archivar.adaptive_timeout import adaptive_timeout
|
||||
except Exception as exc:
|
||||
return tool_error(f"adaptive_timeout nicht verfügbar: {type(exc).__name__}: {exc}")
|
||||
|
||||
agent_name = str(args.get("agent_name") or "rocketchat_reset_timeout").strip()
|
||||
result = adaptive_timeout.reset_timeout(agent_name=agent_name)
|
||||
return tool_result({
|
||||
"success": True,
|
||||
"message": "Adaptive timeout reset to baseline",
|
||||
"calls": result["calls"],
|
||||
"mean": result["mean"],
|
||||
"stddev": result["stddev"],
|
||||
"in_flight": result["in_flight"],
|
||||
})
|
||||
|
||||
|
||||
ROCKETCHAT_RESET_TIMEOUT_SCHEMA = {
|
||||
"name": "rocketchat_reset_timeout",
|
||||
"description": (
|
||||
"Reset the adaptive LLM timeout calibration to baseline (F169). "
|
||||
"Clears the Welford statistics (mean + variance), the call counter, "
|
||||
"and the escalation level. The first call after the reset recalibrates; "
|
||||
"until enough samples are collected, the failsafe (30s) applies. "
|
||||
"Use this before starting a test so the calibration reflects human "
|
||||
"tempo instead of bot tempo."
|
||||
),
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"agent_name": {
|
||||
"type": "string",
|
||||
"description": "Name of the agent triggering the reset (for logging).",
|
||||
},
|
||||
},
|
||||
"required": [],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Registration helpers for the plugin register() function
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -1063,6 +1119,7 @@ _TOOLS = (
|
||||
("rocketchat_download", ROCKETCHAT_DOWNLOAD_SCHEMA, _handle_rocketchat_download, "📥"),
|
||||
("rocketchat_files", ROCKETCHAT_FILES_SCHEMA, _handle_rocketchat_files, "📁"),
|
||||
("rocketchat_broadcast", ROCKETCHAT_BROADCAST_SCHEMA, _handle_rocketchat_broadcast, "📢"),
|
||||
("rocketchat_reset_timeout", ROCKETCHAT_RESET_TIMEOUT_SCHEMA, _handle_rocketchat_reset_timeout, "⏱️"),
|
||||
)
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user