fix(crash_forensics): P0-Schema-Fixes + P1-Takeover-Fix + Integrationstest

B1 [P0]: _read_heartbeat() suchte nicht-existierendes 'ts'-Feld.
  - Entfernt: 'ts'-Validierung
  - Neu: _parse_heartbeat_timestamp() Helper mit 3 Quellen:
    1. start_time (Unix-Float) — Prozess-Start
    2. updated_at (ISO-String) — letzter Heartbeat
    3. mtime der Datei — Fallback

B2 [P0]: restart_loop.json-Parsing suchte nicht-existierendes 'boot_ts'.
  - Entfernt: restart_loop.get('boot_ts')
  - Neu: _parse_restart_loop_recent() Helper
    Liest boots[-1] aus {'boots': [ts1, ts2, ...]}

B3 [P1]: _is_planned_takeover() — False-Positive bei Deployments.
  - TTL-Prüfung (60s) wie Core _marker_is_stale()
  - ValueError/TypeError beim Parsen → stale (matching Core)
  - start_time-Vergleich: Heartbeat neuer als Marker → Takeover

B4 [P1]: Integrationstest run_integration_test().
  - Erstellt echte gateway.heartbeat + restart_loop.json
  - Ruft check_for_predecessor_crash() auf
  - Prüft CRASH-FORENSIK-Report
  - Räumt Test-Dateien auf

