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:
+3
-6
@@ -3589,12 +3589,9 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
self._presence_engine.set_current_room("")
|
||||
logger.info("[presence] mark_busy_done (turn complete)")
|
||||
|
||||
# Phase 5: SubagentTracker — complete background task (symmetrisch zu register)
|
||||
if _has_tracker:
|
||||
try:
|
||||
self._subagent_tracker.complete("background_task")
|
||||
except Exception as e:
|
||||
logger.debug("[subagent_tracker] complete failed (non-critical): %s", e)
|
||||
# Phase 5: SubagentTracker — complete() NICHT im finally!
|
||||
# Der Background-Prozess läuft noch wenn der Turn endet.
|
||||
# Stale-Recovery im DetectionTimer räumt tote Einträge auf.
|
||||
# ── P5 V9.x: OutboundGate — release (symmetrisch zu mark_busy_done) ──
|
||||
# W2: release in try/except BaseException im finally-Block.
|
||||
try:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -102,26 +102,37 @@ class SubagentTracker:
|
||||
self._state_path = state_path
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def register(self, subagent_type: str, room_name: str = "", task_id: str = "") -> dict:
|
||||
def register(self, subagent_type: str, room_name: str = "", task_id: str = "", pid: int = 0) -> dict:
|
||||
"""Register a new active subagent.
|
||||
|
||||
Args:
|
||||
subagent_type: One of 'delegate_task', 'terminal_background', 'task_management'.
|
||||
room_name: Owner room (e.g. 'user:bernd').
|
||||
task_id: Optional task identifier. Auto-generated if empty.
|
||||
pid: Process ID of the background task. Defaults to os.getpid().
|
||||
|
||||
Returns:
|
||||
The created entry dict.
|
||||
"""
|
||||
if not task_id:
|
||||
task_id = f"t_{int(time.time() * 1_000_000)}"
|
||||
if not pid:
|
||||
pid = os.getpid()
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
expected_duration_s = 600
|
||||
expected_done_at = datetime.fromtimestamp(
|
||||
now.timestamp() + expected_duration_s, tz=timezone.utc
|
||||
).isoformat()
|
||||
|
||||
entry = {
|
||||
"task_id": task_id,
|
||||
"type": subagent_type,
|
||||
"owner_room": room_name,
|
||||
"started_at": datetime.now(timezone.utc).isoformat(),
|
||||
"expected_duration_s": 600,
|
||||
"pid": pid,
|
||||
"started_at": now.isoformat(),
|
||||
"expected_duration_s": expected_duration_s,
|
||||
"expected_done_at": expected_done_at,
|
||||
"plugin_state_source": "adapter.subagent_tracker",
|
||||
}
|
||||
|
||||
@@ -173,6 +184,35 @@ class SubagentTracker:
|
||||
)
|
||||
return len(active)
|
||||
|
||||
def remove_by_task_id(self, task_id: str) -> bool:
|
||||
"""Remove a subagent entry by task_id (for stale recovery).
|
||||
|
||||
Used by DetectionTimer to clean up entries whose PID is dead.
|
||||
|
||||
Args:
|
||||
task_id: The task_id to remove.
|
||||
|
||||
Returns:
|
||||
True if an entry was removed, False if not found.
|
||||
"""
|
||||
with self._lock:
|
||||
state = _read_subagent_state(self._state_path)
|
||||
active = state.get("active", [])
|
||||
original_len = len(active)
|
||||
active = [e for e in active if e.get("task_id") != task_id]
|
||||
removed = len(active) < original_len
|
||||
|
||||
if removed:
|
||||
state["active"] = active
|
||||
state["last_change_iso"] = datetime.now(timezone.utc).isoformat()
|
||||
_write_subagent_state(self._state_path, state)
|
||||
logger.info(
|
||||
"[subagent_tracker] stale recovery: removed task_id=%s, remaining=%d",
|
||||
task_id, len(active),
|
||||
)
|
||||
|
||||
return removed
|
||||
|
||||
def list(self) -> List[Dict]:
|
||||
"""List all currently active subagent entries.
|
||||
|
||||
|
||||
@@ -430,3 +430,280 @@ class TestReadSubagentCount:
|
||||
except OSError:
|
||||
pass
|
||||
assert engine._read_subagent_count() == 0
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 9: Stale-Recovery — PID tot → Eintrag wird entfernt
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestStaleRecoveryPidDead:
|
||||
"""Test 9: Stale-Recovery entfernt Einträge mit toter PID."""
|
||||
|
||||
def test_pid_dead_entry_removed(self):
|
||||
"""Wenn PID tot ist, wird der Eintrag aus subagent_status.json entfernt."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
from plugin.archivar.subagent_tracker import (
|
||||
_write_subagent_state, _get_subagent_state_path, get_tracker,
|
||||
)
|
||||
|
||||
subagent_path = _get_subagent_state_path()
|
||||
tracker = get_tracker()
|
||||
|
||||
# Schreibe einen Eintrag mit einer garantiert toten PID (99999)
|
||||
_write_subagent_state(subagent_path, {
|
||||
"active": [{
|
||||
"task_id": "t_dead_pid",
|
||||
"type": "background_task",
|
||||
"owner_room": "user:bernd",
|
||||
"pid": 99999,
|
||||
"started_at": "2025-01-01T00:00:00+00:00",
|
||||
"expected_duration_s": 600,
|
||||
"expected_done_at": "2025-01-01T00:10:00+00:00",
|
||||
"plugin_state_source": "adapter.subagent_tracker",
|
||||
}],
|
||||
"last_change_iso": "",
|
||||
"schema_version": 1,
|
||||
"source": "plugin_internal",
|
||||
})
|
||||
|
||||
# Verify entry exists
|
||||
assert tracker.count() == 1
|
||||
|
||||
# Create DetectionTimer and run stale recovery
|
||||
with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f:
|
||||
gateway_path = f.name
|
||||
try:
|
||||
timer = DetectionTimer(
|
||||
gateway_state_path=gateway_path,
|
||||
detection_interval=10.0,
|
||||
)
|
||||
removed = timer._stale_recovery()
|
||||
|
||||
# PID 99999 ist tot → sollte entfernt worden sein
|
||||
assert removed == 1, f"Expected 1 removed, got {removed}"
|
||||
assert tracker.count() == 0, f"Expected 0 entries, got {tracker.count()}"
|
||||
finally:
|
||||
os.unlink(gateway_path)
|
||||
# Cleanup
|
||||
try:
|
||||
os.unlink(subagent_path)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def test_pid_dead_multiple_entries_cleanup(self):
|
||||
"""Mehrere tote PIDs → alle werden entfernt."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
from plugin.archivar.subagent_tracker import (
|
||||
_write_subagent_state, _get_subagent_state_path, get_tracker,
|
||||
)
|
||||
|
||||
subagent_path = _get_subagent_state_path()
|
||||
tracker = get_tracker()
|
||||
|
||||
_write_subagent_state(subagent_path, {
|
||||
"active": [
|
||||
{
|
||||
"task_id": "t_dead_1",
|
||||
"type": "background_task",
|
||||
"pid": 99998,
|
||||
"started_at": "2025-01-01T00:00:00+00:00",
|
||||
"expected_duration_s": 600,
|
||||
"expected_done_at": "2025-01-01T00:10:00+00:00",
|
||||
},
|
||||
{
|
||||
"task_id": "t_dead_2",
|
||||
"type": "delegate_task",
|
||||
"pid": 99997,
|
||||
"started_at": "2025-01-01T00:00:00+00:00",
|
||||
"expected_duration_s": 600,
|
||||
"expected_done_at": "2025-01-01T00:10:00+00:00",
|
||||
},
|
||||
],
|
||||
"last_change_iso": "",
|
||||
"schema_version": 1,
|
||||
"source": "plugin_internal",
|
||||
})
|
||||
|
||||
assert tracker.count() == 2
|
||||
|
||||
with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f:
|
||||
gateway_path = f.name
|
||||
try:
|
||||
timer = DetectionTimer(
|
||||
gateway_state_path=gateway_path,
|
||||
detection_interval=10.0,
|
||||
)
|
||||
removed = timer._stale_recovery()
|
||||
|
||||
assert removed == 2, f"Expected 2 removed, got {removed}"
|
||||
assert tracker.count() == 0
|
||||
finally:
|
||||
os.unlink(gateway_path)
|
||||
try:
|
||||
os.unlink(subagent_path)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 10: Stale-Recovery — PID lebend → Eintrag bleibt
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestStaleRecoveryPidAlive:
|
||||
"""Test 10: Stale-Recovery lässt Einträge mit lebender PID in Ruhe."""
|
||||
|
||||
def test_pid_alive_entry_kept(self):
|
||||
"""Wenn PID lebt, bleibt der Eintrag erhalten."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
from plugin.archivar.subagent_tracker import (
|
||||
_write_subagent_state, _get_subagent_state_path, get_tracker,
|
||||
)
|
||||
|
||||
subagent_path = _get_subagent_state_path()
|
||||
tracker = get_tracker()
|
||||
|
||||
# Nutze die eigene PID (dieser Testprozess lebt garantiert)
|
||||
own_pid = os.getpid()
|
||||
|
||||
_write_subagent_state(subagent_path, {
|
||||
"active": [{
|
||||
"task_id": "t_alive_pid",
|
||||
"type": "background_task",
|
||||
"owner_room": "user:bernd",
|
||||
"pid": own_pid,
|
||||
"started_at": "2025-01-01T00:00:00+00:00",
|
||||
"expected_duration_s": 600,
|
||||
"expected_done_at": "2099-01-01T00:00:00+00:00", # weit in der Zukunft
|
||||
"plugin_state_source": "adapter.subagent_tracker",
|
||||
}],
|
||||
"last_change_iso": "",
|
||||
"schema_version": 1,
|
||||
"source": "plugin_internal",
|
||||
})
|
||||
|
||||
assert tracker.count() == 1
|
||||
|
||||
with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f:
|
||||
gateway_path = f.name
|
||||
try:
|
||||
timer = DetectionTimer(
|
||||
gateway_state_path=gateway_path,
|
||||
detection_interval=10.0,
|
||||
)
|
||||
removed = timer._stale_recovery()
|
||||
|
||||
# Eigene PID lebt → kein Eintrag entfernt
|
||||
assert removed == 0, f"Expected 0 removed, got {removed}"
|
||||
assert tracker.count() == 1, f"Expected 1 entry, got {tracker.count()}"
|
||||
finally:
|
||||
os.unlink(gateway_path)
|
||||
try:
|
||||
os.unlink(subagent_path)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 11: Stale-Recovery — expected_done_at überschritten + PID tot
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestStaleRecoveryExpectedDoneAt:
|
||||
"""Test 11: expected_done_at als Sekundär-Indikator."""
|
||||
|
||||
def test_expected_done_at_exceeded_pid_dead_removed(self):
|
||||
"""expected_done_at überschritten + PID tot → Eintrag entfernt."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
from plugin.archivar.subagent_tracker import (
|
||||
_write_subagent_state, _get_subagent_state_path, get_tracker,
|
||||
)
|
||||
|
||||
subagent_path = _get_subagent_state_path()
|
||||
tracker = get_tracker()
|
||||
|
||||
# expected_done_at in der Vergangenheit + tote PID
|
||||
_write_subagent_state(subagent_path, {
|
||||
"active": [{
|
||||
"task_id": "t_expired_dead",
|
||||
"type": "background_task",
|
||||
"owner_room": "user:bernd",
|
||||
"pid": 99996,
|
||||
"started_at": "2025-01-01T00:00:00+00:00",
|
||||
"expected_duration_s": 600,
|
||||
"expected_done_at": "2025-01-01T00:10:00+00:00", # lange überschritten
|
||||
"plugin_state_source": "adapter.subagent_tracker",
|
||||
}],
|
||||
"last_change_iso": "",
|
||||
"schema_version": 1,
|
||||
"source": "plugin_internal",
|
||||
})
|
||||
|
||||
assert tracker.count() == 1
|
||||
|
||||
with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f:
|
||||
gateway_path = f.name
|
||||
try:
|
||||
timer = DetectionTimer(
|
||||
gateway_state_path=gateway_path,
|
||||
detection_interval=10.0,
|
||||
)
|
||||
removed = timer._stale_recovery()
|
||||
|
||||
# PID tot → entfernt (expected_done_at ist sekundär, PID ist primär)
|
||||
assert removed == 1, f"Expected 1 removed, got {removed}"
|
||||
assert tracker.count() == 0
|
||||
finally:
|
||||
os.unlink(gateway_path)
|
||||
try:
|
||||
os.unlink(subagent_path)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def test_expected_done_at_exceeded_pid_alive_kept(self):
|
||||
"""expected_done_at überschritten aber PID lebt → Eintrag bleibt (long-running)."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
from plugin.archivar.subagent_tracker import (
|
||||
_write_subagent_state, _get_subagent_state_path, get_tracker,
|
||||
)
|
||||
|
||||
subagent_path = _get_subagent_state_path()
|
||||
tracker = get_tracker()
|
||||
|
||||
own_pid = os.getpid()
|
||||
|
||||
# expected_done_at in der Vergangenheit, aber PID lebt
|
||||
_write_subagent_state(subagent_path, {
|
||||
"active": [{
|
||||
"task_id": "t_long_running",
|
||||
"type": "background_task",
|
||||
"owner_room": "user:bernd",
|
||||
"pid": own_pid,
|
||||
"started_at": "2025-01-01T00:00:00+00:00",
|
||||
"expected_duration_s": 600,
|
||||
"expected_done_at": "2025-01-01T00:10:00+00:00", # überschritten
|
||||
"plugin_state_source": "adapter.subagent_tracker",
|
||||
}],
|
||||
"last_change_iso": "",
|
||||
"schema_version": 1,
|
||||
"source": "plugin_internal",
|
||||
})
|
||||
|
||||
assert tracker.count() == 1
|
||||
|
||||
with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f:
|
||||
gateway_path = f.name
|
||||
try:
|
||||
timer = DetectionTimer(
|
||||
gateway_state_path=gateway_path,
|
||||
detection_interval=10.0,
|
||||
)
|
||||
removed = timer._stale_recovery()
|
||||
|
||||
# PID lebt → Eintrag bleibt, auch wenn expected_done_at überschritten
|
||||
assert removed == 0, f"Expected 0 removed, got {removed}"
|
||||
assert tracker.count() == 1, f"Expected 1 entry, got {tracker.count()}"
|
||||
finally:
|
||||
os.unlink(gateway_path)
|
||||
try:
|
||||
os.unlink(subagent_path)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
Reference in New Issue
Block a user