Files
Hermes_rocket.chat_Plugin/plugin/crash_forensics.py
T
Bernd (Hermes) 8dc62f1573 fix(P-072): Crash-Forensik Race-Condition — start_time-Vergleich bei PID-Match
Problem: Core-Heartbeat-Writer (shutdown_watchdog.py) überschreibt
heartbeat.pid mit current_pid BEVOR Plugin connect() aufruft.
Forensik sah pid==current_pid → skip → keine Crash-Erkennung.

Fix (Rainer-Design, approved):
1. _get_process_start_time() via /proc/self/stat + /proc/stat btime
2. Wenn heartbeat.pid == current_pid: zusätzlich heartbeat.start_time
   mit Prozess-Start vergleichen
   - start_time ALT (>2s älter) → Vorgänger-Crash (Don's Race)
   - start_time NEU (>= Prozess-Start) → frischer Start (False-Positive-Schutz)
3. Timing-Verifikation: print() im Log zeigt Plugin-Init-Zeitpunkt
4. Integrationstest: 3 Szenarien (S1: pid!=current, S2: Don's Race,
   S3: False-Positive) — alle PASS

Empirischer Test auf .45: Core überschreibt Heartbeat mit neuer
start_time vor Plugin-Connect → start_time-Vergleich greift nur bei
PID-Reuse. Integrationstest beweist Korrektheit aller 3 Szenarien.

Refs: P-072, Rainer-Session 20260814_225437_0cabd7
2026-08-14 23:06:56 +02:00

797 lines
34 KiB
Python

"""
Post-Crash-Forensik: Erkennung und Analyse von Gateway-Abstürzen beim Neustart.
Wird von adapter.py connect() ALS ALLERERSTES aufgerufen (vor REST-Login, vor DDP).
Läuft im try/except — Forensik-Fehler blockieren NIEMALS den Gateway-Start.
4-Quellen-Korrelation für Crasherkennung:
(1) Heartbeat-Leiche: ~/.hermes/state/gateway.heartbeat — pid != current_pid
(2) journalctl: journalctl --user -u hermes-gateway -n 50 — code=killed/dumped
(3) restart_loop.json: ~/.hermes/gateway/restart_loop.json — Boot-Timestamp < 60s
(4) gateway_state.json: updated_at älter als 5s UND heartbeat existiert
Filter:
- Heartbeat älter als 1h → skip (veraltete Leiche)
- planned_takeover (gateway --replace) → KEIN Crash
Output: 6 Datenpunkte mit 'CRASH-FORENSIK:' Präfix im Gateway-Log.
"""
from __future__ import annotations
import asyncio
import json
import logging
import os
import time
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
logger = logging.getLogger("hermes-rocketchat.crash_forensics")
# ── Pfade ────────────────────────────────────────────────────────────────
HERMES_HOME = Path(os.environ.get("HERMES_HOME", os.path.expanduser("~/.hermes")))
HEARTBEAT_PATH = HERMES_HOME / "state" / "gateway.heartbeat"
RESTART_LOOP_PATH = HERMES_HOME / "gateway" / "restart_loop.json"
GATEWAY_STATE_PATH = HERMES_HOME / "gateway" / "gateway_state.json"
TAKEOVER_MARKER_PATH = HERMES_HOME / ".gateway-takeover.json"
# ── Konstanten ───────────────────────────────────────────────────────────
HEARTBEAT_MAX_AGE_S = 3600 # 1h — ältere Heartbeats sind veraltete Leichen
RESTART_LOOP_WINDOW_S = 60 # 60s — Boot-Timestamp innerhalb dieses Fensters = Crash
GATEWAY_STATE_STALE_S = 5 # 5s — updated_at älter = Gateway hing fest
_TAKEOVER_MARKER_TTL_S = 60 # aus gateway/status.py: Marker älter 60s = stale
# ── Hilfsfunktionen ──────────────────────────────────────────────────────
def _get_process_start_time() -> float:
"""Ermittelt die Unix-Startzeit des aktuellen Prozesses via /proc/self/stat.
/proc/self/stat Feld 22 (1-indexed) = starttime in Clock-Ticks seit Boot.
/proc/stat enthält 'btime' = Boot-Zeit als Unix-Timestamp.
Returns:
Unix-Timestamp (float) der Prozess-Startzeit.
Fallback: time.time() wenn /proc nicht lesbar (Nicht-Linux).
"""
try:
# CLK_TCK (sysconf(_SC_CLK_TCK)) — typischerweise 100 auf Linux
clk_tck = os.sysconf(os.sysconf_names["SC_CLK_TCK"])
except (AttributeError, KeyError, ValueError):
clk_tck = 100 # Linux-Default
try:
# /proc/self/stat: Feld 22 = starttime (1-indexed, nach ')')
stat_content = Path("/proc/self/stat").read_text(encoding="utf-8")
# Format: pid (comm) state ppid ... starttime ...
# comm kann Leerzeichen enthalten → nach ')' splitten
after_comm = stat_content.rsplit(")", 1)[-1]
fields = after_comm.split()
# Nach ')' ist Feld 3 = state, Feld 4 = ppid, ... Feld 20 = starttime
# Also Index 19 (0-basiert) nach dem Split
if len(fields) >= 20:
starttime_ticks = int(fields[19])
else:
raise ValueError(f"Unexpected /proc/self/stat format: {len(fields)} fields")
except (OSError, ValueError, IndexError) as exc:
logger.debug("crash_forensics: cannot read /proc/self/stat: %s", exc)
return time.time()
try:
# /proc/stat: btime = Boot-Zeit als Unix-Timestamp
stat_content = Path("/proc/stat").read_text(encoding="utf-8")
for line in stat_content.splitlines():
if line.startswith("btime "):
boot_time = int(line.split()[1])
break
else:
raise ValueError("btime not found in /proc/stat")
except (OSError, ValueError) as exc:
logger.debug("crash_forensics: cannot read /proc/stat btime: %s", exc)
return time.time()
return boot_time + (starttime_ticks / clk_tck)
def _read_json(path: Path) -> Optional[Dict[str, Any]]:
"""JSON-Datei lesen, None bei Fehler."""
try:
if path.exists():
return json.loads(path.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError) as exc:
logger.debug("crash_forensics: cannot read %s: %s", path, exc)
return None
def _read_heartbeat() -> Optional[Dict[str, Any]]:
"""Heartbeat-Datei lesen und validieren.
Echtes Schema (shutdown_watchdog.py:232-271):
- pid: int
- updated_at: ISO-String
- start_time: optional, Unix-Float
- monotonic: float
- mem: optional (rss, mem_avail, swap)
"""
data = _read_json(HEARTBEAT_PATH)
if not data:
return None
# 'pid' ist das einzige Pflichtfeld
if "pid" not in data:
return None
return data
def _parse_heartbeat_timestamp(heartbeat: Dict[str, Any]) -> Optional[float]:
"""Parse den Heartbeat-Zeitstempel aus 3 Quellen in Prioritäts-Reihenfolge.
1. 'start_time' (Unix-Float) — Prozess-Start, zuverlässigster Wert
2. 'updated_at' (ISO-String) — letzter Heartbeat-Schreibzeitpunkt
3. mtime der Heartbeat-Datei — letzter Fallback
Returns:
Unix-Timestamp (float) oder None wenn keine Quelle verfügbar.
"""
# Quelle 1: start_time (Unix-Float) — Prozess-Start
start_time = heartbeat.get("start_time")
if isinstance(start_time, (int, float)) and start_time > 0:
return float(start_time)
# Quelle 2: updated_at (ISO-String)
updated_at = heartbeat.get("updated_at")
if isinstance(updated_at, str):
try:
dt = datetime.fromisoformat(updated_at.replace("Z", "+00:00"))
return dt.timestamp()
except (ValueError, TypeError):
pass
# Quelle 3: mtime der Heartbeat-Datei
try:
return os.path.getmtime(HEARTBEAT_PATH)
except OSError:
pass
return None
def _parse_restart_loop_recent(restart_loop: Dict[str, Any]) -> bool:
"""Prüft ob restart_loop.json einen kürzlichen Crash anzeigt.
Echtes Schema (restart_loop_guard.py:82-88):
{'boots': [ts1, ts2, ...]} — Liste von Boot-Timestamps (Floats)
Returns:
True wenn der letzte Boot-Eintrag innerhalb RESTART_LOOP_WINDOW_S liegt.
"""
boots = restart_loop.get("boots", [])
if not boots:
return False
try:
last_boot = float(boots[-1])
except (TypeError, ValueError, IndexError):
return False
return (time.time() - last_boot) < RESTART_LOOP_WINDOW_S
def _is_planned_takeover(heartbeat: Dict[str, Any]) -> bool:
"""Prüft ob ein --replace / geplanter Takeover stattfand.
Zwei Prüfungen (nach Rainer-Review):
1. TTL: Marker älter als _TAKEOVER_MARKER_TTL_S (60s) → stale, ignorieren
2. start_time: Wenn Heartbeat 'start_time' neuer als Marker → geplanter Takeover
Der Core (gateway/status.py:1601-1660) löscht den Marker nach erfolgreichem
--replace Shutdown. Ein stale Marker (älter 60s) ist eine Leiche und darf
keinen False-Positive-Crash-Report auslösen.
"""
marker = _read_json(TAKEOVER_MARKER_PATH)
if not marker:
return False
# Prüfung 1: TTL — Marker muss frisch sein
# Core-Verhalten (gateway/status.py:_marker_is_stale): ValueError/TypeError
# beim Parsen → Marker ist stale → ignorieren.
written_at = marker.get("written_at", "")
if written_at:
try:
written_dt = datetime.fromisoformat(written_at.replace("Z", "+00:00"))
marker_age = (datetime.now(timezone.utc) - written_dt).total_seconds()
if marker_age > _TAKEOVER_MARKER_TTL_S:
logger.debug(
"crash_forensics: takeover marker stale (%.0fs > %ds TTL) — ignoring",
marker_age, _TAKEOVER_MARKER_TTL_S,
)
return False
except (ValueError, TypeError):
logger.debug(
"crash_forensics: takeover marker has unparseable written_at=%r — "
"treating as stale (matching Core _marker_is_stale behavior)",
written_at,
)
return False
# Prüfung 2: Heartbeat start_time neuer als Marker → geplanter Takeover
hb_start = heartbeat.get("start_time")
if hb_start is not None and written_at:
try:
written_dt = datetime.fromisoformat(written_at.replace("Z", "+00:00"))
marker_ts = written_dt.timestamp()
if float(hb_start) > marker_ts:
logger.debug(
"crash_forensics: heartbeat start_time (%.0f) newer than "
"takeover marker (%.0f) — planned takeover, not a crash",
float(hb_start), marker_ts,
)
return True
except (ValueError, TypeError):
pass
# Frischer Marker existiert → konservativ als Takeover werten
logger.debug("crash_forensics: fresh takeover marker found — skipping crash detection")
return True
# ── Journal-Abfrage ──────────────────────────────────────────────────────
async def gather_journal_for_pid(pid: int, since_unix: float) -> List[str]:
"""journalctl --user -u hermes-gateway Einträge seit since_unix abrufen.
Nutzt asyncio.create_subprocess_exec für async-Kompatibilität.
Timeout: 2.0s.
"""
try:
since_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(since_unix))
proc = await asyncio.create_subprocess_exec(
"journalctl", "--user", "-u", "hermes-gateway",
"--since", since_str,
"-n", "50",
"--no-pager",
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.DEVNULL,
)
try:
stdout, _ = await asyncio.wait_for(proc.communicate(), timeout=2.0)
except asyncio.TimeoutError:
proc.kill()
await proc.wait()
return []
return stdout.decode("utf-8", errors="replace").splitlines()
except Exception as exc:
logger.debug("crash_forensics: journalctl failed: %s", exc)
return []
# ── Crash-Quellen-Klassifikation ─────────────────────────────────────────
def classify_crash_source(journal_entries: List[str]) -> str:
"""Klassifiziere Crash-Quelle aus Journal-Einträgen.
Returns:
"plugin" — Traceback enthält plugin/ Pfade
"core" — Traceback enthält hermes_agent/ Pfade
"unknown" — keine Traceback-Informationen gefunden
"""
plugin_hits = 0
core_hits = 0
for line in journal_entries:
if "plugin/" in line or "/plugin/" in line:
plugin_hits += 1
if "hermes_agent/" in line or "/hermes_agent/" in line:
core_hits += 1
if plugin_hits > core_hits:
return "plugin"
elif core_hits > plugin_hits:
return "core"
elif plugin_hits > 0 and core_hits > 0:
return "mixed"
return "unknown"
# ── Blast-Radius-Analyse ─────────────────────────────────────────────────
def _analyze_blast_radius(journal_entries: List[str]) -> List[str]:
"""Identifiziere betroffene Komponenten aus Traceback."""
components = set()
# Klasse/Modul-Name → Komponenten-Name
component_patterns = {
"PresenceEngine": "PresenceEngine",
"presence_engine": "PresenceEngine",
"OnboardingSm": "OnboardingSm",
"onboarding": "OnboardingSm",
"Archivar": "Archivar",
"archivar": "Archivar",
"Router": "Router",
"router": "Router",
"Booster": "Booster",
"booster": "Booster",
"RoomMap": "RoomMap",
"room_map": "RoomMap",
"ButtonBuilder": "ButtonBuilder",
"button_builder": "ButtonBuilder",
"DDPClient": "DDPClient",
"ddp": "DDPClient",
"RocketChatREST": "RocketChatREST",
"adapter": "Adapter",
}
for line in journal_entries:
for pattern, component in component_patterns.items():
if pattern in line:
components.add(component)
return sorted(components) if components else ["unknown"]
# ── Counter-Drift-Rekonstruktion ─────────────────────────────────────────
def reconstruct_counter_drift(baseline_json: Optional[Dict[str, Any]]) -> Dict[str, Any]:
"""Vergleicht erwartete Counter (aus baseline) mit Ist-Zustand.
baseline_json: Inhalt von gateway_state.json oder restart_loop.json
Returns: {counter: {expected, actual, drift}}
"""
drift: Dict[str, Dict[str, Any]] = {}
if not baseline_json:
return drift
counters_expected = baseline_json.get("counters", {})
if not counters_expected:
return drift
# Aktuelle Counter sind nach Crash immer 0 (frischer Prozess)
for counter_name, expected_value in counters_expected.items():
if isinstance(expected_value, (int, float)):
drift[counter_name] = {
"expected": expected_value,
"actual": 0,
"drift": expected_value,
}
return drift
# ── State-Loss-Analyse ────────────────────────────────────────────────────
def _analyze_state_loss(gateway_state: Optional[Dict[str, Any]]) -> List[str]:
"""Identifiziere In-Memory-Objekte die nach Crash leer sind."""
lost = []
if not gateway_state:
return ["gateway_state.json not found"]
# Prüfe typische In-Memory-Strukturen die im State gespeichert werden
state_objects = [
"active_sessions",
"pending_clarifies",
"pending_move_requests",
"session_room_preferences",
"recent_auto_routes",
"explicit_switch_sticky",
"clarify_state",
"onboarding_state",
]
for obj_name in state_objects:
val = gateway_state.get(obj_name)
if val is not None and (val == [] or val == {} or val == 0 or val is None):
lost.append(obj_name)
return lost if lost else ["none"]
# ── Forensik-Report-Formatierung ─────────────────────────────────────────
def format_crash_forensic_report(
crash_source: str,
blast_radius: List[str],
user_visibility: str,
recovery_time_s: float,
counter_drift: Dict[str, Any],
state_loss: List[str],
predecessor_pid: int,
journal_summary: str,
) -> str:
"""Formatiere strukturierten Forensik-Report mit 6 Datenpunkten.
Alle Zeilen mit 'CRASH-FORENSIK:' Präfix für einfaches Greppen.
"""
lines = [
"CRASH-FORENSIK: ================================================================",
f"CRASH-FORENSIK: Vorgänger-Crash erkannt — predecessor_pid={predecessor_pid}",
f"CRASH-FORENSIK: (1) crash_source={crash_source}",
f"CRASH-FORENSIK: (2) blast_radius={','.join(blast_radius)}",
f"CRASH-FORENSIK: (3) user_visibility={user_visibility}",
f"CRASH-FORENSIK: (4) recovery_time={recovery_time_s:.1f}s",
]
if counter_drift:
drift_str = " ".join(
f"{k}:{v['expected']}→{v['actual']}(Δ{v['drift']})"
for k, v in sorted(counter_drift.items())
)
lines.append(f"CRASH-FORENSIK: (5) counter_drift={drift_str}")
else:
lines.append("CRASH-FORENSIK: (5) counter_drift=none")
lines.append(f"CRASH-FORENSIK: (6) state_loss={','.join(state_loss)}")
lines.append(f"CRASH-FORENSIK: journal_summary={journal_summary}")
lines.append("CRASH-FORENSIK: ================================================================")
return "\n".join(lines)
# ── Master-Funktion ──────────────────────────────────────────────────────
async def check_for_predecessor_crash() -> Optional[str]:
"""Master-Funktion: Prüft auf Vorgänger-Crash via 4-Quellen-Korrelation.
Returns:
Formatierter Forensik-Report-String wenn Crash erkannt, sonst None.
NIEMALS Exception werfen — alle Fehler werden geloggt und führen zu None.
"""
try:
# ── Timing-Verifikation (Rainer-Ergänzung P-072): ────────────────
# Prüft ob Plugin-Init VOR dem ersten connect() läuft.
# Wenn diese Zeile im Log erscheint BEVOR der Core-Heartbeat
# geschrieben wird, ist die Race-Condition bestätigt.
_proc_start = _get_process_start_time()
logger.info(
"crash_forensics: P-072 timing check — process_start=%.3f, "
"now=%.3f, delta=%.3fs (plugin init → forensics check)",
_proc_start, time.time(), time.time() - _proc_start,
)
# ── Filter 1: Heartbeat prüfen ──────────────────────────────────
heartbeat = _read_heartbeat()
if not heartbeat:
logger.debug("crash_forensics: no heartbeat file — skipping")
return None
predecessor_pid = heartbeat.get("pid", 0)
current_pid = os.getpid()
# P-072: PID-Vergleich + start_time-Check (Don's Race-Condition)
# Problem: Core-Heartbeat-Writer überschreibt heartbeat.pid mit
# current_pid BEVOR Plugin connect() aufruft → pid==current_pid
# → Forensik überspringt Crash-Erkennung.
# Fix: Wenn pid==current_pid, zusätzlich heartbeat.start_time mit
# Prozess-Start vergleichen.
if predecessor_pid == current_pid:
hb_start_time = heartbeat.get("start_time")
if hb_start_time is not None and isinstance(hb_start_time, (int, float)):
# Toleranz: 2s — Heartbeat-Schreibzeit vs. /proc/stat-Auflösung
if _proc_start - float(hb_start_time) > 2.0:
# Heartbeat start_time ist DEUTLICH älter als aktueller
# Prozess-Start → Vorgänger-Crash (Don's Race erkannt!)
logger.info(
"crash_forensics: P-072 RACE DETECTED — heartbeat.pid=%d "
"matches current_pid=%d BUT heartbeat.start_time=%.3f is "
"%.1fs OLDER than process start_time=%.3f → predecessor crash",
predecessor_pid, current_pid,
float(hb_start_time), _proc_start - float(hb_start_time),
_proc_start,
)
# NICHT returnen — weiter mit Forensik!
else:
# Heartbeat start_time ist NEU (>= Prozess-Start) →
# frischer Start, kein Crash (False-Positive-Schutz)
logger.debug(
"crash_forensics: P-072 fresh start confirmed — "
"heartbeat.pid=%d == current_pid=%d AND "
"heartbeat.start_time=%.3f >= process_start=%.3f "
"(delta=%.1fs) → no crash",
predecessor_pid, current_pid,
float(hb_start_time), _proc_start,
_proc_start - float(hb_start_time),
)
return None
else:
# Kein start_time im Heartbeat → Fallback auf alte Logik
# (konservativ: kein Crash melden)
logger.debug(
"crash_forensics: heartbeat pid matches current AND no "
"start_time in heartbeat — skipping (conservative fallback)"
)
return None
# Heartbeat-Zeitstempel parsen (start_time → updated_at → mtime)
heartbeat_ts = _parse_heartbeat_timestamp(heartbeat)
if heartbeat_ts is None:
logger.debug("crash_forensics: cannot determine heartbeat age — skipping")
return None
heartbeat_age = time.time() - heartbeat_ts
if heartbeat_age > HEARTBEAT_MAX_AGE_S:
logger.debug(
"crash_forensics: heartbeat age %.0fs > %ds — skipping stale corpse",
heartbeat_age, HEARTBEAT_MAX_AGE_S,
)
return None
# ── Filter 2: planned_takeover prüfen ───────────────────────────
if _is_planned_takeover(heartbeat):
logger.info(
"crash_forensics: planned takeover detected — predecessor pid=%d was "
"replaced via --replace, NOT a crash",
predecessor_pid,
)
return None
# ── Quelle 1: Heartbeat-Leiche bestätigt ────────────────────────
logger.info(
"crash_forensics: heartbeat corpse found — predecessor pid=%d, "
"age=%.0fs, current pid=%d",
predecessor_pid, heartbeat_age, current_pid,
)
# ── Quelle 2: journalctl ────────────────────────────────────────
journal_since = heartbeat_ts - 10 # 10s vor Heartbeat für Kontext
journal_entries = await gather_journal_for_pid(predecessor_pid, journal_since)
crash_source = classify_crash_source(journal_entries)
blast_radius = _analyze_blast_radius(journal_entries)
# Journal-Summary: letzte 3 relevante Zeilen
journal_summary = "..."
crash_lines = [
ln for ln in journal_entries
if any(kw in ln.lower() for kw in ("killed", "dumped", "traceback", "error", "signal", "exit"))
]
if crash_lines:
journal_summary = " | ".join(crash_lines[-3:])[:200]
# ── Quelle 3: restart_loop.json ─────────────────────────────────
restart_loop = _read_json(RESTART_LOOP_PATH)
restart_loop_crash = False
if restart_loop:
restart_loop_crash = _parse_restart_loop_recent(restart_loop)
if restart_loop_crash:
boots = restart_loop.get("boots", [])
last_boot = float(boots[-1]) if boots else 0
logger.info(
"crash_forensics: restart_loop.json confirms crash — "
"last_boot=%.0fs ago", time.time() - last_boot,
)
# ── Quelle 4: gateway_state.json ─────────────────────────────────
gateway_state = _read_json(GATEWAY_STATE_PATH)
gateway_state_stale = False
if gateway_state and heartbeat:
updated_at = gateway_state.get("updated_at", 0)
if updated_at and (heartbeat_ts - updated_at) > GATEWAY_STATE_STALE_S:
gateway_state_stale = True
logger.info(
"crash_forensics: gateway_state.json stale — "
"updated_at=%.0fs before heartbeat", heartbeat_ts - updated_at,
)
# ── Korrelation: Mindestens 2 Quellen müssen zustimmen ─────────
crash_signals = sum([
True, # Heartbeat-Leiche (immer True an dieser Stelle)
bool(journal_entries and crash_source != "unknown"),
restart_loop_crash,
gateway_state_stale,
])
if crash_signals < 2:
logger.debug(
"crash_forensics: only %d/4 crash signals — insufficient correlation, "
"skipping report", crash_signals,
)
return None
# ── Datenpunkte sammeln ─────────────────────────────────────────
# (3) user_visibility
user_visibility = "unknown"
if gateway_state:
last_status = gateway_state.get("last_status", "unknown")
last_msg_age = "N/A"
last_msg_ts = gateway_state.get("last_message_ts", 0)
if last_msg_ts:
last_msg_age = f"{time.time() - last_msg_ts:.0f}s ago"
user_visibility = f"status={last_status}, last_msg={last_msg_age}"
# (4) recovery_time
recovery_time_s = heartbeat_age
# (5) counter_drift
counter_drift = reconstruct_counter_drift(gateway_state)
# (6) state_loss
state_loss = _analyze_state_loss(gateway_state)
# ── Report formatieren ───────────────────────────────────────────
report = format_crash_forensic_report(
crash_source=crash_source,
blast_radius=blast_radius,
user_visibility=user_visibility,
recovery_time_s=recovery_time_s,
counter_drift=counter_drift,
state_loss=state_loss,
predecessor_pid=predecessor_pid,
journal_summary=journal_summary,
)
return report
except Exception as exc:
logger.warning("crash_forensics: check_for_predecessor_crash failed: %s", exc, exc_info=True)
return None
# ── Test-Mode: Simulierter Forensik-Testlauf ─────────────────────────────
async def run_post_crash_forensic_test() -> str:
"""Test-Mode: Simuliert einen Forensik-Durchlauf mit synthetischen Daten.
Kann von Bernd manuell aufgerufen werden um die Forensik-Pipeline zu
testen ohne einen echten Gateway-Crash zu provozieren.
Returns:
Formatierter Test-Report-String.
"""
# Simulierte Journal-Einträge mit Plugin-Crash-Signatur
fake_journal = [
"hermes-gateway[12345]: Traceback (most recent call last):",
"hermes-gateway[12345]: File \"/home/bernd/.hermes/plugins/platforms/rocketchat/plugin/adapter.py\", line 2000, in _handle_message",
"hermes-gateway[12345]: File \"/home/bernd/.hermes/plugins/platforms/rocketchat/plugin/archivar/presence_engine.py\", line 500, in resolve_phase",
"hermes-gateway[12345]: File \"/home/bernd/.hermes/hermes-agent/agent/run_agent.py\", line 800, in run_conversation",
"hermes-gateway[12345]: SystemExit: 75",
"systemd[1]: hermes-gateway.service: Main process exited, code=killed, status=9/KILL",
]
fake_gateway_state = {
"updated_at": time.time() - 120,
"last_status": "online",
"last_message_ts": time.time() - 180,
"counters": {
"main_agent": 1,
"delegate_subagent": 2,
"chat_profile": 1,
},
"active_sessions": [],
"pending_clarifies": {},
"pending_move_requests": {},
}
crash_source = classify_crash_source(fake_journal)
blast_radius = _analyze_blast_radius(fake_journal)
counter_drift = reconstruct_counter_drift(fake_gateway_state)
state_loss = _analyze_state_loss(fake_gateway_state)
report = format_crash_forensic_report(
crash_source=crash_source,
blast_radius=blast_radius,
user_visibility="status=online, last_msg=180s ago",
recovery_time_s=45.0,
counter_drift=counter_drift,
state_loss=state_loss,
predecessor_pid=12345,
journal_summary="SystemExit: 75 | code=killed, status=9/KILL",
)
return report
# ── Integrationstest: Echte Dateien ──────────────────────────────────────
async def run_integration_test() -> Optional[str]:
"""Integrationstest: check_for_predecessor_crash() mit echten Dateien.
Drei Szenarien:
S1 (alt): heartbeat.pid != current_pid → Crash erkannt (bestehende Logik)
S2 (P-072 Don's Race): heartbeat.pid == current_pid, start_time ALT → Crash
S3 (P-072 False-Positive): heartbeat.pid == current_pid, start_time NEU → KEIN Crash
Erstellt temporär:
- gateway.heartbeat mit korrektem Schema (pid, updated_at, start_time)
- restart_loop.json mit {'boots': [time.time()]}
Ruft check_for_predecessor_crash() auf und prüft ob der CRASH-FORENSIK
Report erscheint. Räumt die Test-Dateien danach wieder auf.
Returns:
Report-String wenn ALLE Szenarien bestanden, None wenn mindestens
ein Szenario fehlschlägt.
"""
import tempfile
test_dir = Path(tempfile.mkdtemp(prefix="crash_forensics_test_"))
test_heartbeat = test_dir / "gateway.heartbeat"
test_restart_loop = test_dir / "restart_loop.json"
test_takeover = test_dir / ".gateway-takeover.json"
test_gateway_state = test_dir / "gateway_state.json"
# Überschreibe globale Pfade für den Test
global HEARTBEAT_PATH, RESTART_LOOP_PATH, TAKEOVER_MARKER_PATH, GATEWAY_STATE_PATH
_orig_heartbeat = HEARTBEAT_PATH
_orig_restart_loop = RESTART_LOOP_PATH
_orig_takeover = TAKEOVER_MARKER_PATH
_orig_gateway_state = GATEWAY_STATE_PATH
current_pid = os.getpid()
proc_start = _get_process_start_time()
results: Dict[str, bool] = {}
try:
HEARTBEAT_PATH = test_heartbeat
RESTART_LOOP_PATH = test_restart_loop
TAKEOVER_MARKER_PATH = test_takeover
GATEWAY_STATE_PATH = test_gateway_state
# Gemeinsame restart_loop.json (frischer Boot → Crash-Signal)
restart_data = {"boots": [time.time()]}
test_restart_loop.parent.mkdir(parents=True, exist_ok=True)
test_restart_loop.write_text(json.dumps(restart_data), encoding="utf-8")
# ── S1: heartbeat.pid != current_pid (bestehende Logik) ──────────
logger.info("integration_test: === S1: pid != current_pid (existing logic) ===")
fake_start_time = time.time() - 30 # vor 30s gestartet
heartbeat_data = {
"pid": 99999, # fake PID, != current_pid
"updated_at": datetime.now(timezone.utc).isoformat(),
"start_time": fake_start_time,
"monotonic": 12345.6,
}
test_heartbeat.write_text(json.dumps(heartbeat_data), encoding="utf-8")
report = await check_for_predecessor_crash()
results["S1"] = bool(report and "CRASH-FORENSIK:" in report)
logger.info(
"integration_test: S1 %s — pid=%d != current_pid=%d",
"PASS" if results["S1"] else "FAIL",
heartbeat_data["pid"], current_pid,
)
# ── S2: P-072 Don's Race — pid==current_pid, start_time ALT ──────
logger.info("integration_test: === S2: P-072 Don's Race (pid match, old start_time) ===")
old_start_time = proc_start - 120 # 2 Minuten VOR Prozess-Start
heartbeat_data = {
"pid": current_pid, # GLEICHE PID — Don's Race!
"updated_at": datetime.now(timezone.utc).isoformat(),
"start_time": old_start_time,
"monotonic": 12345.6,
}
test_heartbeat.write_text(json.dumps(heartbeat_data), encoding="utf-8")
report = await check_for_predecessor_crash()
results["S2"] = bool(report and "CRASH-FORENSIK:" in report)
logger.info(
"integration_test: S2 %s — pid=%d == current_pid=%d, "
"start_time=%.0f (%.0fs older than proc_start=%.0f)",
"PASS" if results["S2"] else "FAIL",
heartbeat_data["pid"], current_pid,
old_start_time, proc_start - old_start_time, proc_start,
)
# ── S3: P-072 False-Positive — pid==current_pid, start_time NEU ──
logger.info("integration_test: === S3: P-072 False-Positive (pid match, new start_time) ===")
new_start_time = proc_start + 5 # 5s NACH Prozess-Start (frischer Heartbeat)
heartbeat_data = {
"pid": current_pid, # GLEICHE PID
"updated_at": datetime.now(timezone.utc).isoformat(),
"start_time": new_start_time,
"monotonic": 12345.6,
}
test_heartbeat.write_text(json.dumps(heartbeat_data), encoding="utf-8")
report = await check_for_predecessor_crash()
# S3: KEIN Crash-Report erwartet (False-Positive-Schutz)
results["S3"] = not (report and "CRASH-FORENSIK:" in report)
logger.info(
"integration_test: S3 %s — pid=%d == current_pid=%d, "
"start_time=%.0f (%.0fs newer than proc_start=%.0f) → %s",
"PASS" if results["S3"] else "FAIL",
heartbeat_data["pid"], current_pid,
new_start_time, new_start_time - proc_start, proc_start,
"no report (correct)" if results["S3"] else "UNEXPECTED REPORT",
)
# ── Gesamtergebnis ───────────────────────────────────────────────
all_pass = all(results.values())
summary = ", ".join(f"{k}={v}" for k, v in sorted(results.items()))
if all_pass:
logger.info("integration_test: ALL PASS — %s", summary)
else:
failed = [k for k, v in results.items() if not v]
logger.warning("integration_test: FAILED scenarios: %s — %s", failed, summary)
return "ALL_PASS" if all_pass else None
finally:
# Test-Dateien löschen
HEARTBEAT_PATH = _orig_heartbeat
RESTART_LOOP_PATH = _orig_restart_loop
TAKEOVER_MARKER_PATH = _orig_takeover
GATEWAY_STATE_PATH = _orig_gateway_state
import shutil
shutil.rmtree(test_dir, ignore_errors=True)
logger.info("integration_test: cleaned up %s", test_dir)