import logging import os import time from datetime import datetime, timedelta, timezone 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) parsed_last_time = datetime.fromisoformat(ts_str) if parsed_last_time.tzinfo is None: # Legacy history lines were written as local naive timestamps. local_tz = datetime.now().astimezone().tzinfo or timezone.utc last_time = parsed_last_time.replace(tzinfo=local_tz).astimezone(timezone.utc) else: last_time = parsed_last_time.astimezone(timezone.utc) 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(timezone.utc) - 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 recheck_membership_mismatch(auditor, result, recheck_delay, wait=time.sleep): """ Re-audits after a short delay when the finding is a membership mismatch, so decisions the bouncer has not applied yet are not treated as drift. """ is_synced, _count, drift = result if is_synced or recheck_delay <= 0: return result if (drift or {}).get("reason") != "membership_mismatch": return result logging.warning( f"Membership mismatch seen; re-checking in {recheck_delay}s before healing." ) wait(recheck_delay) rechecked = auditor.reconcile() if rechecked[0]: logging.info("Membership mismatch cleared on re-check; no heal needed.") else: logging.warning("Drift persisted on re-check.") return rechecked 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", ""), 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", ""), 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", ""), heal_result=heal_result, ) logging.error( f"Heal restart failed; skipping verification " f"(pre_fingerprint={drift.get('fingerprint', '')})." ) return heal_result, post_drift