fix: Presence-Engine Stale-Recovery — complete() aus finally entfernt + PID-Tracking
5 Schritte:
1. adapter.py: complete('background_task') aus finally-Block entfernt.
Der Turn endet bevor der Background-Prozess endet — register() beim
Turn-Start bleibt, Stale-Recovery räumt tote Einträge auf.
2. subagent_tracker.py: register() speichert jetzt pid (os.getpid())
und expected_done_at (started_at + 600s). Neues remove_by_task_id()
für Stale-Recovery durch DetectionTimer.
3. presence_engine.py DetectionTimer: _stale_recovery() prüft jeden
aktiven Eintrag in subagent_status.json:
- os.kill(pid, 0) + /proc/<pid>/ Fallback
- PID tot → Eintrag entfernt
- PID lebend + expected_done_at überschritten → Eintrag bleibt
(long-running Task)
4. expected_done_at als Sekundär-Indikator: DetectionTimer nutzt es
für Logging/Diagnose, aber PID ist der primäre Indikator.
5. Lock-Order dokumentiert: _busy_honeymoon_lock vor _mode_lock.
Race-Bedingung zwischen Honeymoon-Expiry und set_pulse_target()
explizit im PresenceEngine-Docstring dokumentiert.
Tests: 40/40 passed (19 tracker + 21 presence, inkl. 5 neue Stale-Recovery-Tests)
This commit is contained in:
@@ -152,6 +152,23 @@ class PresenceEngine:
|
||||
|
||||
P1a: Honeymoon-Timer ensures busy status is visible for at least
|
||||
MIN_BUSY_VISIBLE_S (1.0s) before transitioning to online.
|
||||
|
||||
Lock-Order (Rainers Pflicht-Nachbesserung #1):
|
||||
─────────────────────────────────────────────
|
||||
Race-Bedingung: Honeymoon-Expiry (_honeymoon_expired) kann parallel zu
|
||||
PulseController.set_pulse_target() laufen. Beide greifen auf
|
||||
_transition_from_busy → _update_presence_with_subagents → set_pulse_target.
|
||||
|
||||
LOCK-ORDER (immer in dieser Reihenfolge):
|
||||
1. _busy_honeymoon_lock (PresenceEngine)
|
||||
2. _mode_lock (PulseController)
|
||||
|
||||
_honeymoon_expired() acquired _busy_honeymoon_lock zuerst, dann
|
||||
ruft es _transition_from_busy() → set_pulse_target() → _mode_lock.
|
||||
|
||||
Externe Aufrufer von set_pulse_target() (z.B. mark_busy_done) MÜSSEN
|
||||
sicherstellen dass _busy_honeymoon_lock NICHT gehalten wird wenn sie
|
||||
_mode_lock anfordern — sonst Deadlock.
|
||||
"""
|
||||
|
||||
# P1a: Minimum time busy status must be visible (prevents coalesce race)
|
||||
@@ -1511,7 +1528,8 @@ class DetectionTimer:
|
||||
try:
|
||||
from archivar.subagent_tracker import _read_subagent_state, _get_subagent_state_path
|
||||
subagent_state = _read_subagent_state(_get_subagent_state_path())
|
||||
subagent_count = len(subagent_state.get("active", []))
|
||||
active_entries = subagent_state.get("active", [])
|
||||
subagent_count = len(active_entries)
|
||||
if subagent_count > 0:
|
||||
result = True
|
||||
subagent_used = True
|
||||
@@ -1519,6 +1537,11 @@ class DetectionTimer:
|
||||
except Exception as e:
|
||||
logger.debug("[detection] subagent_status.json read failed: %s", e)
|
||||
|
||||
# ── Phase 5: Stale-Recovery — räumt tote PID-Einträge auf ──────────
|
||||
# Läuft IMMER (nicht nur wenn subagent_used), damit auch Einträge
|
||||
# aufgeräumt werden wenn PID-Sentinel oder gateway_state aktiv sind.
|
||||
self._stale_recovery()
|
||||
|
||||
# ── P2 QUATERNARY: pgrep — erweitertes Pattern 'gateway run' ────────
|
||||
if not pid_used and not gateway_used and not plugin_used and not subagent_used:
|
||||
try:
|
||||
@@ -1581,6 +1604,92 @@ class DetectionTimer:
|
||||
self._last_result = result
|
||||
return result
|
||||
|
||||
def _stale_recovery(self) -> int:
|
||||
"""Phase 5: Stale-Recovery — räumt tote PID-Einträge aus subagent_status.json.
|
||||
|
||||
Für jeden aktiven Eintrag prüfen:
|
||||
- os.kill(pid, 0) oder /proc/<pid>/ — lebt der Prozess noch?
|
||||
- Wenn PID tot → Eintrag entfernen (remove_by_task_id)
|
||||
- Wenn expected_done_at überschritten UND PID tot → aufräumen
|
||||
- Wenn expected_done_at überschritten UND PID noch lebend → Eintrag bleibt
|
||||
|
||||
Returns:
|
||||
Number of entries removed.
|
||||
"""
|
||||
removed = 0
|
||||
try:
|
||||
from archivar.subagent_tracker import (
|
||||
_read_subagent_state, _get_subagent_state_path, get_tracker,
|
||||
)
|
||||
state = _read_subagent_state(_get_subagent_state_path())
|
||||
active = state.get("active", [])
|
||||
if not active:
|
||||
return 0
|
||||
|
||||
tracker = get_tracker()
|
||||
now = datetime.now(timezone.utc)
|
||||
|
||||
for entry in list(active): # iterate over copy
|
||||
task_id = entry.get("task_id", "")
|
||||
pid = entry.get("pid", 0)
|
||||
if not task_id or not pid:
|
||||
continue
|
||||
|
||||
# Check if PID is alive
|
||||
pid_alive = self._pid_is_alive(pid)
|
||||
|
||||
if not pid_alive:
|
||||
# PID is dead — always clean up
|
||||
tracker.remove_by_task_id(task_id)
|
||||
removed += 1
|
||||
logger.info(
|
||||
"[detection] stale recovery: removed dead PID %d (task_id=%s)",
|
||||
pid, task_id,
|
||||
)
|
||||
else:
|
||||
# PID is alive — check expected_done_at
|
||||
expected_done_str = entry.get("expected_done_at", "")
|
||||
if expected_done_str:
|
||||
try:
|
||||
expected_done = datetime.fromisoformat(expected_done_str)
|
||||
if now > expected_done:
|
||||
# expected_done_at überschritten, aber PID lebt noch
|
||||
# → Eintrag bleibt (long-running Task)
|
||||
logger.debug(
|
||||
"[detection] stale recovery: task_id=%s pid=%d "
|
||||
"exceeded expected_done_at but still alive — keeping",
|
||||
task_id, pid,
|
||||
)
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
except Exception as e:
|
||||
logger.debug("[detection] stale recovery failed: %s", e)
|
||||
|
||||
if removed > 0:
|
||||
logger.info("[detection] stale recovery: removed %d stale entries", removed)
|
||||
return removed
|
||||
|
||||
@staticmethod
|
||||
def _pid_is_alive(pid: int) -> bool:
|
||||
"""Check if a process with the given PID is alive.
|
||||
|
||||
Uses os.kill(pid, 0) which sends no signal but checks permissions
|
||||
and process existence. Falls back to /proc/<pid>/ check.
|
||||
|
||||
Args:
|
||||
pid: Process ID to check.
|
||||
|
||||
Returns:
|
||||
True if the process exists, False otherwise.
|
||||
"""
|
||||
try:
|
||||
os.kill(pid, 0)
|
||||
return True
|
||||
except OSError:
|
||||
# Fallback: /proc/<pid>/ check
|
||||
return os.path.exists(f"/proc/{pid}")
|
||||
|
||||
def _detection_loop(self) -> None:
|
||||
"""Background thread: periodically check for background agents."""
|
||||
tick = 0
|
||||
|
||||
Reference in New Issue
Block a user