fix(presence): pgrep False-Positive + DDP 429-Verbesserung (V8.8)

Bug 1 — pgrep argv-basierter Scanner:
- _pgrep_hermes_subagents() nutzt jetzt argv-basierte Erkennung
  statt Substring-Suche in der kompletten cmdline
- 'chat' und '--profile' muessen eigene argv-Elemente sein
- argv[0] basename pruefen: 'hermes', 'python', 'python3'
- python: '-m hermes_cli.main' oder hermes-Skript-Pfad in argv
- Gateway-PID aus gateway_state.json ausschliessen
- Neue _read_gateway_pid() Hilfsmethode
- 6 neue False-Positive-Tests (bash grep, snap-path, gateway)

Bug 2 — DDP 429 Circuit-Breaker + Pulse-Interval:
- Circuit-Breaker threshold: 3 → 1 (sofort nach erstem 429)
- DDP-Timeout: 2.0s → 1.0s (schneller fail)
- Mode-abhaengige Pulse-Intervalle: away=3.0s, busy=1.5s
- set_pulse_target() passt dynamisch das Interval an

Tests: 144/144 passed
This commit is contained in:
Bernd (Hermes)
2026-08-02 13:51:31 +02:00
parent 30015f0cfe
commit c3c995765f
3 changed files with 306 additions and 66 deletions
+21 -38
View File
@@ -2263,8 +2263,8 @@ class TestCircuitBreakerStateTransitions:
assert pc.get_breaker_state() == "CLOSED"
assert pc.get_consecutive_429s() == 0
def test_three_consecutive_429s_open_breaker(self):
"""3 aufeinanderfolgende 429 → CLOSED→OPEN, pulse_interval steigt."""
def test_one_429_opens_breaker(self):
"""V8.8: 1×429 → CLOSED→OPEN sofort (threshold=1)."""
from plugin.archivar.presence_engine import PulseController
mock_ddp = MagicMock()
@@ -2277,20 +2277,10 @@ class TestCircuitBreakerStateTransitions:
base_interval = pc.get_effective_pulse_interval()
# Tick 1: 429 #1
pc._pulse_tick()
assert pc.get_breaker_state() == "CLOSED"
assert pc.get_consecutive_429s() == 1
# Tick 2: 429 #2
pc._pulse_tick()
assert pc.get_breaker_state() == "CLOSED"
assert pc.get_consecutive_429s() == 2
# Tick 3: 429 #3 → OPEN
# Tick 1: 429 #1 → OPEN (threshold=1)
pc._pulse_tick()
assert pc.get_breaker_state() == "OPEN"
assert pc.get_consecutive_429s() == 3
assert pc.get_consecutive_429s() == 1
# pulse_interval sollte auf backoff_level=0 → 5.0s gestiegen sein
assert pc.get_effective_pulse_interval() > base_interval
@@ -2305,9 +2295,8 @@ class TestCircuitBreakerStateTransitions:
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
pc.bind_ddp(mock_ddp)
# 3×429 → OPEN
for _ in range(3):
pc._pulse_tick()
# 1×429 → OPEN (threshold=1)
pc._pulse_tick()
assert pc.get_breaker_state() == "OPEN"
# Weitere Ticks werden geblockt (kein DDP-Call mehr)
@@ -2325,12 +2314,12 @@ class TestCircuitBreakerHalfOpen:
"""HALF_OPEN Test-Ping success → CLOSED, pulse_interval reset."""
from plugin.archivar.presence_engine import PulseController
# DDP wirft 3×429, dann success
# DDP wirft 1×429, dann success (threshold=1)
call_count = [0]
def ddp_side_effect(status):
call_count[0] += 1
if call_count[0] <= 3:
if call_count[0] <= 1:
raise Exception("HTTP 429 Too Many Requests")
return True
@@ -2341,9 +2330,8 @@ class TestCircuitBreakerHalfOpen:
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
pc.bind_ddp(mock_ddp)
# 3×429 → OPEN
for _ in range(3):
pc._pulse_tick()
# 1×429 → OPEN (threshold=1)
pc._pulse_tick()
assert pc.get_breaker_state() == "OPEN"
# Simuliere Cooldown-Ablauf: setze _breaker_opened_at in die Vergangenheit
@@ -2368,9 +2356,8 @@ class TestCircuitBreakerHalfOpen:
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
pc.bind_ddp(mock_ddp)
# 3×429 → OPEN (backoff_level=0, pulse_interval=5.0)
for _ in range(3):
pc._pulse_tick()
# 1×429 → OPEN (threshold=1, backoff_level=0, pulse_interval=5.0)
pc._pulse_tick()
assert pc.get_breaker_state() == "OPEN"
first_open_interval = pc.get_effective_pulse_interval()
@@ -2399,9 +2386,8 @@ class TestCircuitBreakerSustained429:
intervals_seen = [pc.get_effective_pulse_interval()]
# Zyklus 1: 3×429 → OPEN (backoff 0: 5.0s)
for _ in range(3):
pc._pulse_tick()
# Zyklus 1: 1×429 → OPEN (threshold=1, backoff 0: 5.0s)
pc._pulse_tick()
intervals_seen.append(pc.get_effective_pulse_interval())
# Cooldown ablaufen lassen → HALF_OPEN → 429 → OPEN (backoff 1: 15.0s)
@@ -2438,9 +2424,8 @@ class TestCircuitBreakerSustained429:
# 5 Zyklen OPEN→HALF_OPEN→OPEN (mehr als backoff_intervals Länge)
for cycle in range(5):
# 3×429 → OPEN
for _ in range(3):
pc._pulse_tick()
# 1×429 → OPEN (threshold=1)
pc._pulse_tick()
# Cooldown ablaufen → HALF_OPEN → 429 → OPEN
pc._breaker_opened_at = time.monotonic() - pc._breaker_cooldown_s - 1.0
pc._pulse_tick()
@@ -2521,9 +2506,8 @@ class TestCircuitBreakerDdpErrorClassification:
pc.bind_ddp(mock_ddp)
pc.bind_rest(mock_rest)
# 3×429 DDP → OPEN, REST wurde NIE aufgerufen
for _ in range(3):
pc._pulse_tick()
# 1×429 DDP → OPEN (threshold=1), REST wurde NIE aufgerufen
pc._pulse_tick()
# REST wurde NICHT aufgerufen (429 blockiert Fallback)
mock_rest._request.assert_not_called()
@@ -2559,7 +2543,7 @@ class TestCircuitBreakerRecordSuccess:
def ddp_side_effect(status):
call_count[0] += 1
if call_count[0] <= 3:
if call_count[0] <= 1:
raise Exception("HTTP 429 Too Many Requests")
return True
@@ -2570,9 +2554,8 @@ class TestCircuitBreakerRecordSuccess:
pc = PulseController(pulse_interval=1.5, _clamp_pulse=False)
pc.bind_ddp(mock_ddp)
# 3×429 → OPEN (pulse_interval=5.0)
for _ in range(3):
pc._pulse_tick()
# 1×429 → OPEN (threshold=1, pulse_interval=5.0)
pc._pulse_tick()
assert pc.get_breaker_state() == "OPEN"
assert pc.get_effective_pulse_interval() == 5.0
@@ -162,21 +162,25 @@ class TestHoneymoonExpiredWithBgTasks:
# ═══════════════════════════════════════════════════════════════════════════
class TestPgrepHermesSubagents:
"""Test 6: _pgrep_hermes_subagents() erkennt hermes chat --profile Prozesse."""
"""Test 6: _pgrep_hermes_subagents() erkennt hermes chat --profile Prozesse.
def test_pgrep_finds_hermes_chat_profile_process(self):
"""_pgrep_hermes_subagents() findet einen simulierten hermes-Prozess."""
V8.8: argv-basierter Scanner — verhindert False-Positives auf
Shell-Befehle die 'hermes'+'chat'+'--profile' als Text enthalten.
"""
def test_pgrep_finds_hermes_binary_chat_profile(self):
"""_pgrep_hermes_subagents() findet 'hermes chat --profile rainer'."""
from plugin.archivar.presence_engine import DetectionTimer
own_pid = os.getpid()
# Mock /proc: nur ein simulierter hermes chat --profile Prozess
# Mock /proc: ein echter hermes chat --profile Prozess
mock_proc_entries = ["1", "2", str(own_pid), "99999", "12345"]
def mock_cmdline_read(pid_dir):
"""Simuliere /proc/<pid>/cmdline."""
if pid_dir == "12345":
return b"python\x00hermes\x00chat\x00--profile\x00miguel\x00--model\x00deepseek\x00"
# argv: ["hermes", "chat", "--profile", "rainer"]
return b"hermes\x00chat\x00--profile\x00rainer\x00"
elif pid_dir == str(own_pid):
return b"python\x00pytest\x00"
else:
@@ -184,9 +188,7 @@ class TestPgrepHermesSubagents:
with patch("os.listdir", return_value=mock_proc_entries):
with patch("builtins.open") as mock_open:
# Simuliere open() für /proc/<pid>/cmdline
def open_side_effect(path, mode="r"):
# Extrahiere PID aus Pfad: /proc/<pid>/cmdline
parts = path.split("/")
if len(parts) >= 3 and parts[1] == "proc":
pid_dir = parts[2]
@@ -197,11 +199,178 @@ class TestPgrepHermesSubagents:
mock_open.side_effect = open_side_effect
count = DetectionTimer._pgrep_hermes_subagents()
# Mock _read_gateway_pid → None (kein Gateway)
with patch.object(DetectionTimer, '_read_gateway_pid', return_value=None):
count = DetectionTimer._pgrep_hermes_subagents()
# Sollte 1 Prozess finden (PID 12345, nicht own_pid)
assert count == 1, f"Expected 1, got {count}"
def test_pgrep_finds_python_m_hermes_cli_chat_profile(self):
"""_pgrep_hermes_subagents() findet 'python -m hermes_cli.main chat --profile miguel'."""
from plugin.archivar.presence_engine import DetectionTimer
own_pid = os.getpid()
mock_proc_entries = ["1", str(own_pid), "12345"]
def mock_cmdline_read(pid_dir):
if pid_dir == "12345":
# argv: ["python", "-m", "hermes_cli.main", "chat", "--profile", "miguel"]
return b"python\x00-m\x00hermes_cli.main\x00chat\x00--profile\x00miguel\x00"
elif pid_dir == str(own_pid):
return b"python\x00pytest\x00"
return b"bash\x00"
with patch("os.listdir", return_value=mock_proc_entries):
with patch("builtins.open") as mock_open:
def open_side_effect(path, mode="r"):
parts = path.split("/")
if len(parts) >= 3 and parts[1] == "proc":
pid_dir = parts[2]
mock_file = MagicMock()
mock_file.__enter__.return_value.read.return_value = mock_cmdline_read(pid_dir)
return mock_file
raise FileNotFoundError(path)
mock_open.side_effect = open_side_effect
with patch.object(DetectionTimer, '_read_gateway_pid', return_value=None):
count = DetectionTimer._pgrep_hermes_subagents()
assert count == 1, f"Expected 1, got {count}"
def test_pgrep_false_positive_bash_grep(self):
"""V8.8: 'bash -c grep hermes.*chat.*--profile' → KEIN match (False-Positive)."""
from plugin.archivar.presence_engine import DetectionTimer
own_pid = os.getpid()
mock_proc_entries = ["1", str(own_pid), "12345"]
def mock_cmdline_read(pid_dir):
if pid_dir == "12345":
# argv: ["bash", "-c", "grep hermes.*chat.*--profile /var/log/..."]
return b"bash\x00-c\x00grep hermes.*chat.*--profile /var/log/syslog\x00"
elif pid_dir == str(own_pid):
return b"python\x00pytest\x00"
return b"bash\x00"
with patch("os.listdir", return_value=mock_proc_entries):
with patch("builtins.open") as mock_open:
def open_side_effect(path, mode="r"):
parts = path.split("/")
if len(parts) >= 3 and parts[1] == "proc":
pid_dir = parts[2]
mock_file = MagicMock()
mock_file.__enter__.return_value.read.return_value = mock_cmdline_read(pid_dir)
return mock_file
raise FileNotFoundError(path)
mock_open.side_effect = open_side_effect
with patch.object(DetectionTimer, '_read_gateway_pid', return_value=None):
count = DetectionTimer._pgrep_hermes_subagents()
assert count == 0, f"Expected 0 (false positive), got {count}"
def test_pgrep_false_positive_hermes_snap_path(self):
"""V8.8: '/tmp/hermes-snap-xxx bash -c ...' → KEIN match (False-Positive)."""
from plugin.archivar.presence_engine import DetectionTimer
own_pid = os.getpid()
mock_proc_entries = ["1", str(own_pid), "12345"]
def mock_cmdline_read(pid_dir):
if pid_dir == "12345":
# argv: ["/tmp/hermes-snap-xxx", "bash", "-c", "hermes chat --profile"]
return b"/tmp/hermes-snap-abc123\x00bash\x00-c\x00hermes chat --profile rainer\x00"
elif pid_dir == str(own_pid):
return b"python\x00pytest\x00"
return b"bash\x00"
with patch("os.listdir", return_value=mock_proc_entries):
with patch("builtins.open") as mock_open:
def open_side_effect(path, mode="r"):
parts = path.split("/")
if len(parts) >= 3 and parts[1] == "proc":
pid_dir = parts[2]
mock_file = MagicMock()
mock_file.__enter__.return_value.read.return_value = mock_cmdline_read(pid_dir)
return mock_file
raise FileNotFoundError(path)
mock_open.side_effect = open_side_effect
with patch.object(DetectionTimer, '_read_gateway_pid', return_value=None):
count = DetectionTimer._pgrep_hermes_subagents()
assert count == 0, f"Expected 0 (false positive), got {count}"
def test_pgrep_false_positive_gateway_process(self):
"""V8.8: Gateway 'python -m hermes_cli.main gateway run' → KEIN match."""
from plugin.archivar.presence_engine import DetectionTimer
own_pid = os.getpid()
mock_proc_entries = ["1", str(own_pid), "12345"]
def mock_cmdline_read(pid_dir):
if pid_dir == "12345":
# argv: ["python", "-m", "hermes_cli.main", "gateway", "run"]
return b"python\x00-m\x00hermes_cli.main\x00gateway\x00run\x00"
elif pid_dir == str(own_pid):
return b"python\x00pytest\x00"
return b"bash\x00"
with patch("os.listdir", return_value=mock_proc_entries):
with patch("builtins.open") as mock_open:
def open_side_effect(path, mode="r"):
parts = path.split("/")
if len(parts) >= 3 and parts[1] == "proc":
pid_dir = parts[2]
mock_file = MagicMock()
mock_file.__enter__.return_value.read.return_value = mock_cmdline_read(pid_dir)
return mock_file
raise FileNotFoundError(path)
mock_open.side_effect = open_side_effect
with patch.object(DetectionTimer, '_read_gateway_pid', return_value=None):
count = DetectionTimer._pgrep_hermes_subagents()
assert count == 0, f"Expected 0 (gateway, no chat), got {count}"
def test_pgrep_excludes_gateway_pid(self):
"""V8.8: Gateway-PID aus gateway_state.json wird ausgeschlossen."""
from plugin.archivar.presence_engine import DetectionTimer
own_pid = os.getpid()
gateway_pid = 12345
mock_proc_entries = ["1", str(own_pid), str(gateway_pid)]
def mock_cmdline_read(pid_dir):
if pid_dir == str(gateway_pid):
# Sieht aus wie hermes chat --profile, ist aber Gateway
return b"hermes\x00chat\x00--profile\x00miguel\x00"
elif pid_dir == str(own_pid):
return b"python\x00pytest\x00"
return b"bash\x00"
with patch("os.listdir", return_value=mock_proc_entries):
with patch("builtins.open") as mock_open:
def open_side_effect(path, mode="r"):
parts = path.split("/")
if len(parts) >= 3 and parts[1] == "proc":
pid_dir = parts[2]
mock_file = MagicMock()
mock_file.__enter__.return_value.read.return_value = mock_cmdline_read(pid_dir)
return mock_file
raise FileNotFoundError(path)
mock_open.side_effect = open_side_effect
with patch.object(DetectionTimer, '_read_gateway_pid', return_value=gateway_pid):
count = DetectionTimer._pgrep_hermes_subagents()
assert count == 0, f"Expected 0 (gateway excluded), got {count}"
def test_pgrep_returns_zero_when_no_hermes_processes(self):
"""_pgrep_hermes_subagents() → 0 wenn keine hermes-Prozesse."""
from plugin.archivar.presence_engine import DetectionTimer
@@ -227,7 +396,8 @@ class TestPgrepHermesSubagents:
mock_open.side_effect = open_side_effect
count = DetectionTimer._pgrep_hermes_subagents()
with patch.object(DetectionTimer, '_read_gateway_pid', return_value=None):
count = DetectionTimer._pgrep_hermes_subagents()
assert count == 0, f"Expected 0, got {count}"
def test_pgrep_excludes_own_pid(self):
@@ -240,7 +410,7 @@ class TestPgrepHermesSubagents:
def mock_cmdline_read(pid_dir):
# Eigener Prozess hat hermes chat --profile in cmdline
return b"python\x00hermes\x00chat\x00--profile\x00miguel\x00"
return b"hermes\x00chat\x00--profile\x00miguel\x00"
with patch("os.listdir", return_value=mock_proc_entries):
with patch("builtins.open") as mock_open:
@@ -255,7 +425,8 @@ class TestPgrepHermesSubagents:
mock_open.side_effect = open_side_effect
count = DetectionTimer._pgrep_hermes_subagents()
with patch.object(DetectionTimer, '_read_gateway_pid', return_value=None):
count = DetectionTimer._pgrep_hermes_subagents()
# Eigene PID wird ausgeschlossen → 0
assert count == 0, f"Expected 0 (own PID excluded), got {count}"
@@ -268,9 +439,9 @@ class TestPgrepHermesSubagents:
def mock_cmdline_read(pid_dir):
if pid_dir == "55555":
return b"python\x00hermes\x00serve\x00" # hermes aber kein chat
return b"hermes\x00serve\x00" # hermes binary aber kein chat
elif pid_dir == "66666":
return b"python\x00chat\x00--profile\x00" # chat aber kein hermes
return b"python\x00chat\x00--profile\x00" # chat+profile aber argv0=python ohne -m hermes_cli
elif pid_dir == str(own_pid):
return b"python\x00pytest\x00"
return b"bash\x00"
@@ -288,7 +459,8 @@ class TestPgrepHermesSubagents:
mock_open.side_effect = open_side_effect
count = DetectionTimer._pgrep_hermes_subagents()
with patch.object(DetectionTimer, '_read_gateway_pid', return_value=None):
count = DetectionTimer._pgrep_hermes_subagents()
# Keiner der Prozesse hat hermes+chat+--profile → 0
assert count == 0, f"Expected 0, got {count}"
@@ -317,7 +489,8 @@ class TestPgrepHermesSubagents:
mock_open.side_effect = open_side_effect
count = DetectionTimer._pgrep_hermes_subagents()
with patch.object(DetectionTimer, '_read_gateway_pid', return_value=None):
count = DetectionTimer._pgrep_hermes_subagents()
# PermissionError → Prozess wird ignoriert, count=0
assert count == 0, f"Expected 0, got {count}"