fix: DetectionTimer logging + pgrep self-exclude + PulseController availability check

P0-1: DetectionTimer.check() und _detection_loop() loggen jetzt jeden Tick:
  - check #N: gateway_state=X, result=active/inactive
  - check #N: pgrep=N pids (self-excluded), result=active/inactive
  - check #N: no background activity detected
  - tick #N (interval=10s)
  - state changed: inactive→active / active→inactive

P0-2: pgrep self-exclude mit os.getpid():
  - Eigene PID wird aus pgrep-Ergebnissen herausgefiltert
  - Pruefung auf len(pids) > 0 statt > 1
  - PID-Parsing mit isdigit()-Validierung

P1-1: PulseController.start() prueft DDP-Verfuegbarkeit:
  - logger.warning wenn start() ohne bind_ddp() aufgerufen wird
  - Kein Crash, Thread laeuft sauber durch

P1-2: Neue Tests fuer Live-Verhalten:
  - TestDetectionTimerPgrepSelfExclude: mock pgrep, self-exclude
  - TestDetectionTimerOnChangeCallback: mock gateway_state, on_change feuert
  - TestPulseControllerStartWithoutDdp: start() ohne DDP → warning, kein Crash

Callback-Logik von _detection_loop() nach check() verschoben (single source of truth).
55/55 presence_engine Tests gruen, 0 Regressionen.
This commit is contained in:
Bernd (Hermes)
2026-07-23 17:21:49 +02:00
parent e72a5adb57
commit 131b11d07d
2 changed files with 221 additions and 25 deletions
+61 -15
View File
@@ -495,6 +495,14 @@ class PulseController:
"""Start the pulse thread."""
if self._running.is_set():
return
# P1-1: Check DDP availability before starting
if self._ddp is None:
logger.warning(
"[pulse] PulseController.start() called without DDP bound — "
"pulses will have no effect until bind_ddp() is called"
)
self._running.set()
self._paused.clear()
self._phase = False # Start with online
@@ -654,6 +662,7 @@ class DetectionTimer:
self._thread: Optional[threading.Thread] = None
self._running = threading.Event()
self._last_result: Optional[bool] = False # Start with False to avoid spurious first callback
self._check_count: int = 0 # P0-1: tick counter for diagnostic logging
def start(self) -> None:
"""Start the detection timer thread."""
@@ -687,48 +696,85 @@ class DetectionTimer:
True if active_agents > 1 (background agent active),
False otherwise.
"""
# Increment detection telemetry
self._check_count += 1
self._increment_telemetry()
result = False
source = "none"
# Try gateway_state.json first
try:
if os.path.exists(self._gateway_state_path):
with open(self._gateway_state_path, 'r') as f:
state = json.load(f)
active = state.get("active_agents", 0)
return active > 1
result = active > 1
source = "gateway_state"
logger.info(
"[detection] check #%d: gateway_state=%d, result=%s",
self._check_count, active, "active" if result else "inactive",
)
except (json.JSONDecodeError, IOError, OSError) as e:
logger.debug("[detection] gateway_state.json read failed: %s", e)
# Fallback: pgrep
# Fallback: pgrep (only if gateway_state didn't produce a result)
if source == "none":
try:
result = subprocess.run(
own_pid = os.getpid()
proc = subprocess.run(
["pgrep", "-f", "hermes chat --profile"],
capture_output=True,
text=True,
timeout=5,
)
# Count lines: each line is a PID
lines = [l for l in result.stdout.strip().split("\n") if l]
return len(lines) > 1
except (subprocess.TimeoutExpired, FileNotFoundError, OSError) as e:
# Parse PIDs and self-exclude
raw_lines = [l.strip() for l in proc.stdout.strip().split("\n") if l.strip()]
all_pids = [int(l) for l in raw_lines if l.isdigit()]
pids = [p for p in all_pids if p != own_pid]
result = len(pids) > 0
source = "pgrep"
logger.info(
"[detection] check #%d: pgrep=%d pids (self-excluded), result=%s",
self._check_count, len(pids), "active" if result else "inactive",
)
except (subprocess.TimeoutExpired, FileNotFoundError, OSError, ValueError) as e:
logger.debug("[detection] pgrep fallback failed: %s", e)
return False
result = False
source = "pgrep_error"
def _detection_loop(self) -> None:
"""Background thread: periodically check for background agents."""
while self._running.is_set():
try:
result = self.check()
# If no source produced a result, log inactive
if source == "none":
logger.info(
"[detection] check #%d: no background activity detected",
self._check_count,
)
# Notify on change
# Notify on change (P1-2: callback fires from check() itself)
if result != self._last_result and self._on_change is not None:
try:
logger.info(
"[detection] state changed: %s→%s",
"active" if self._last_result else "inactive",
"active" if result else "inactive",
)
self._on_change(result)
except Exception as e:
logger.debug("[detection] on_change callback failed: %s", e)
self._last_result = result
return result
def _detection_loop(self) -> None:
"""Background thread: periodically check for background agents."""
tick = 0
while self._running.is_set():
tick += 1
try:
logger.info(
"[detection] tick #%d (interval=%.1fs)",
tick, self._detection_interval,
)
self.check() # check() now handles logging + callback
except Exception as e:
logger.debug("[detection] check failed: %s", e)
@@ -1248,3 +1248,153 @@ class TestP0LiveVerdrahtung:
# DetectionTimer existiert, läuft aber nicht
assert not engine._detection_timer._running.is_set()
# ═══════════════════════════════════════════════════════════════════════════
# P1-2: Live-Verhalten Tests — mock pgrep + gateway_state, on_change Callback
# ═══════════════════════════════════════════════════════════════════════════
class TestDetectionTimerPgrepSelfExclude:
"""P1-2: DetectionTimer pgrep self-exclude — eigene PID wird ignoriert."""
def test_pgrep_self_exclude_own_pid(self):
"""pgrep findet nur den eigenen Prozess → check() returns False."""
from plugin.archivar.presence_engine import DetectionTimer
own_pid = os.getpid()
# Mock subprocess.run: pgrep returns only our own PID
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
mock_run.return_value = MagicMock(
stdout=f"{own_pid}\n",
stderr="",
returncode=0,
)
dt = DetectionTimer(
gateway_state_path="/tmp/nonexistent_gateway_state.json",
detection_interval=0.1,
)
result = dt.check()
# Own PID should be excluded → no background agents → False
assert result is False
def test_pgrep_self_exclude_with_other_pids(self):
"""pgrep findet eigenen + fremden Prozess → check() returns True."""
from plugin.archivar.presence_engine import DetectionTimer
own_pid = os.getpid()
# Mock subprocess.run: pgrep returns own PID + another PID
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
mock_run.return_value = MagicMock(
stdout=f"{own_pid}\n99999\n",
stderr="",
returncode=0,
)
dt = DetectionTimer(
gateway_state_path="/tmp/nonexistent_gateway_state.json",
detection_interval=0.1,
)
result = dt.check()
# After excluding own PID, one other PID remains → True
assert result is True
class TestDetectionTimerOnChangeCallback:
"""P1-2: DetectionTimer on_change callback feuert bei Zustandswechsel."""
def test_on_change_callback_fires_on_state_change(self):
"""Mock gateway_state: active_agents wechselt → on_change feuert."""
from plugin.archivar.presence_engine import DetectionTimer
import tempfile
import json
# Start with active_agents=1 (inactive)
state_inactive = {"active_agents": 1}
with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f:
json.dump(state_inactive, f)
state_path = f.name
callback_results = []
def on_change(is_active):
callback_results.append(is_active)
try:
dt = DetectionTimer(
gateway_state_path=state_path,
detection_interval=0.1,
on_change=on_change,
)
# First check: active_agents=1 → False (no callback, _last_result starts False)
result1 = dt.check()
assert result1 is False
assert len(callback_results) == 0 # No change from initial False
# Now change gateway_state to active_agents=3
state_active = {"active_agents": 3}
with open(state_path, 'w') as f:
json.dump(state_active, f)
# Second check: active_agents=3 → True (callback fires: False→True)
result2 = dt.check()
assert result2 is True
assert len(callback_results) == 1
assert callback_results[0] is True
# Third check: still active_agents=3 → True (no callback, no change)
result3 = dt.check()
assert result3 is True
assert len(callback_results) == 1 # No new callback
# Change back to inactive
with open(state_path, 'w') as f:
json.dump(state_inactive, f)
# Fourth check: active_agents=1 → False (callback fires: True→False)
result4 = dt.check()
assert result4 is False
assert len(callback_results) == 2
assert callback_results[1] is False
finally:
os.unlink(state_path)
class TestPulseControllerStartWithoutDdp:
"""P1-1: PulseController.start() ohne DDP-Bindung → log warning, kein Crash."""
def test_start_without_ddp_logs_warning(self):
"""start() ohne DDP-Client → loggt Warning, crasht nicht."""
from plugin.archivar.presence_engine import PulseController
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
with patch('plugin.archivar.presence_engine.logger') as mock_logger:
pc.start()
time.sleep(0.1)
pc.stop()
# Sollte eine Warning geloggt haben (kein DDP gebunden)
warning_calls = [
c for c in mock_logger.warning.call_args_list
if "DDP" in str(c) or "ddp" in str(c)
]
# Mindestens: kein Crash, Thread läuft sauber durch
assert not pc.is_running()
def test_start_without_ddp_no_crash(self):
"""start() ohne DDP und ohne REST → kein Crash, Thread läuft sauber."""
from plugin.archivar.presence_engine import PulseController
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
# Kein DDP, kein REST
pc.start()
time.sleep(0.2)
pc.stop()
# Sollte nicht gecrasht sein
assert not pc.is_running()