Reviewed-by: Rainer (Session 20260814_204809_bbe8e6)
This commit is contained in:
Bernd (Hermes)
2026-08-14 21:34:38 +02:00
parent 438d4bc2cb
commit bb91300aa8
+210 -16
View File
@@ -23,6 +23,7 @@ import json
import logging import logging
import os import os
import time import time
from datetime import datetime, timezone
from pathlib import Path from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple from typing import Any, Dict, List, Optional, Tuple
@@ -39,6 +40,7 @@ TAKEOVER_MARKER_PATH = HERMES_HOME / ".gateway-takeover.json"
HEARTBEAT_MAX_AGE_S = 3600 # 1h — ältere Heartbeats sind veraltete Leichen HEARTBEAT_MAX_AGE_S = 3600 # 1h — ältere Heartbeats sind veraltete Leichen
RESTART_LOOP_WINDOW_S = 60 # 60s — Boot-Timestamp innerhalb dieses Fensters = Crash RESTART_LOOP_WINDOW_S = 60 # 60s — Boot-Timestamp innerhalb dieses Fensters = Crash
GATEWAY_STATE_STALE_S = 5 # 5s — updated_at älter = Gateway hing fest 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 ────────────────────────────────────────────────────── # ── Hilfsfunktionen ──────────────────────────────────────────────────────
@@ -54,23 +56,132 @@ def _read_json(path: Path) -> Optional[Dict[str, Any]]:
def _read_heartbeat() -> Optional[Dict[str, Any]]: def _read_heartbeat() -> Optional[Dict[str, Any]]:
"""Heartbeat-Datei lesen und validieren.""" """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) data = _read_json(HEARTBEAT_PATH)
if not data: if not data:
return None return None
# Validiere Struktur # 'pid' ist das einzige Pflichtfeld
if "pid" not in data or "ts" not in data: if "pid" not in data:
return None return None
return data return data
def _is_planned_takeover() -> bool: def _parse_heartbeat_timestamp(heartbeat: Dict[str, Any]) -> Optional[float]:
"""Prüft ob ein --replace / geplanter Takeover stattfand.""" """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) marker = _read_json(TAKEOVER_MARKER_PATH)
if marker: if not marker:
logger.debug("crash_forensics: takeover marker found — skipping crash detection") return False
return True
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 ────────────────────────────────────────────────────── # ── Journal-Abfrage ──────────────────────────────────────────────────────
@@ -277,8 +388,12 @@ async def check_for_predecessor_crash() -> Optional[str]:
logger.debug("crash_forensics: heartbeat pid matches current — skipping") logger.debug("crash_forensics: heartbeat pid matches current — skipping")
return None return None
# Heartbeat zu alt → veraltete Leiche # Heartbeat-Zeitstempel parsen (start_time → updated_at → mtime)
heartbeat_ts = heartbeat.get("ts", 0) 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 heartbeat_age = time.time() - heartbeat_ts
if heartbeat_age > HEARTBEAT_MAX_AGE_S: if heartbeat_age > HEARTBEAT_MAX_AGE_S:
logger.debug( logger.debug(
@@ -288,7 +403,7 @@ async def check_for_predecessor_crash() -> Optional[str]:
return None return None
# ── Filter 2: planned_takeover prüfen ─────────────────────────── # ── Filter 2: planned_takeover prüfen ───────────────────────────
if _is_planned_takeover(): if _is_planned_takeover(heartbeat):
logger.info( logger.info(
"crash_forensics: planned takeover detected — predecessor pid=%d was " "crash_forensics: planned takeover detected — predecessor pid=%d was "
"replaced via --replace, NOT a crash", "replaced via --replace, NOT a crash",
@@ -322,12 +437,13 @@ async def check_for_predecessor_crash() -> Optional[str]:
restart_loop = _read_json(RESTART_LOOP_PATH) restart_loop = _read_json(RESTART_LOOP_PATH)
restart_loop_crash = False restart_loop_crash = False
if restart_loop: if restart_loop:
boot_ts = restart_loop.get("boot_ts", 0) restart_loop_crash = _parse_restart_loop_recent(restart_loop)
if boot_ts and (time.time() - boot_ts) < RESTART_LOOP_WINDOW_S: if restart_loop_crash:
restart_loop_crash = True boots = restart_loop.get("boots", [])
last_boot = float(boots[-1]) if boots else 0
logger.info( logger.info(
"crash_forensics: restart_loop.json confirms crash — " "crash_forensics: restart_loop.json confirms crash — "
"boot_ts=%.0fs ago", time.time() - boot_ts, "last_boot=%.0fs ago", time.time() - last_boot,
) )
# ── Quelle 4: gateway_state.json ───────────────────────────────── # ── Quelle 4: gateway_state.json ─────────────────────────────────
@@ -445,3 +561,81 @@ async def run_post_crash_forensic_test() -> str:
journal_summary="SystemExit: 75 | code=killed, status=9/KILL", journal_summary="SystemExit: 75 | code=killed, status=9/KILL",
) )
return report return report
# ── Integrationstest: Echte Dateien ──────────────────────────────────────
async def run_integration_test() -> Optional[str]:
"""Integrationstest: check_for_predecessor_crash() mit echten Dateien.
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 Test erfolgreich (Crash erkannt), None wenn nicht.
"""
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
try:
HEARTBEAT_PATH = test_heartbeat
RESTART_LOOP_PATH = test_restart_loop
TAKEOVER_MARKER_PATH = test_takeover
GATEWAY_STATE_PATH = test_gateway_state
# 1. Echte gateway.heartbeat mit korrektem Schema erstellen
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")
logger.info("integration_test: wrote heartbeat — pid=%d, start_time=%.0f",
heartbeat_data["pid"], fake_start_time)
# 2. Echte restart_loop.json mit {'boots': [time.time()]} erstellen
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")
logger.info("integration_test: wrote restart_loop.json — boots=[%.0f]",
restart_data["boots"][0])
# 3. check_for_predecessor_crash() aufrufen
report = await check_for_predecessor_crash()
# 4. Prüfen: CRASH-FORENSIK Eintrag muss erscheinen
if report and "CRASH-FORENSIK:" in report:
logger.info("integration_test: PASS — crash detected:\n%s", report)
else:
logger.warning("integration_test: FAIL — no crash report generated (report=%s)", report)
return report
finally:
# 5. 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)