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:
@@ -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
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["pgrep", "-f", "hermes chat --profile"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=5,
|
||||
# Fallback: pgrep (only if gateway_state didn't produce a result)
|
||||
if source == "none":
|
||||
try:
|
||||
own_pid = os.getpid()
|
||||
proc = subprocess.run(
|
||||
["pgrep", "-f", "hermes chat --profile"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=5,
|
||||
)
|
||||
# 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)
|
||||
result = False
|
||||
source = "pgrep_error"
|
||||
|
||||
# If no source produced a result, log inactive
|
||||
if source == "none":
|
||||
logger.info(
|
||||
"[detection] check #%d: no background activity detected",
|
||||
self._check_count,
|
||||
)
|
||||
# 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:
|
||||
logger.debug("[detection] pgrep fallback failed: %s", e)
|
||||
return False
|
||||
|
||||
# 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:
|
||||
result = self.check()
|
||||
|
||||
# Notify on change
|
||||
if result != self._last_result and self._on_change is not None:
|
||||
try:
|
||||
self._on_change(result)
|
||||
except Exception as e:
|
||||
logger.debug("[detection] on_change callback failed: %s", e)
|
||||
|
||||
self._last_result = result
|
||||
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)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user