Files
patrickandClaude Opus 5.5 16338a2507
CI / Unit tests (push) Successful in 3s
CI / Unit tests (pull_request) Successful in 3s
fix(healing): judge post-heal verification against the pre-heal decisions
A decision issued in the seconds between a heal and its verification is
missing from the kernel until the bouncer's next poll, so verification
reported the heal as failed even though it had fixed the drift it was
started for. Seen on a node: a metadata heal fixed a stale TTL, a new
ban arrived inside the 5 s window, and the heal was logged as failed;
the next audit found the node in sync.

reconcile() now records the decision values it saw (last_truth_values)
and takes an optional baseline_truth. Post-heal verification passes the
values the drift was found against; values whose LAPI membership changed
since then are left out of the drift, logged with a count, returned as
lapi_changed_values, and checked by the next regular audit. Drift on
decisions that existed when the heal started still fails verification.
The regular audit and the membership re-check are unchanged.

Tests: baseline handling in reconcile, the verification call, and a
replay of the logged sequence (failed before, success now). 78 tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 23:32:41 -05:00

212 lines
7.7 KiB
Python

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): "
f"the heal at {last_time.isoformat()} did not hold "
f"(fingerprint={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 {}
# The decisions the drift was found against. Verification is judged against
# them, so a decision issued after the heal started (which the bouncer only
# applies on its next poll) is not counted as a failed heal.
baseline_truth = getattr(auditor, "last_truth_values", None)
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:
if baseline_truth is None:
post_is_synced, post_count, post_drift = auditor.reconcile()
else:
post_is_synced, post_count, post_drift = auditor.reconcile(baseline_truth=baseline_truth)
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,
unenforceable_range_count=len(post_drift.get("unenforceable_ranges", [])),
)
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)} "
f"lapi_changed={len(post_drift.get('lapi_changed_values', []))}"
)
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