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
This commit is contained in:
+177
-22
@@ -45,6 +45,55 @@ _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:
|
||||
@@ -374,6 +423,17 @@ async def check_for_predecessor_crash() -> Optional[str]:
|
||||
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:
|
||||
@@ -383,10 +443,49 @@ async def check_for_predecessor_crash() -> Optional[str]:
|
||||
predecessor_pid = heartbeat.get("pid", 0)
|
||||
current_pid = os.getpid()
|
||||
|
||||
# Gleicher PID = kein Crash (eigener Heartbeat)
|
||||
# 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:
|
||||
logger.debug("crash_forensics: heartbeat pid matches current — skipping")
|
||||
return None
|
||||
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)
|
||||
@@ -568,6 +667,11 @@ async def run_post_crash_forensic_test() -> str:
|
||||
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()]}
|
||||
@@ -576,7 +680,8 @@ async def run_integration_test() -> Optional[str]:
|
||||
Report erscheint. Räumt die Test-Dateien danach wieder auf.
|
||||
|
||||
Returns:
|
||||
Report-String wenn Test erfolgreich (Crash erkannt), None wenn nicht.
|
||||
Report-String wenn ALLE Szenarien bestanden, None wenn mindestens
|
||||
ein Szenario fehlschlägt.
|
||||
"""
|
||||
import tempfile
|
||||
|
||||
@@ -593,13 +698,23 @@ async def run_integration_test() -> Optional[str]:
|
||||
_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
|
||||
|
||||
# 1. Echte gateway.heartbeat mit korrektem Schema erstellen
|
||||
# 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
|
||||
@@ -608,29 +723,69 @@ async def run_integration_test() -> Optional[str]:
|
||||
"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()
|
||||
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,
|
||||
)
|
||||
|
||||
# 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)
|
||||
# ── 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:
|
||||
logger.warning("integration_test: FAIL — no crash report generated (report=%s)", report)
|
||||
failed = [k for k, v in results.items() if not v]
|
||||
logger.warning("integration_test: FAILED scenarios: %s — %s", failed, summary)
|
||||
|
||||
return report
|
||||
return "ALL_PASS" if all_pass else None
|
||||
|
||||
finally:
|
||||
# 5. Test-Dateien löschen
|
||||
# Test-Dateien löschen
|
||||
HEARTBEAT_PATH = _orig_heartbeat
|
||||
RESTART_LOOP_PATH = _orig_restart_loop
|
||||
TAKEOVER_MARKER_PATH = _orig_takeover
|
||||
|
||||
Reference in New Issue
Block a user