d9951fa822
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)
710 lines
30 KiB
Python
710 lines
30 KiB
Python
"""
|
|
V8.6 Phase 5: Subagent-Status — PresenceEngine Integrationstests.
|
|
|
|
Testet:
|
|
- mark_busy_done mit background_tasks > 0 (kein online-Übergang)
|
|
- mark_busy_done mit background_tasks == 0 (Regression: online-Übergang)
|
|
- _honeymoon_expired mit background_tasks > 0
|
|
- DetectionTimer liest subagent_status.json
|
|
- PulseController pulse_target="away" toggles
|
|
- PulseController pulse_target="busy" message-pulses
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import sys
|
|
import tempfile
|
|
import threading
|
|
import time
|
|
from pathlib import Path
|
|
from unittest.mock import MagicMock, patch, call
|
|
|
|
import pytest
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
|
|
|
|
|
# ═══════════════════════════════════════════════════════════════════════════
|
|
# B4: Autouse fixture — engine.shutdown() nach jedem Test
|
|
# ═══════════════════════════════════════════════════════════════════════════
|
|
|
|
_ENGINE_REGISTRY: list = []
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def _shutdown_presence_engines():
|
|
"""Track all PresenceEngine instances and call shutdown() after each test."""
|
|
from plugin.archivar.presence_engine import PresenceEngine
|
|
|
|
_original_init = PresenceEngine.__init__
|
|
|
|
def _tracking_init(self, *args, **kwargs):
|
|
_original_init(self, *args, **kwargs)
|
|
_ENGINE_REGISTRY.append(self)
|
|
|
|
PresenceEngine.__init__ = _tracking_init
|
|
_ENGINE_REGISTRY.clear()
|
|
|
|
try:
|
|
yield
|
|
finally:
|
|
PresenceEngine.__init__ = _original_init
|
|
for engine in _ENGINE_REGISTRY:
|
|
try:
|
|
engine.shutdown()
|
|
except Exception:
|
|
pass
|
|
_ENGINE_REGISTRY.clear()
|
|
|
|
|
|
# ═══════════════════════════════════════════════════════════════════════════
|
|
# Helper: create a PresenceEngine with mocked REST
|
|
# ═══════════════════════════════════════════════════════════════════════════
|
|
|
|
def _make_engine(**kwargs):
|
|
from plugin.archivar.presence_engine import PresenceEngine
|
|
mock_rest = MagicMock()
|
|
mock_rest.auth_token = "token"
|
|
mock_rest.user_id = "user123"
|
|
mock_rest._request = MagicMock(return_value={"success": True})
|
|
engine = PresenceEngine(rest=mock_rest, **kwargs)
|
|
return engine, mock_rest
|
|
|
|
|
|
# ═══════════════════════════════════════════════════════════════════════════
|
|
# Test 3: mark_busy_done with bg_tasks > 0 does NOT transition to online
|
|
# ═══════════════════════════════════════════════════════════════════════════
|
|
|
|
class TestMarkBusyDoneWithBgTasks:
|
|
"""Test 3: mark_busy_done mit background_tasks > 0 geht NICHT auf online."""
|
|
|
|
def test_busy_done_with_bg_tasks_stays_away_or_busy(self):
|
|
"""Wenn background_tasks > 0, transitioniert mark_busy_done nicht auf online."""
|
|
engine, mock_rest = _make_engine(coalesce_ms=100)
|
|
|
|
# Simuliere: Hauptagent busy + Subagent läuft
|
|
engine.mark_busy_started(room_name="testroom")
|
|
engine.increment_background_tasks() # bg=1
|
|
|
|
# Honeymoon abwarten
|
|
time.sleep(1.2)
|
|
|
|
# mark_busy_done — sollte NICHT auf online gehen weil bg=1
|
|
engine.mark_busy_done()
|
|
|
|
# Flush coalesce
|
|
time.sleep(0.3)
|
|
|
|
# Prüfe: letzter gesendeter Status ist NICHT "online"
|
|
# (sollte "away" sein wegen Subagent-Pulse)
|
|
calls = mock_rest._request.call_args_list
|
|
assert len(calls) > 0, "Expected at least one REST call"
|
|
# Der letzte Call sollte nicht "online" mit leerer Message sein
|
|
last_call = calls[-1]
|
|
last_data = last_call[1].get("data", {})
|
|
# Entweder "away" (idle+subagent) oder "busy" (busy+subagent)
|
|
assert last_data.get("status") != "online", (
|
|
f"Expected non-online status, got {last_data}"
|
|
)
|
|
|
|
def test_busy_done_zero_bg_tasks_transitions_to_online(self):
|
|
"""Regression: background_tasks == 0 → online (klassischer Pfad)."""
|
|
engine, mock_rest = _make_engine(coalesce_ms=100)
|
|
|
|
engine.mark_busy_started(room_name="testroom")
|
|
# KEIN increment_background_tasks → bg=0
|
|
|
|
time.sleep(1.2)
|
|
|
|
engine.mark_busy_done()
|
|
time.sleep(0.3)
|
|
|
|
calls = mock_rest._request.call_args_list
|
|
last_call = calls[-1]
|
|
last_data = last_call[1].get("data", {})
|
|
assert last_data.get("status") == "online", (
|
|
f"Expected online status, got {last_data}"
|
|
)
|
|
|
|
|
|
# ═══════════════════════════════════════════════════════════════════════════
|
|
# Test 5: _honeymoon_expired with bg_tasks > 0
|
|
# ═══════════════════════════════════════════════════════════════════════════
|
|
|
|
class TestHoneymoonExpiredWithBgTasks:
|
|
"""Test 5: _honeymoon_expired mit background_tasks > 0 geht nicht auf online."""
|
|
|
|
def test_honeymoon_expired_with_bg_tasks_does_not_transition(self):
|
|
"""Honeymoon-Timer feuert, aber bg_tasks > 0 → kein online."""
|
|
engine, mock_rest = _make_engine(coalesce_ms=100)
|
|
|
|
# Starte busy, dann sofort mark_busy_done (Honeymoon läuft noch)
|
|
engine.mark_busy_started(room_name="testroom")
|
|
engine.increment_background_tasks() # bg=1
|
|
|
|
# Honeymoon abwarten
|
|
time.sleep(1.2)
|
|
|
|
# Honeymoon-Timer sollte gefeuert haben, aber bg=1 → kein online
|
|
# Rufe _transition_from_busy manuell auf um zu prüfen
|
|
engine._transition_from_busy()
|
|
|
|
time.sleep(0.3)
|
|
|
|
calls = mock_rest._request.call_args_list
|
|
last_call = calls[-1]
|
|
last_data = last_call[1].get("data", {})
|
|
assert last_data.get("status") != "online", (
|
|
f"Expected non-online status after honeymoon with bg_tasks, got {last_data}"
|
|
)
|
|
|
|
|
|
# ═══════════════════════════════════════════════════════════════════════════
|
|
# Test 6: DetectionTimer reads subagent_status.json
|
|
# ═══════════════════════════════════════════════════════════════════════════
|
|
|
|
class TestDetectionTimerReadsSubagentStatus:
|
|
"""Test 6: DetectionTimer.check() liest subagent_status.json."""
|
|
|
|
def test_detection_timer_detects_subagent_status(self):
|
|
"""DetectionTimer erkennt aktive Einträge in subagent_status.json."""
|
|
from plugin.archivar.presence_engine import DetectionTimer
|
|
from plugin.archivar.subagent_tracker import _write_subagent_state, _get_subagent_state_path
|
|
|
|
# Schreibe einen aktiven Subagenten
|
|
subagent_path = _get_subagent_state_path()
|
|
_write_subagent_state(subagent_path, {
|
|
"active": [{"task_id": "t_123", "type": "delegate_task", "owner_room": "user:bernd"}],
|
|
"last_change_iso": "",
|
|
"schema_version": 1,
|
|
"source": "plugin_internal",
|
|
})
|
|
|
|
# DetectionTimer ohne gateway_state (damit PID-Sentinel + gateway fehlschlagen)
|
|
with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f:
|
|
gateway_path = f.name
|
|
try:
|
|
# Leeres gateway_state → PID-Sentinel greift (Gateway lebt)
|
|
# Um subagent_status zu testen, mocken wir _check_gateway_pid_alive
|
|
timer = DetectionTimer(
|
|
gateway_state_path=gateway_path,
|
|
detection_interval=10.0,
|
|
)
|
|
|
|
with patch.object(timer, '_check_gateway_pid_alive', return_value=False):
|
|
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
|
mock_run.return_value = MagicMock(stdout="", returncode=1)
|
|
result = timer.check()
|
|
|
|
# Sollte True sein weil subagent_status.json aktive Einträge hat
|
|
assert result is True, f"Expected True, got {result}"
|
|
|
|
finally:
|
|
os.unlink(gateway_path)
|
|
# Cleanup subagent_status.json
|
|
try:
|
|
os.unlink(subagent_path)
|
|
except OSError:
|
|
pass
|
|
|
|
def test_detection_timer_empty_subagent_status(self):
|
|
"""DetectionTimer erkennt leere subagent_status.json nicht als aktiv."""
|
|
from plugin.archivar.presence_engine import DetectionTimer
|
|
from plugin.archivar.subagent_tracker import _write_subagent_state, _get_subagent_state_path
|
|
|
|
subagent_path = _get_subagent_state_path()
|
|
_write_subagent_state(subagent_path, {
|
|
"active": [],
|
|
"last_change_iso": "",
|
|
"schema_version": 1,
|
|
"source": "plugin_internal",
|
|
})
|
|
|
|
# Auch plugin_state.json bereinigen (könnte bg_tasks vom vorherigen Test haben)
|
|
from plugin.archivar.presence_engine import _get_plugin_state_path, _write_plugin_state
|
|
plugin_path = _get_plugin_state_path()
|
|
_write_plugin_state(plugin_path, {
|
|
"background_tasks": 0,
|
|
"last_update_iso": "",
|
|
"source": "plugin_internal",
|
|
"schema_version": 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,
|
|
)
|
|
|
|
with patch.object(timer, '_check_gateway_pid_alive', return_value=False):
|
|
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
|
mock_run.return_value = MagicMock(stdout="", returncode=1)
|
|
result = timer.check()
|
|
|
|
# Sollte False sein weil keine Quellen aktiv
|
|
assert result is False, f"Expected False, got {result}"
|
|
|
|
finally:
|
|
os.unlink(gateway_path)
|
|
try:
|
|
os.unlink(subagent_path)
|
|
except OSError:
|
|
pass
|
|
|
|
|
|
# ═══════════════════════════════════════════════════════════════════════════
|
|
# Test 7: PulseController pulse_target="away" toggles
|
|
# ═══════════════════════════════════════════════════════════════════════════
|
|
|
|
class TestPulseControllerAwayMode:
|
|
"""Test 7: PulseController mit pulse_target='away' toggled online↔away."""
|
|
|
|
def test_pulse_target_default_is_away(self):
|
|
"""Default pulse_target ist 'away'."""
|
|
from plugin.archivar.presence_engine import PulseController
|
|
pc = PulseController(pulse_interval=0.1, _clamp_pulse=False)
|
|
assert pc.get_pulse_target() == "away"
|
|
|
|
def test_set_pulse_target_away(self):
|
|
"""set_pulse_target('away') funktioniert."""
|
|
from plugin.archivar.presence_engine import PulseController
|
|
pc = PulseController(pulse_interval=0.1, _clamp_pulse=False)
|
|
changed = pc.set_pulse_target("away")
|
|
assert changed is False # already "away"
|
|
assert pc.get_pulse_target() == "away"
|
|
|
|
def test_set_pulse_target_busy(self):
|
|
"""set_pulse_target('busy') wechselt Modus."""
|
|
from plugin.archivar.presence_engine import PulseController
|
|
pc = PulseController(pulse_interval=0.1, _clamp_pulse=False)
|
|
changed = pc.set_pulse_target("busy")
|
|
assert changed is True
|
|
assert pc.get_pulse_target() == "busy"
|
|
|
|
def test_set_pulse_target_invalid_raises(self):
|
|
"""Ungültiger pulse_target wirft ValueError."""
|
|
from plugin.archivar.presence_engine import PulseController
|
|
pc = PulseController(pulse_interval=0.1, _clamp_pulse=False)
|
|
with pytest.raises(ValueError):
|
|
pc.set_pulse_target("invalid")
|
|
|
|
def test_pulse_target_mode_sentinel_prevents_race(self):
|
|
"""Mode-Sentinel: parallele set_pulse_target-Aufrufe sind sicher."""
|
|
from plugin.archivar.presence_engine import PulseController
|
|
pc = PulseController(pulse_interval=0.1, _clamp_pulse=False)
|
|
|
|
errors = []
|
|
|
|
def toggle_mode():
|
|
try:
|
|
for _ in range(50):
|
|
pc.set_pulse_target("away")
|
|
pc.set_pulse_target("busy")
|
|
except Exception as e:
|
|
errors.append(e)
|
|
|
|
threads = [threading.Thread(target=toggle_mode) for _ in range(4)]
|
|
for t in threads:
|
|
t.start()
|
|
for t in threads:
|
|
t.join()
|
|
|
|
assert len(errors) == 0, f"Errors: {errors}"
|
|
# Final mode should be one of the two valid values
|
|
assert pc.get_pulse_target() in ("away", "busy")
|
|
|
|
|
|
# ═══════════════════════════════════════════════════════════════════════════
|
|
# Test 8: PulseController pulse_target="busy" message-pulses
|
|
# ═══════════════════════════════════════════════════════════════════════════
|
|
|
|
class TestPulseControllerBusyMode:
|
|
"""Test 8: PulseController mit pulse_target='busy' hält busy-Status."""
|
|
|
|
def test_busy_mode_does_not_toggle_to_online(self):
|
|
"""Im busy-Modus wird nicht auf online getoggled."""
|
|
from plugin.archivar.presence_engine import PulseController
|
|
pc = PulseController(pulse_interval=0.1, _clamp_pulse=False)
|
|
pc.set_pulse_target("busy")
|
|
|
|
# Mock DDP
|
|
mock_ddp = MagicMock()
|
|
mock_ddp.connected = True
|
|
mock_ddp.set_status = MagicMock()
|
|
pc.bind_ddp(mock_ddp)
|
|
|
|
# Start pulse
|
|
pc.start()
|
|
time.sleep(0.4) # Wait for a few ticks
|
|
pc.stop()
|
|
|
|
# Im busy-Modus sollte der PulseController NICHT online↔away togglen
|
|
# sondern den busy-Status halten (via _update_presence_with_subagents)
|
|
# Hier testen wir nur dass der Mode korrekt gesetzt ist
|
|
assert pc.get_pulse_target() == "busy"
|
|
|
|
def test__update_presence_with_subagents_idle(self):
|
|
"""_update_presence_with_subagents bei idle startet away-Pulse."""
|
|
engine, mock_rest = _make_engine(coalesce_ms=100)
|
|
|
|
# Sicherstellen dass active_tasks == 0
|
|
assert engine._active_tasks == 0
|
|
|
|
engine._update_presence_with_subagents(3)
|
|
|
|
time.sleep(0.3)
|
|
|
|
# Sollte "away" mit Message "3 Subagent läuft" gesendet haben
|
|
calls = mock_rest._request.call_args_list
|
|
assert len(calls) > 0
|
|
last_data = calls[-1][1].get("data", {})
|
|
assert last_data.get("status") == "away"
|
|
assert "3 Subagent" in last_data.get("message", "")
|
|
|
|
def test__update_presence_with_subagents_busy(self):
|
|
"""_update_presence_with_subagents bei busy setzt busy+Message."""
|
|
engine, mock_rest = _make_engine(coalesce_ms=100)
|
|
|
|
# Simuliere busy
|
|
engine.increment_active_tasks()
|
|
engine.set_current_room("testroom")
|
|
|
|
engine._update_presence_with_subagents(2)
|
|
|
|
time.sleep(0.3)
|
|
|
|
calls = mock_rest._request.call_args_list
|
|
assert len(calls) > 0
|
|
last_data = calls[-1][1].get("data", {})
|
|
assert last_data.get("status") == "busy"
|
|
assert "2 Subagent" in last_data.get("message", "")
|
|
assert "testroom" in last_data.get("message", "")
|
|
|
|
|
|
# ═══════════════════════════════════════════════════════════════════════════
|
|
# Test: _read_subagent_count
|
|
# ═══════════════════════════════════════════════════════════════════════════
|
|
|
|
class TestReadSubagentCount:
|
|
"""Test: _read_subagent_count() liest subagent_status.json."""
|
|
|
|
def test_read_subagent_count_returns_zero_when_empty(self):
|
|
"""Leere Datei → 0."""
|
|
engine, _ = _make_engine()
|
|
# Clean state
|
|
from plugin.archivar.subagent_tracker import _write_subagent_state, _get_subagent_state_path
|
|
_write_subagent_state(_get_subagent_state_path(), {
|
|
"active": [],
|
|
"last_change_iso": "",
|
|
"schema_version": 1,
|
|
"source": "plugin_internal",
|
|
})
|
|
assert engine._read_subagent_count() == 0
|
|
|
|
def test_read_subagent_count_returns_count(self):
|
|
"""Datei mit 2 Einträgen → 2."""
|
|
engine, _ = _make_engine()
|
|
from plugin.archivar.subagent_tracker import _write_subagent_state, _get_subagent_state_path
|
|
_write_subagent_state(_get_subagent_state_path(), {
|
|
"active": [
|
|
{"task_id": "t_1", "type": "delegate_task"},
|
|
{"task_id": "t_2", "type": "terminal_background"},
|
|
],
|
|
"last_change_iso": "",
|
|
"schema_version": 1,
|
|
"source": "plugin_internal",
|
|
})
|
|
assert engine._read_subagent_count() == 2
|
|
|
|
def test_read_subagent_count_missing_file_returns_zero(self):
|
|
"""Fehlende Datei → 0 (graceful degradation)."""
|
|
engine, _ = _make_engine()
|
|
from plugin.archivar.subagent_tracker import _get_subagent_state_path
|
|
path = _get_subagent_state_path()
|
|
try:
|
|
os.unlink(path)
|
|
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
|