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:
Bernd (Hermes)
2026-09-05 12:16:57 +02:00
parent b957a35402
commit 44b2ada193
5 changed files with 339 additions and 0 deletions
+58
View File
@@ -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:
+5
View File
@@ -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