fix(P-075): crash_forensics.py an reales gateway_state.json-Schema anpassen

3 Datenpunkte korrigiert (Viola-Schema-Analyse auf .101/.45):

(3) user_visibility:
  - last_status: liest jetzt gateway_state['platforms']['rocketchat']['state']
    (real vorhanden: online/busy/away/offline) statt nicht-existentem 'last_status'
  - last_message_ts: nicht im Schema -> aus journalctl rekonstruiert via
    _extract_last_user_message() (Adapter-Log 'Message from <user> in <room>')
  - Fallback 'unavailable' wenn platforms-Struktur fehlt

(5) counter_drift:
  - liest gateway_state['active_agents'] (einziger serialisierter Counter)
    statt nicht-existentem 'counters'
  - Format 'active_agents: N (vor Crash)' vs '0 (nach Neustart)'
  - dokumentiert: chat_profile/delegate_subagent/main_agent sind In-Memory
    in PresenceEngine, nie serialisiert

(6) state_loss:
  - feste ehrliche Ausweisung 'in-memory (lost on crash) — active_sessions,
    pending_clarifies, pending_move_requests' statt 'unknown'/'none'
  - diese Objekte werden nie serialisiert, sind nach Crash grundsätzlich verloren

Test-Mode auf reales Schema umgestellt (fake_gateway_state + fake_journal).
This commit is contained in:
Bernd (Hermes)
2026-08-15 10:26:10 +02:00
parent 8af0c0360f
commit f7cbe7dc83
+103 -46
View File
@@ -293,6 +293,40 @@ async def gather_journal_for_pid(pid: int, since_unix: float) -> List[str]:
return []
def _extract_last_user_message(journal_entries: List[str]) -> Optional[str]:
"""Extrahiert die letzte User-Nachricht vor dem Crash aus Journal-Einträgen.
P-075: last_message_ts existiert NICHT im realen gateway_state.json-Schema.
Die letzte User-Aktivität vor dem Crash muss daher aus journalctl rekonstruiert
werden. Der Adapter loggt eingehende Nachrichten als:
"[rocketchat] Message from <user> in <room> [<type>]: <text>"
(adapter.py:2375). Diese Zeile ist der zuverlässigste Indikator für die
letzte User-Nachricht vor dem Crash.
Returns:
Formatierter String "user=<user>, room=<room>, text=<text>" oder None
wenn keine Nachrichten-Zeile gefunden wurde.
"""
message_lines = [ln for ln in journal_entries if "Message from" in ln]
if not message_lines:
return None
# Chronologisch letzte Nachricht (Journal ist aufsteigend sortiert)
last = message_lines[-1]
try:
after_marker = last.split("Message from", 1)[1].strip()
# after_marker = "<user> in <room> [<type>]: <text>"
user, _, rest = after_marker.partition(" in ")
room, _, rest = rest.partition(" [")
_, _, text = rest.partition("]: ")
return f"user={user.strip()}, room={room.strip()}, text={text.strip()[:60]}"
except Exception:
# Fallback: rohe Zeile (gekürzt) wenn das Format nicht passt
return last.strip()[:120]
# ── Crash-Quellen-Klassifikation ─────────────────────────────────────────
def classify_crash_source(journal_entries: List[str]) -> str:
@@ -386,52 +420,61 @@ def _analyze_blast_radius(journal_entries: List[str]) -> List[str]:
def reconstruct_counter_drift(baseline_json: Optional[Dict[str, Any]]) -> Dict[str, Any]:
"""Vergleicht erwartete Counter (aus baseline) mit Ist-Zustand.
P-075: Das reale gateway_state.json-Schema enthält KEIN 'counters'-Feld.
Die detaillierten Counter (chat_profile, delegate_subagent, main_agent)
sind In-Memory in der PresenceEngine und werden NIE serialisiert.
Der EINZIGE verfügbare Counter im realen Schema ist 'active_agents'
(int, z.B. 0). Wenn dieser vor dem Crash > 0 war, ist das der Drift —
nach dem Neustart ist er immer 0 (frischer Prozess).
baseline_json: Inhalt von gateway_state.json oder restart_loop.json
Returns: {counter: {expected, actual, drift}}
Returns: {'active_agents': {expected, actual, drift}} oder {} wenn
active_agents nicht vorhanden ist.
"""
drift: Dict[str, Dict[str, Any]] = {}
if not baseline_json:
return drift
counters_expected = baseline_json.get("counters", {})
if not counters_expected:
# P-075: active_agents ist der einzige serialisierte Counter.
# Keine detaillierten Counter (chat_profile, delegate_subagent, main_agent)
# — die sind In-Memory in der PresenceEngine, nie serialisiert.
active_agents = baseline_json.get("active_agents")
if not isinstance(active_agents, (int, float)):
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,
}
# Nach Crash ist active_agents immer 0 (frischer Prozess)
drift["active_agents"] = {
"expected": active_agents,
"actual": 0,
"drift": active_agents,
}
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 = []
"""Weist In-Memory-Objekte aus, die bei einem Crash grundsätzlich verloren gehen.
P-075: active_sessions, pending_clarifies und pending_move_requests sind
In-Memory-Objekte der PresenceEngine/des Adapters. Sie werden NIE in
gateway_state.json serialisiert — sie existieren nur im laufenden Prozess
und sind nach einem Crash grundsätzlich verloren.
Statt 'unknown' (suggeriert Unwissen) wird ehrlich 'lost on crash'
ausgewiesen: Der User weiß damit klar, dass diese Daten bei einem Crash
verloren gehen.
"""
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",
# P-075: Diese In-Memory-Objekte werden nie serialisiert — sie sind nach
# einem Crash grundsätzlich verloren. Feste, ehrliche Ausweisung statt
# 'unknown' oder 'none'.
return [
"in-memory (lost on crash) — active_sessions, pending_clarifies, pending_move_requests"
]
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 ─────────────────────────────────────────
@@ -653,14 +696,22 @@ async def check_for_predecessor_crash() -> Optional[str]:
# ── Datenpunkte sammeln ─────────────────────────────────────────
# (3) user_visibility
user_visibility = "unknown"
# P-075: last_status/last_message_ts existieren NICHT im realen Schema.
# - last_status → gateway_state['platforms']['rocketchat']['state']
# (real vorhanden: 'online', 'busy', 'away', 'offline')
# - last_message_ts → aus journalctl rekonstruiert (letzte User-Nachricht)
user_visibility = "unavailable"
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}"
platforms = gateway_state.get("platforms")
if isinstance(platforms, dict):
rc = platforms.get("rocketchat")
if isinstance(rc, dict):
last_status = rc.get("state", "unavailable")
last_msg = _extract_last_user_message(journal_entries)
if last_msg:
user_visibility = f"status={last_status}, last_msg={last_msg}"
else:
user_visibility = f"status={last_status}, last_msg=unavailable"
# (4) recovery_time
recovery_time_s = heartbeat_age
@@ -708,20 +759,21 @@ async def run_post_crash_forensic_test() -> str:
"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",
"[rocketchat] Message from bernd in testraum [t]: Hallo, bitte pruefe den Status",
]
# P-075: Reales gateway_state.json-Schema (Viola-Analyse auf .101/.45).
# KEINE last_status/last_message_ts/counters/active_sessions-Felder.
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,
"pid": 12345,
"start_time": 8726113,
"updated_at": "2026-08-15T10:20:00+02:00",
"active_agents": 2,
"platforms": {
"rocketchat": {
"state": "online",
}
},
"active_sessions": [],
"pending_clarifies": {},
"pending_move_requests": {},
}
crash_source = classify_crash_source(fake_journal)
@@ -729,6 +781,11 @@ async def run_post_crash_forensic_test() -> str:
counter_drift = reconstruct_counter_drift(fake_gateway_state)
state_loss = _analyze_state_loss(fake_gateway_state)
# P-075: user_visibility aus realem Schema + journalctl-Rekonstruktion
last_status = fake_gateway_state["platforms"]["rocketchat"]["state"]
last_msg = _extract_last_user_message(fake_journal)
user_visibility = f"status={last_status}, last_msg={last_msg}"
# P-074b: SIGKILL-Szenario — reiner externer Kill ohne Traceback.
# Verifiziert, dass classify_crash_source() bei systemd 'status=9/KILL'
# eine Aussage liefert statt 'unknown'.
@@ -745,7 +802,7 @@ async def run_post_crash_forensic_test() -> str:
report = format_crash_forensic_report(
crash_source=crash_source,
blast_radius=blast_radius,
user_visibility="status=online, last_msg=180s ago",
user_visibility=user_visibility,
recovery_time_s=45.0,
counter_drift=counter_drift,
state_loss=state_loss,