import logging import os import time from datetime import datetime, timedelta def _read_last_heal_line(history_file, chunk_size=4096, max_scan_bytes=262144): """ Returns the most recent line containing 'HEAL:' by scanning from file tail. Falls back to a full forward scan if no marker is found in the tail window. """ file_size = os.path.getsize(history_file) if file_size <= 0: return None with open(history_file, "rb") as f: pos = file_size scanned = 0 buffer = b"" while pos > 0 and scanned < max_scan_bytes: to_read = min(chunk_size, pos, max_scan_bytes - scanned) pos -= to_read f.seek(pos) chunk = f.read(to_read) buffer = chunk + buffer scanned += to_read lines = buffer.splitlines() if pos > 0 and lines: # Drop potential partial line at the chunk boundary. lines = lines[1:] for raw_line in reversed(lines): line = raw_line.decode("utf-8", errors="replace").strip() if "HEAL:" in line: return line # Fallback for unusual files where recent tail has no HEAL marker. last_heal_line = None with open(history_file) as f: for line in f: if "HEAL:" in line: last_heal_line = line.strip() return last_heal_line def should_heal(history_file, drift_fingerprint, min_interval=900): """ Prevents heal flapping by suppressing repeated no-op heals. """ try: if not os.path.exists(history_file): return True last = _read_last_heal_line(history_file) if not last: return True ts_str, msg = last.split(" - ", 1) last_time = datetime.fromisoformat(ts_str) last_fingerprint = "" marker = "drift_fingerprint=" if marker in msg: last_fingerprint = msg.split(marker, 1)[1].split()[0].strip() if not drift_fingerprint: return True # If healed recently AND nothing changed, suppress if datetime.now() - last_time < timedelta(seconds=min_interval): if last_fingerprint and last_fingerprint == drift_fingerprint: logging.warning( "Heal suppressed (recent identical drift fingerprint)." ) return False return True except Exception as e: logging.error(f"Heal gate failed open: {e}") return True def execute_heal_and_verify(auditor, reporter, count, drift, heal_verify_delay): """ Executes heal + post-heal verification and persists reporter state. """ drift = drift or {} if hasattr(auditor, "heal_with_drift"): heal_ok = auditor.heal_with_drift(drift) else: heal_ok = auditor.heal() heal_result = "restart_failed" post_drift = { "reason": "not_verified", "missing_count": 0, "extra_count": 0, "metadata_drift_count": 0, "fingerprint": "", } if heal_ok: logging.info( f"Post-heal verification in {heal_verify_delay}s " f"(pre_fingerprint={drift.get('fingerprint', '')})." ) time.sleep(heal_verify_delay) try: post_is_synced, post_count, post_drift = auditor.reconcile() heal_result = "success" if post_is_synced else "failed" verify_error = None if post_is_synced else "Post-heal verification failed" reporter.update_status( post_is_synced, post_count, last_error=verify_error, missing_count=post_drift.get("missing_count", 0), extra_count=post_drift.get("extra_count", 0), metadata_drift_count=post_drift.get("metadata_drift_count", 0), last_drift_fingerprint=post_drift.get("fingerprint", ""), last_heal_result=heal_result, ) logging.warning( "Post-heal verification result " f"result={heal_result} pre={drift.get('fingerprint', '')} " f"post={post_drift.get('fingerprint', '')} " f"missing={post_drift.get('missing_count', 0)} " f"extra={post_drift.get('extra_count', 0)} " f"metadata={post_drift.get('metadata_drift_count', 0)}" ) except Exception as e: heal_result = "verify_error" reporter.update_status( False, count, last_error=f"Post-heal verify error: {e}", missing_count=0, extra_count=0, metadata_drift_count=0, last_drift_fingerprint=drift.get("fingerprint", ""), last_heal_result=heal_result, ) post_drift = { "reason": "verify_error", "missing_count": 0, "extra_count": 0, "metadata_drift_count": 0, "fingerprint": "", } logging.error( "Post-heal verification crashed " f"(pre_fingerprint={drift.get('fingerprint', '')}): {e}" ) else: reporter.update_status( False, count, last_error="Bouncer restart failed", missing_count=drift.get("missing_count", 0), extra_count=drift.get("extra_count", 0), metadata_drift_count=drift.get("metadata_drift_count", 0), last_drift_fingerprint=drift.get("fingerprint", ""), last_heal_result=heal_result, ) logging.error( f"Heal restart failed; skipping verification " f"(pre_fingerprint={drift.get('fingerprint', '')})." ) return heal_result, post_drift