From 09a4ecb326dc6d31a459749aa6b16f566ab51132 Mon Sep 17 00:00:00 2001 From: "juvenal.diaz" Date: Wed, 4 Nov 2026 14:31:07 -0600 Subject: [PATCH] Verify heal actions with focused live probes --- docs/app-ops.md | 7 ++ docs/templates/app-ops.md.tmpl | 7 ++ jeannie | 15 +++ scripts/heal | 138 ++++++++++++++---------- tests/jeannie/test_self_heal_context.py | 28 ++++- 5 files changed, 134 insertions(+), 61 deletions(-) diff --git a/docs/app-ops.md b/docs/app-ops.md index bf423dd..d3de37a 100644 --- a/docs/app-ops.md +++ b/docs/app-ops.md @@ -12,6 +12,13 @@ report identifies its mode, and fast mode cannot establish backup freshness or the absence of recent errors. Healing collects deep evidence and rejects an explicitly supplied fast status report. +After a planner-driven heal, Jeannie verifies the original finding with a +focused live check: the affected Gitea endpoint/container, RPi DNS or service, +selected cluster runtime/API/node, or stale-pod eligibility. Kubernetes +verification rechecks the pinned identity. An unknown action is not declared +healed; failed checks retry up to `LAB_HEAL_VERIFY_TIMEOUT_SECONDS` (default +180 seconds), with the configured verification interval. + Compact `status` and `doctor-homelab` run independent read-only probes in parallel (four at a time by default, capped at eight). Set `LAB_REPORT_PARALLELISM=1` to serialize them or `LAB_REPORT_TIMING=true` to diff --git a/docs/templates/app-ops.md.tmpl b/docs/templates/app-ops.md.tmpl index 4f1c15a..2daa0a8 100644 --- a/docs/templates/app-ops.md.tmpl +++ b/docs/templates/app-ops.md.tmpl @@ -12,6 +12,13 @@ report identifies its mode, and fast mode cannot establish backup freshness or the absence of recent errors. Healing collects deep evidence and rejects an explicitly supplied fast status report. +After a planner-driven heal, Jeannie verifies the original finding with a +focused live check: the affected Gitea endpoint/container, RPi DNS or service, +selected cluster runtime/API/node, or stale-pod eligibility. Kubernetes +verification rechecks the pinned identity. An unknown action is not declared +healed; failed checks retry up to `LAB_HEAL_VERIFY_TIMEOUT_SECONDS` (default +180 seconds), with the configured verification interval. + Compact `status` and `doctor-homelab` run independent read-only probes in parallel (four at a time by default, capped at eight). Set `LAB_REPORT_PARALLELISM=1` to serialize them or `LAB_REPORT_TIMING=true` to diff --git a/jeannie b/jeannie index c33be20..8d64eef 100755 --- a/jeannie +++ b/jeannie @@ -312,6 +312,21 @@ case "${1:-}" in __up-task) up_task "${2:-}" ;; + __heal-check) + case "${2:-}" in + api) status_kubernetes_api_ok ;; + nodes) status_kubernetes_nodes_ready ;; + runtime) status_cluster_control_runtime ;; + control-vm) status_pimox_control_plane_running ;; + worker-vms) status_pimox_workers_running ;; + pihole) check_pihole_dns_query ;; + rpi-storage) check_rpi_docker_root_state ;; + uptime-kuma) status_rpi_uptime_kuma_ok ;; + gitea-container) status_container_running "${GITEA_CONTAINER_NAME:-homelab-gitea}" ;; + gitea-http) status_http_ok "http://127.0.0.1:${LAB_GITEA_HTTP_PORT:-3000}/" ;; + *) echo "Unknown heal verification check." >&2; exit 2 ;; + esac + ;; "" | help | -h | --help) print_usage ;; diff --git a/scripts/heal b/scripts/heal index 8c2c56b..a733c97 100755 --- a/scripts/heal +++ b/scripts/heal @@ -498,24 +498,20 @@ def stale_reason(status: dict[str, object]) -> str: return "" -def stale_pods() -> tuple[list[dict[str, str]], list[dict[str, str]]]: - process = subprocess.run( - [ - "kubectl", - "--kubeconfig", - str(DEFAULT_KUBECONFIG), - "get", - "pods", - "-A", - "-o", - "json", - ], - cwd=REPO_ROOT, - text=True, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - check=False, - ) +def stale_pods(timeout=30) -> tuple[list[dict[str, str]], list[dict[str, str]]]: + try: + process = subprocess.run( + ["kubectl", "--kubeconfig", str(DEFAULT_KUBECONFIG), "get", "pods", "-A", "-o", "json"], + cwd=REPO_ROOT, + text=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + check=False, + timeout=timeout, + ) + except (OSError, subprocess.TimeoutExpired) as error: + print(f"Cannot read pods: {error}", file=sys.stderr) + raise SystemExit(1) if process.returncode != 0: print(process.stderr.strip() or "kubectl get pods failed", file=sys.stderr) raise SystemExit(process.returncode) @@ -598,12 +594,15 @@ def cleanup_stale_pods(yes: bool) -> int: return 0 -def cluster_identity_ok(startup=False) -> bool: - result = subprocess.run( - [sys.executable, str(REPO_ROOT / "scripts/cluster-context.py"), "check-startup" if startup else "check", "--profile", CLUSTER["profile"], "--kubeconfig", str(DEFAULT_KUBECONFIG)], - cwd=REPO_ROOT, text=True, stdout=subprocess.DEVNULL, check=False, - ) - return result.returncode == 0 +def cluster_identity_ok(startup=False, timeout=30) -> bool: + try: + result = subprocess.run( + [sys.executable, str(REPO_ROOT / "scripts/cluster-context.py"), "check-startup" if startup else "check", "--profile", CLUSTER["profile"], "--kubeconfig", str(DEFAULT_KUBECONFIG)], + cwd=REPO_ROOT, text=True, stdout=subprocess.DEVNULL, check=False, timeout=timeout, + ) + return result.returncode == 0 + except (OSError, subprocess.TimeoutExpired): + return False def load_heal_state() -> dict[str, object]: @@ -676,59 +675,80 @@ def verify_healed(target: dict[str, object]) -> bool: interval = int(os.environ.get("LAB_HEAL_VERIFY_INTERVAL_SECONDS", "10")) deadline = time.monotonic() + timeout while True: - if target_is_healed(target): + remaining = max(0.1, deadline - time.monotonic()) + result = target_is_healed(target, timeout=min(30, remaining)) + if result is None: + print("No focused verification exists for this action; manual investigation is required.") + return False + if result: return True if time.monotonic() >= deadline: return False remaining = int(deadline - time.monotonic()) print(f"waiting for heal verification ({max(remaining, 0)}s left)...") - time.sleep(interval) + time.sleep(min(interval, max(0, deadline - time.monotonic()))) -def target_is_healed(target: dict[str, object]) -> bool: +def target_is_healed(target: dict[str, object], timeout=30) -> bool | None: command = str(target.get("command") or "") + deadline = time.monotonic() + timeout + if (command == "./jeannie start-cluster" or command == "./jeannie heal cleanup-stale-pods --yes" + or re.fullmatch(r"\./jeannie workers restart \d+", command)): + if not cluster_identity_ok(timeout=max(0.1, deadline - time.monotonic())): + return False + remaining = max(0.1, deadline - time.monotonic()) if command == "./jeannie heal cleanup-stale-pods --yes": try: - eligible, _ = stale_pods() - except SystemExit: + eligible, _ = stale_pods(timeout=remaining) + except (SystemExit, ValueError, TypeError): return False # Pending workloads are a separate scheduling issue and cannot be # fixed by removing terminal residual pod records. return not eligible - worker_match = re.search(r"\bworkers\s+restart\s+(\d+)\b", command) - if worker_match: - return pimox_worker_ready(int(worker_match.group(1))) - - try: - status = load_status(None) - except SystemExit: - return False - area = str(target.get("area") or "") + worker_match = re.fullmatch(r"\./jeannie workers restart (\d+)", command) check = str(target.get("check") or "") - for row in status_rows(status): - if str(row.get("area") or "") == area and str(row.get("check") or "") == check: - return False - return True + if worker_match: + return pimox_worker_ready(int(worker_match.group(1)), timeout=remaining) + + checks = { + ("./jeannie start-cluster", "Kubernetes API"): "api", + ("./jeannie start-cluster", "API ready"): "api", + ("./jeannie start-cluster", "API"): "api", + ("./jeannie start-cluster", "Kubernetes nodes Ready"): "nodes", + ("./jeannie start-cluster", "Nodes Ready"): "nodes", + ("./jeannie start-cluster", "Control-plane runtime"): "runtime", + ("./jeannie start-cluster", "Control-plane VM running"): "control-vm", + ("./jeannie start-cluster", "Pimox workers running"): "worker-vms", + ("./jeannie start-cluster", "Workers running"): "worker-vms", + ("./jeannie start-cluster", "Worker VMs running"): "worker-vms", + ("./jeannie rpi-services", "Pi-hole DNS"): "pihole", + ("./jeannie rpi-services", "RPi Docker root state"): "rpi-storage", + ("./jeannie rpi-services", "Uptime Kuma HTTP"): "uptime-kuma", + ("./jeannie deploy-gitea", "Gitea container"): "gitea-container", + ("./jeannie deploy-gitea", "Gitea local HTTP"): "gitea-http", + } + probe = checks.get((command, check)) + if probe is None: + return None + try: + result = subprocess.run([str(REPO_ROOT / "jeannie"), "__heal-check", probe], + cwd=REPO_ROOT, text=True, stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, check=False, timeout=remaining) + except (OSError, subprocess.TimeoutExpired): + return False + return result.returncode == 0 -def pimox_worker_ready(index: int) -> bool: +def pimox_worker_ready(index: int, timeout=30) -> bool: node_name = f"pimox-worker-{index:02d}" - process = subprocess.run( - [ - "kubectl", - "--kubeconfig", - str(DEFAULT_KUBECONFIG), - "get", - "node", - node_name, - "--no-headers", - ], - cwd=REPO_ROOT, - text=True, - stdout=subprocess.PIPE, - stderr=subprocess.DEVNULL, - check=False, - ) + try: + process = subprocess.run( + ["kubectl", "--kubeconfig", str(DEFAULT_KUBECONFIG), "get", "node", node_name, "--no-headers"], + cwd=REPO_ROOT, text=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, + check=False, timeout=timeout, + ) + except (OSError, subprocess.TimeoutExpired): + return False if process.returncode != 0: return False parts = process.stdout.split() diff --git a/tests/jeannie/test_self_heal_context.py b/tests/jeannie/test_self_heal_context.py index 62c204f..5ed5d25 100644 --- a/tests/jeannie/test_self_heal_context.py +++ b/tests/jeannie/test_self_heal_context.py @@ -45,16 +45,40 @@ class SelfHealContextTests(unittest.TestCase): def test_pending_workloads_do_not_fail_successful_residual_cleanup(self): module = self.heal() - with patch.object(module, "stale_pods", return_value=([], [])), \ + with patch.object(module, "cluster_identity_ok", return_value=True), \ + patch.object(module, "stale_pods", return_value=([], [])), \ patch.object(module, "load_status") as status: self.assertTrue(module.target_is_healed({"command": "./jeannie heal cleanup-stale-pods --yes"})) status.assert_not_called() def test_remaining_eligible_residual_fails_cleanup_verification(self): module = self.heal() - with patch.object(module, "stale_pods", return_value=([{"reason": "Evicted"}], [])): + with patch.object(module, "cluster_identity_ok", return_value=True), \ + patch.object(module, "stale_pods", return_value=([{"reason": "Evicted"}], [])): self.assertFalse(module.target_is_healed({"command": "./jeannie heal cleanup-stale-pods --yes"})) + def test_gitea_verification_uses_only_the_focused_probe(self): + module = self.heal() + completed = subprocess.CompletedProcess([], 0) + with patch.object(module.subprocess, "run", return_value=completed) as run, \ + patch.object(module, "load_status") as status: + self.assertTrue(module.target_is_healed({"command": "./jeannie deploy-gitea", "check": "Gitea local HTTP"})) + self.assertEqual(run.call_args.args[0][-2:], ["__heal-check", "gitea-http"]) + status.assert_not_called() + + def test_unmapped_verification_never_reports_success(self): + module = self.heal() + with patch.object(module, "load_status") as status: + self.assertIsNone(module.target_is_healed({"command": "./jeannie unknown", "check": "missing"})) + status.assert_not_called() + + def test_cluster_verification_requires_matching_live_identity(self): + module = self.heal() + with patch.object(module, "cluster_identity_ok", return_value=False), \ + patch.object(module.subprocess, "run") as run: + self.assertFalse(module.target_is_healed({"command": "./jeannie start-cluster", "check": "API"})) + run.assert_not_called() + class WebhookRoutingTests(unittest.TestCase): def setUp(self):