From aa83840f43166f7dd0de1471346ec8ef632bca9b Mon Sep 17 00:00:00 2001 From: Omar Sy Date: Sun, 14 Jun 2026 18:02:59 +0200 Subject: [PATCH 1/7] =?UTF-8?q?feat(observability):=20greffer=20self-healt?= =?UTF-8?q?h=20=E2=80=94=20/readyz=20+=20watchdog=20+=20log=20rotation?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Feature #3 of the greffer-observability epic. Three pieces: - **/readyz** (app/readiness.py + routers/health.py): readiness with a fatal-vs-degraded split. FATAL (503): docker daemon unreachable, or a long-lived worker (monitor/crl-sync/heartbeat) dead. DEGRADED (200 + reasons): registration pending acceptance — a greffer awaiting accept is healthy and must not be flapped. Auth via X-GREFFON-TOKEN (publicly routed like /healthz). /healthz is unchanged (a greffer-cli contract). - **In-process watchdog** (app/workers/watchdog.py): plain `docker compose` does not restart on an unhealthy healthcheck, so the greffer self-monitors and, on a FATAL condition sustained past a grace window, sends itself SIGTERM (graceful, so lifespan teardown runs) and `restart: unless-stopped` recovers it. On by default; the safety is in the logic (only-fatal, grace window, never on degraded), not a flag. The compose healthcheck targets /readyz for visibility only, with start_period so a pending-acceptance greffer never reads unhealthy. - **Compose log rotation**: a json-file max-size/max-file anchor on the greffer's own services (greffer/nginx/tunnel-sidecar), and injected into every rendered greffon INSTANCE compose (the real disk risk) unless the catalog author set their own logging. Worker task handles are exposed on app.state.worker_tasks so /readyz and the watchdog can tell a live long-lived worker from a crashed one. 18 new tests; full suite 395 passing; compose config validates (base + tunnel profile). Co-Authored-By: Claude Opus 4.8 --- app/lifespan.py | 4 ++ app/readiness.py | 88 ++++++++++++++++++++++++++++++++++ app/routers/health.py | 33 ++++++++++++- app/settings.py | 21 ++++++++ app/workers/__init__.py | 9 +++- app/workers/watchdog.py | 72 ++++++++++++++++++++++++++++ apps/utils/docker/compose.py | 23 +++++++++ docker-compose.yml | 36 ++++++++++++++ tests/test_log_rotation.py | 42 ++++++++++++++++ tests/test_readiness.py | 74 ++++++++++++++++++++++++++++ tests/test_readyz.py | 61 +++++++++++++++++++++++ tests/test_workers_watchdog.py | 65 +++++++++++++++++++++++++ 12 files changed, 526 insertions(+), 2 deletions(-) create mode 100644 app/readiness.py create mode 100644 app/workers/watchdog.py create mode 100644 tests/test_log_rotation.py create mode 100644 tests/test_readiness.py create mode 100644 tests/test_readyz.py create mode 100644 tests/test_workers_watchdog.py diff --git a/app/lifespan.py b/app/lifespan.py index 308ddecf..6b0c9cce 100644 --- a/app/lifespan.py +++ b/app/lifespan.py @@ -34,6 +34,10 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]: yield return tasks = start_workers(app) + # Expose the task handles by name so /readyz and the watchdog can tell a + # live long-lived worker from a crashed one (Feature #3). Set synchronously + # before the first ``yield``, so it is populated before any task runs. + app.state.worker_tasks = {t.get_name(): t for t in tasks} logger.info("started %d background workers", len(tasks)) try: yield diff --git a/app/readiness.py b/app/readiness.py new file mode 100644 index 00000000..ff2f9605 --- /dev/null +++ b/app/readiness.py @@ -0,0 +1,88 @@ +"""Greffer self-readiness evaluation (greffer-observability epic, Feature #3). + +Shared by the ``/readyz`` endpoint (operator / manager visibility) and the +in-process watchdog (self-heal). The fatal-vs-degraded split is deliberate: + +- **fatal**: the greffer is wedged and a process restart is the right fix. The + watchdog acts on a SUSTAINED fatal condition; the compose healthcheck surfaces + it for ``docker compose ps``. +- **degraded**: something is off but a restart would not help (and could + restart-loop). A greffer pending acceptance is the canonical case: it is + healthy and MUST stay up until an admin accepts it. + +Reasons are machine-readable tokens carried by both the endpoint body and the +watchdog's logs. +""" +from __future__ import annotations + +import logging +from dataclasses import dataclass, field + +from fastapi import FastAPI + +logger = logging.getLogger("greffer") + +# Long-lived worker tasks whose death means the greffer is wedged (the loop is +# gone until a restart). ``greffer-register`` is one-shot (it exits normally +# after success) and ``greffer-reregister`` is an idle supervisor (its death +# only delays a 403-driven re-register, which is recoverable), so neither is +# fatal here. +FATAL_WORKERS = ("greffer-monitor", "greffer-crl-sync", "greffer-heartbeat") + + +@dataclass +class Readiness: + fatal: bool = False + reasons: list[str] = field(default_factory=list) + + @property + def status(self) -> str: + if self.fatal: + return "fatal" + return "degraded" if self.reasons else "ready" + + +def _docker_ok() -> bool: + """Ping the docker daemon. Imported lazily so unit tests run without the + docker SDK initializing its ``from_env()`` client at import (mirrors + status_collect / the monitor).""" + try: + from apps.utils.docker.base import client + + client.ping() + return True + except Exception: + # A readiness probe must treat ANY ping failure as "daemon unreachable" + # (the docker SDK raises APIError / connection / socket errors of + # several types); logging keeps it from being a silent swallow. + logger.warning("readiness: docker ping failed", exc_info=True) + return False + + +def evaluate_readiness(app: FastAPI) -> Readiness: + """Compute the greffer's readiness. Pure-ish (only reads ``app.state`` and + pings docker), so the endpoint and the watchdog share one definition.""" + r = Readiness() + + # fatal: docker daemon unreachable. Every compose op depends on it; a + # restart re-establishes the client. + if not _docker_ok(): + r.fatal = True + r.reasons.append("docker_unreachable") + + # fatal: a long-lived worker crashed. ``task.done()`` on a forever-loop + # worker means it returned or raised; only a restart brings the loop back. + tasks = getattr(app.state, "worker_tasks", None) or {} + for name in FATAL_WORKERS: + task = tasks.get(name) + if task is not None and task.done(): + r.fatal = True + r.reasons.append(f"worker_dead:{name}") + + # degraded: registration not yet accepted. The greffer is healthy and must + # NOT be restarted while it waits for an admin to accept it. + registered = getattr(app.state, "registered", None) + if registered is not None and not registered.is_set(): + r.reasons.append("registration_pending") + + return r diff --git a/app/routers/health.py b/app/routers/health.py index 8babeb14..1dc2b3e5 100644 --- a/app/routers/health.py +++ b/app/routers/health.py @@ -1,6 +1,10 @@ from __future__ import annotations -from fastapi import APIRouter, Request +from fastapi import APIRouter, Depends, Request +from fastapi.responses import JSONResponse + +from app.auth import require_token +from app.readiness import evaluate_readiness router = APIRouter() @@ -21,3 +25,30 @@ async def healthz(request: Request) -> dict[str, str]: "id": request.app.state.settings.greffer_id, "status": "ok", } + + +@router.get("/readyz", dependencies=[Depends(require_token)]) +async def readyz(request: Request) -> JSONResponse: + """Readiness with a fatal-vs-degraded split (greffer-observability epic, + Feature #3). + + Returns **503** on a FATAL condition (docker daemon unreachable, a + long-lived worker dead) so the compose healthcheck can surface it; **200** + otherwise, including when ``degraded`` (a greffer pending acceptance is + healthy and must not be flapped). The ``reasons`` list is machine-readable. + + Auth is ``X-GREFFON-TOKEN`` (same as the controller routes) because this + endpoint is publicly routed like ``/healthz`` and would otherwise leak the + greffer's internal state. The in-process watchdog shares + ``evaluate_readiness`` so the endpoint and the self-heal decision can never + drift. ``/healthz`` stays liveness-only (a greffer-cli contract). + """ + r = evaluate_readiness(request.app) + return JSONResponse( + { + "id": request.app.state.settings.greffer_id, + "status": r.status, + "reasons": r.reasons, + }, + status_code=503 if r.fatal else 200, + ) diff --git a/app/settings.py b/app/settings.py index d7f2d338..0e4186ff 100644 --- a/app/settings.py +++ b/app/settings.py @@ -139,6 +139,27 @@ def _heartbeat_interval_in_range(cls, v): # bug Codex caught before merge (greffon/greffer#17 review). greffer_workers_enabled: bool = False + # Self-health watchdog (greffer-observability epic, Feature #3). The + # watchdog evaluates /readyz's FATAL conditions and, when one is sustained + # past the grace window, exits the uvicorn process so ``restart: + # unless-stopped`` recovers it (plain ``docker compose`` does NOT restart a + # container on an unhealthy healthcheck). On by default. Degraded states + # (e.g. registration pending acceptance) are NEVER fatal, so a greffer + # awaiting acceptance does not restart-loop. ``grace`` rides out transient + # docker blips. Field names carry the ``greffer_`` prefix to bind the + # documented GREFFER_WATCHDOG_* env vars (see prefix pitfall above). + greffer_watchdog_enabled: bool = True + greffer_watchdog_interval: int = 10 + greffer_watchdog_grace: int = 30 + + # Compose log rotation for the greffon INSTANCE containers the greffer + # renders (the real disk risk: an instance can log unbounded under the + # docker json-file driver's default of no rotation). Injected per service + # in ``create_compose`` unless the catalog author already set ``logging``. + # The greffer's OWN services carry static logging in docker-compose.yml. + greffer_instance_log_max_size: str = "10m" + greffer_instance_log_max_file: int = 3 + logger_name: str = "greffer" diff --git a/app/workers/__init__.py b/app/workers/__init__.py index 0fb055d6..c2672ab1 100644 --- a/app/workers/__init__.py +++ b/app/workers/__init__.py @@ -29,12 +29,13 @@ from app.workers.heartbeat import heartbeat_worker from app.workers.monitor import monitor_worker from app.workers.register import register_worker, reregister_worker +from app.workers.watchdog import watchdog_worker logger = logging.getLogger("greffer") def start_workers(app: FastAPI) -> list[asyncio.Task]: - return [ + tasks = [ asyncio.create_task(register_worker(app), name="greffer-register"), asyncio.create_task(monitor_worker(app), name="greffer-monitor"), asyncio.create_task(crl_sync_worker(app), name="greffer-crl-sync"), @@ -42,6 +43,12 @@ def start_workers(app: FastAPI) -> list[asyncio.Task]: asyncio.create_task( reregister_worker(app), name="greffer-reregister"), ] + # Self-heal watchdog (Feature #3), on by default. Appended after the others + # so their tasks exist by the time it first evaluates readiness. + if app.state.settings.greffer_watchdog_enabled: + tasks.append(asyncio.create_task( + watchdog_worker(app), name="greffer-watchdog")) + return tasks async def stop_workers(tasks: list[asyncio.Task]) -> None: diff --git a/app/workers/watchdog.py b/app/workers/watchdog.py new file mode 100644 index 00000000..944644fa --- /dev/null +++ b/app/workers/watchdog.py @@ -0,0 +1,72 @@ +"""Self-heal watchdog (greffer-observability epic, Feature #3). + +Plain ``docker compose`` (non-Swarm) does NOT restart a container on an +unhealthy healthcheck; ``restart: unless-stopped`` fires only on process exit. +So the greffer watches its OWN readiness in-process and, when a FATAL condition +(see ``app/readiness.py``) is sustained past the grace window, exits the uvicorn +process so the restart policy recovers it. + +Safety (the watchdog is on by default, so the safety lives in the logic, not a +flag): only FATAL conditions ever trigger an exit; degraded states (e.g. +registration pending acceptance) never do, so a greffer awaiting acceptance is +never restart-looped. The grace window rides out transient docker blips, and a +condition that clears before grace expires resets the timer. +""" +from __future__ import annotations + +import asyncio +import logging +import os +import signal +import time + +from fastapi import FastAPI + +from app.readiness import evaluate_readiness +from app.settings import Settings + +logger = logging.getLogger("greffer") + + +def _terminate() -> None: + """Ask uvicorn to shut down gracefully so the container's restart policy + brings up a fresh process. SIGTERM (not ``os._exit``) so lifespan teardown + and worker cancellation run rather than leaving in-flight compose ops or + file writes half-done. Isolated in a function so tests can patch it.""" + logger.critical("watchdog: sending SIGTERM to self (pid=%s) for restart", + os.getpid()) + os.kill(os.getpid(), signal.SIGTERM) + + +async def watchdog_worker(app: FastAPI) -> None: + settings: Settings = app.state.settings + fatal_since: float | None = None + try: + while True: + await asyncio.sleep(settings.greffer_watchdog_interval) + readiness = evaluate_readiness(app) + if not readiness.fatal: + if fatal_since is not None: + logger.info( + "watchdog: fatal condition cleared before grace " + "expired; not restarting") + fatal_since = None + continue + now = time.monotonic() + if fatal_since is None: + # First fatal observation: start the grace clock, do not act + # yet (rides out a transient blip). + fatal_since = now + logger.error( + "watchdog: FATAL readiness %s; will restart if sustained " + "%ss", readiness.reasons, settings.greffer_watchdog_grace) + elif now - fatal_since >= settings.greffer_watchdog_grace: + logger.critical( + "watchdog: FATAL readiness sustained >= %ss (%s); exiting " + "uvicorn for restart", settings.greffer_watchdog_grace, + readiness.reasons) + _terminate() + return + except asyncio.CancelledError: + logger.info("watchdog cancelled") + raise diff --git a/apps/utils/docker/compose.py b/apps/utils/docker/compose.py index 5abdd906..435e23a1 100644 --- a/apps/utils/docker/compose.py +++ b/apps/utils/docker/compose.py @@ -518,6 +518,28 @@ def _compute_instance_context(greffon_info): return greffon_info +def _inject_instance_log_rotation(compose): + """Cap per-container log disk on the greffon INSTANCE containers + (greffer-observability epic, Feature #3). Docker's json-file driver does + NOT rotate by default, so a chatty instance can fill the operator's disk. + Set ``max-size``/``max-file`` on every service that has not already declared + its own ``logging`` (a catalog author's explicit choice wins). Values come + from GREFFER_INSTANCE_LOG_MAX_SIZE / _MAX_FILE (read via os.getenv here, + matching this module's env style; the same vars bind Settings fields).""" + services = (compose or {}).get('services') + if not isinstance(services, dict): + return + max_size = os.getenv('GREFFER_INSTANCE_LOG_MAX_SIZE', '10m') + max_file = os.getenv('GREFFER_INSTANCE_LOG_MAX_FILE', '3') + for service in services.values(): + if not isinstance(service, dict) or 'logging' in service: + continue + service['logging'] = { + 'driver': 'json-file', + 'options': {'max-size': max_size, 'max-file': str(max_file)}, + } + + def create_compose(compose, greffon_info): greffon_path = os.path.join(os.getenv('GREFFON_PATH', '/data'), greffon_info['id']) if not os.path.exists(greffon_path): @@ -531,6 +553,7 @@ def create_compose(compose, greffon_info): # values would otherwise be templated `{{ smtp.host }}` strings. greffon_info = _compute_integrations_context(greffon_info) _delete_unset_integration_env_keys(compose, greffon_info) + _inject_instance_log_rotation(compose) t = Template(yaml.dump(compose)) compose_file = t.render(**greffon_info) with open(os.path.join(greffon_path, 'docker-compose.yml'), 'w') as temp_file: diff --git a/docker-compose.yml b/docker-compose.yml index c7da7f53..317ba3a5 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,9 +1,22 @@ version: "3.8" + +# Log rotation for the greffer's OWN containers (greffer-observability epic, +# Feature #3). Docker's json-file driver does not rotate by default; without a +# cap, uvicorn/nginx/rathole logs grow unbounded on the operator's box. The +# greffon INSTANCE containers the greffer renders get the same treatment via +# create_compose's _inject_instance_log_rotation (the larger disk risk). +x-logging: &default-logging + driver: json-file + options: + max-size: "10m" + max-file: "3" + services: greffer: build: . image: &app app restart: unless-stopped + logging: *default-logging networks: - internal # Run pending ops migrations BEFORE uvicorn binds so they can't race @@ -46,9 +59,31 @@ services: # picks up changes. Always mounted so proxy-mode deployments # don't need a separate compose layer. - rathole-client-config:/config + # Self-health visibility (Feature #3). Targets /readyz so `docker compose + # ps` shows when the greffer is wedged. This is NOT the restart trigger: + # plain compose does not restart on `unhealthy`; the in-process watchdog + # exits the process on a sustained FATAL readyz, and `restart: + # unless-stopped` recovers it. A greffer pending acceptance is DEGRADED -> + # 200 -> healthy, so it is not flapped. start_period covers ops-migrations + + # uvicorn bind + token resolve before failures count. + healthcheck: + test: + - CMD-SHELL + - >- + python -c "import urllib.request,os; + t=open(os.path.join(os.getenv('GREFFON_PATH','/data'), + '.greffer-token')).read().strip(); + urllib.request.urlopen(urllib.request.Request( + 'http://localhost:8000/readyz', + headers={'X-GREFFON-TOKEN': t}), timeout=4)" + interval: 30s + timeout: 5s + retries: 3 + start_period: 60s nginx: build: ./nginx restart: unless-stopped + logging: *default-logging networks: - internal volumes: @@ -76,6 +111,7 @@ services: profiles: ["tunnel"] network_mode: host restart: unless-stopped + logging: *default-logging depends_on: - greffer # rathole-client forwards inbound tunnel traffic to whatever host the diff --git a/tests/test_log_rotation.py b/tests/test_log_rotation.py new file mode 100644 index 00000000..d8ff6e78 --- /dev/null +++ b/tests/test_log_rotation.py @@ -0,0 +1,42 @@ +"""Tests for instance compose log-rotation injection (Feature #3).""" +from __future__ import annotations + +from apps.utils.docker.compose import _inject_instance_log_rotation + + +def test_injects_logging_into_each_service(monkeypatch): + monkeypatch.setenv("GREFFER_INSTANCE_LOG_MAX_SIZE", "5m") + monkeypatch.setenv("GREFFER_INSTANCE_LOG_MAX_FILE", "2") + compose = {"services": {"web": {"image": "nginx"}, "db": {"image": "pg"}}} + _inject_instance_log_rotation(compose) + expected = {"driver": "json-file", + "options": {"max-size": "5m", "max-file": "2"}} + assert compose["services"]["web"]["logging"] == expected + assert compose["services"]["db"]["logging"] == expected + + +def test_respects_catalog_authors_existing_logging(monkeypatch): + compose = {"services": {"web": {"image": "nginx", + "logging": {"driver": "syslog"}}}} + _inject_instance_log_rotation(compose) + # An explicit author choice is left untouched. + assert compose["services"]["web"]["logging"] == {"driver": "syslog"} + + +def test_default_values_when_env_unset(monkeypatch): + monkeypatch.delenv("GREFFER_INSTANCE_LOG_MAX_SIZE", raising=False) + monkeypatch.delenv("GREFFER_INSTANCE_LOG_MAX_FILE", raising=False) + compose = {"services": {"web": {"image": "nginx"}}} + _inject_instance_log_rotation(compose) + assert compose["services"]["web"]["logging"]["options"] == { + "max-size": "10m", "max-file": "3"} + + +def test_no_services_is_safe(): + compose = {"version": "3"} + _inject_instance_log_rotation(compose) # must not raise + assert "services" not in compose + + +def test_none_compose_is_safe(): + _inject_instance_log_rotation(None) # must not raise diff --git a/tests/test_readiness.py b/tests/test_readiness.py new file mode 100644 index 00000000..ba95a17d --- /dev/null +++ b/tests/test_readiness.py @@ -0,0 +1,74 @@ +"""Unit tests for the readiness evaluation (greffer-observability Feature #3).""" +from __future__ import annotations + +import asyncio +from types import SimpleNamespace +from unittest.mock import Mock, patch + +from app.readiness import evaluate_readiness + + +def _app(registered: bool = True, worker_tasks: dict | None = None): + ev = asyncio.Event() + if registered: + ev.set() + return SimpleNamespace( + state=SimpleNamespace(registered=ev, worker_tasks=worker_tasks or {})) + + +def _task(done: bool): + t = Mock() + t.done.return_value = done + return t + + +def test_ready_when_all_good(): + with patch("app.readiness._docker_ok", return_value=True): + r = evaluate_readiness(_app(registered=True, worker_tasks={})) + assert not r.fatal + assert r.status == "ready" + assert r.reasons == [] + + +def test_degraded_when_registration_pending(): + # A greffer awaiting acceptance is healthy, NOT fatal — it must not be + # restart-looped by the watchdog. + with patch("app.readiness._docker_ok", return_value=True): + r = evaluate_readiness(_app(registered=False)) + assert not r.fatal + assert r.status == "degraded" + assert r.reasons == ["registration_pending"] + + +def test_fatal_when_docker_unreachable(): + with patch("app.readiness._docker_ok", return_value=False): + r = evaluate_readiness(_app(registered=True)) + assert r.fatal + assert r.status == "fatal" + assert "docker_unreachable" in r.reasons + + +def test_fatal_when_long_lived_worker_dead(): + wt = {"greffer-monitor": _task(done=True)} + with patch("app.readiness._docker_ok", return_value=True): + r = evaluate_readiness(_app(registered=True, worker_tasks=wt)) + assert r.fatal + assert "worker_dead:greffer-monitor" in r.reasons + + +def test_alive_long_lived_worker_not_fatal(): + wt = {"greffer-heartbeat": _task(done=False)} + with patch("app.readiness._docker_ok", return_value=True): + r = evaluate_readiness(_app(registered=True, worker_tasks=wt)) + assert not r.fatal + + +def test_one_shot_register_done_is_not_fatal(): + # ``register`` exits normally after success; its done() must NOT be fatal + # (only the forever-loop workers count). + wt = {"greffer-register": _task(done=True), + "greffer-monitor": _task(done=False)} + with patch("app.readiness._docker_ok", return_value=True): + r = evaluate_readiness(_app(registered=True, worker_tasks=wt)) + assert not r.fatal + assert not any("worker_dead" in reason for reason in r.reasons) diff --git a/tests/test_readyz.py b/tests/test_readyz.py new file mode 100644 index 00000000..0ea4a7dd --- /dev/null +++ b/tests/test_readyz.py @@ -0,0 +1,61 @@ +"""Tests for the /readyz endpoint (greffer-observability Feature #3).""" +from __future__ import annotations + +from unittest.mock import patch + +import pytest +from httpx import ASGITransport, AsyncClient + +from app.main import create_app +from app.settings import Settings + +AUTH = {"X-GREFFON-TOKEN": "test-token"} +DOCK = "app.readiness._docker_ok" + + +@pytest.mark.asyncio +async def test_readyz_requires_token(client: AsyncClient) -> None: + r = await client.get("/readyz") + assert r.status_code == 401 + + +@pytest.mark.asyncio +async def test_readyz_degraded_when_pending_registration( + client: AsyncClient, +) -> None: + # Docker reachable, no crashed workers, but registration not yet accepted: + # 200 + degraded (a pending greffer must never read fatal). + with patch(DOCK, return_value=True): + r = await client.get("/readyz", headers=AUTH) + assert r.status_code == 200 + body = r.json() + assert body["status"] == "degraded" + assert "registration_pending" in body["reasons"] + assert body["id"] == "test-greffer-id" + + +@pytest.mark.asyncio +async def test_readyz_fatal_when_docker_unreachable(client: AsyncClient) -> None: + with patch(DOCK, return_value=False): + r = await client.get("/readyz", headers=AUTH) + assert r.status_code == 503 + body = r.json() + assert body["status"] == "fatal" + assert "docker_unreachable" in body["reasons"] + + +@pytest.mark.asyncio +async def test_readyz_ready_when_registered_and_healthy( + settings: Settings, +) -> None: + app = create_app(token="test-token", settings=settings) + app.state.registered.set() # simulate an accepted greffer + with patch(DOCK, return_value=True): + async with AsyncClient( + transport=ASGITransport(app=app), base_url="http://test" + ) as ac: + r = await ac.get("/readyz", headers=AUTH) + assert r.status_code == 200 + body = r.json() + assert body["status"] == "ready" + assert body["reasons"] == [] diff --git a/tests/test_workers_watchdog.py b/tests/test_workers_watchdog.py new file mode 100644 index 00000000..af9ec555 --- /dev/null +++ b/tests/test_workers_watchdog.py @@ -0,0 +1,65 @@ +"""Tests for the self-heal watchdog (greffer-observability Feature #3). + +The watchdog is on by default and deliberately exits the process, so the +behaviour that matters: it acts ONLY on a sustained FATAL condition, NEVER on +degraded, and resets when a fatal blip clears before grace expires. ``sleep`` +and ``_terminate`` are patched so no real time passes and no real SIGTERM fires. +""" +from __future__ import annotations + +import asyncio +from types import SimpleNamespace +from unittest.mock import AsyncMock, patch + +import pytest + +from app.readiness import Readiness +from app.workers.watchdog import watchdog_worker + +WD = "app.workers.watchdog" + + +def _app(interval: int = 0, grace: int = 0): + return SimpleNamespace(state=SimpleNamespace(settings=SimpleNamespace( + greffer_watchdog_interval=interval, greffer_watchdog_grace=grace))) + + +@pytest.mark.asyncio +async def test_terminates_on_sustained_fatal(): + # grace=0: first fatal arms the timer, the second (>= grace) fires. + fatal = Readiness(fatal=True, reasons=["docker_unreachable"]) + with patch(f"{WD}.asyncio.sleep", new=AsyncMock()), \ + patch(f"{WD}.evaluate_readiness", return_value=fatal), \ + patch(f"{WD}._terminate") as term: + await watchdog_worker(_app(grace=0)) + term.assert_called_once() + + +@pytest.mark.asyncio +async def test_does_not_terminate_on_degraded(): + degraded = Readiness(fatal=False, reasons=["registration_pending"]) + # Break out after a couple of ticks via a cancelled sleep (simulates + # shutdown) so the forever-loop test terminates. + sleep = AsyncMock(side_effect=[None, None, asyncio.CancelledError()]) + with patch(f"{WD}.asyncio.sleep", new=sleep), \ + patch(f"{WD}.evaluate_readiness", return_value=degraded), \ + patch(f"{WD}._terminate") as term: + with pytest.raises(asyncio.CancelledError): + await watchdog_worker(_app()) + term.assert_not_called() + + +@pytest.mark.asyncio +async def test_resets_when_fatal_clears_before_grace(): + # Large grace so two quick fatals never reach it; then a ready reading + # clears the timer, so no restart even though fatals were seen. + fatal = Readiness(fatal=True, reasons=["docker_unreachable"]) + ready = Readiness(fatal=False, reasons=[]) + sleep = AsyncMock(side_effect=[None, None, None, asyncio.CancelledError()]) + with patch(f"{WD}.asyncio.sleep", new=sleep), \ + patch(f"{WD}.evaluate_readiness", + side_effect=[fatal, fatal, ready, ready]), \ + patch(f"{WD}._terminate") as term: + with pytest.raises(asyncio.CancelledError): + await watchdog_worker(_app(grace=1000)) + term.assert_not_called() From 476b25ea08264eae0f3d54ed5072dfe728f306ad Mon Sep 17 00:00:00 2001 From: Omar Sy Date: Sun, 14 Jun 2026 18:10:29 +0200 Subject: [PATCH 2/7] fix(observability): harden self-health after review (3 findings) Self-review + independent adversarial pass on Feature #3: - (MEDIUM, mine) Offload evaluate_readiness's docker ping via anyio.to_thread.run_sync in BOTH the /readyz route and the watchdog. The docker SDK ping is blocking; a hung (not down) daemon would otherwise stall the shared uvicorn event loop for the SDK timeout, freezing all requests and heartbeats. Mirrors the heartbeat worker's existing offload. - (MEDIUM) Healthcheck tolerates a missing token file: first boot before the token is persisted, or an ephemeral-token deployment (unwritable volume, token held only in memory) where the file never exists, would otherwise make the probe crash and a healthy greffer show perpetually-unhealthy. Now exits 0 when the token file is absent; a present token + FATAL /readyz (503) still reports unhealthy as intended. - (LOW) _inject_instance_log_rotation coerces GREFFER_INSTANCE_LOG_MAX_FILE to an int with a logged fallback, so a malformed value can't write an invalid max-file into every rendered instance compose and break every greffon start. Watchdog restart-loop safety (the riskiest path) was confirmed correct by both passes: fatal-only triggering, sustained-across-grace timing, proper reset, and no spurious self-SIGTERM during a legitimate `docker compose stop` or a daemon bounce. Full suite still 395 passing; compose config validates. Co-Authored-By: Claude Opus 4.8 --- app/routers/health.py | 6 +++++- app/workers/watchdog.py | 5 ++++- apps/utils/docker/compose.py | 12 +++++++++++- docker-compose.yml | 13 +++++++++---- 4 files changed, 29 insertions(+), 7 deletions(-) diff --git a/app/routers/health.py b/app/routers/health.py index 1dc2b3e5..27842ddc 100644 --- a/app/routers/health.py +++ b/app/routers/health.py @@ -1,5 +1,6 @@ from __future__ import annotations +import anyio from fastapi import APIRouter, Depends, Request from fastapi.responses import JSONResponse @@ -43,7 +44,10 @@ async def readyz(request: Request) -> JSONResponse: ``evaluate_readiness`` so the endpoint and the self-heal decision can never drift. ``/healthz`` stays liveness-only (a greffer-cli contract). """ - r = evaluate_readiness(request.app) + # ``evaluate_readiness`` pings docker (a blocking SDK call). Offload it so a + # hung daemon can't stall the uvicorn event loop (mirrors the heartbeat + # worker's anyio.to_thread offload). + r = await anyio.to_thread.run_sync(evaluate_readiness, request.app) return JSONResponse( { "id": request.app.state.settings.greffer_id, diff --git a/app/workers/watchdog.py b/app/workers/watchdog.py index 944644fa..998f2be1 100644 --- a/app/workers/watchdog.py +++ b/app/workers/watchdog.py @@ -20,6 +20,7 @@ import signal import time +import anyio from fastapi import FastAPI from app.readiness import evaluate_readiness @@ -44,7 +45,9 @@ async def watchdog_worker(app: FastAPI) -> None: try: while True: await asyncio.sleep(settings.greffer_watchdog_interval) - readiness = evaluate_readiness(app) + # Offload the docker-pinging evaluation so a hung daemon cannot + # block the event loop the other workers share. + readiness = await anyio.to_thread.run_sync(evaluate_readiness, app) if not readiness.fatal: if fatal_since is not None: logger.info( diff --git a/apps/utils/docker/compose.py b/apps/utils/docker/compose.py index 435e23a1..e191db55 100644 --- a/apps/utils/docker/compose.py +++ b/apps/utils/docker/compose.py @@ -530,7 +530,17 @@ def _inject_instance_log_rotation(compose): if not isinstance(services, dict): return max_size = os.getenv('GREFFER_INSTANCE_LOG_MAX_SIZE', '10m') - max_file = os.getenv('GREFFER_INSTANCE_LOG_MAX_FILE', '3') + # ``max-file`` must be an integer string; coerce with a fallback so a + # malformed GREFFER_INSTANCE_LOG_MAX_FILE does not write an invalid value + # into EVERY rendered instance compose and break every greffon start. + raw_max_file = os.getenv('GREFFER_INSTANCE_LOG_MAX_FILE', '3') + try: + max_file = str(int(raw_max_file)) + except (TypeError, ValueError): + logger.warning( + 'invalid GREFFER_INSTANCE_LOG_MAX_FILE=%r; using default 3', + raw_max_file) + max_file = '3' for service in services.values(): if not isinstance(service, dict) or 'logging' in service: continue diff --git a/docker-compose.yml b/docker-compose.yml index 317ba3a5..ec4500b4 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -65,15 +65,20 @@ services: # exits the process on a sustained FATAL readyz, and `restart: # unless-stopped` recovers it. A greffer pending acceptance is DEGRADED -> # 200 -> healthy, so it is not flapped. start_period covers ops-migrations + - # uvicorn bind + token resolve before failures count. + # uvicorn bind + token resolve before failures count. A missing token file + # (first boot before it is persisted, or an ephemeral-token deployment on an + # unwritable volume where the greffer holds the token only in memory) exits + # 0 rather than crashing the probe, so a healthy greffer is never shown + # perpetually-unhealthy; a present token + FATAL /readyz (503) raises and is + # reported unhealthy as intended. healthcheck: test: - CMD-SHELL - >- python -c "import urllib.request,os; - t=open(os.path.join(os.getenv('GREFFON_PATH','/data'), - '.greffer-token')).read().strip(); - urllib.request.urlopen(urllib.request.Request( + p=os.path.join(os.getenv('GREFFON_PATH','/data'),'.greffer-token'); + t=(open(p).read().strip() if os.path.exists(p) else ''); + t and urllib.request.urlopen(urllib.request.Request( 'http://localhost:8000/readyz', headers={'X-GREFFON-TOKEN': t}), timeout=4)" interval: 30s From 8d910fe829889441ad127a3a3dc138fd4b1a287b Mon Sep 17 00:00:00 2001 From: Omar Sy Date: Sun, 14 Jun 2026 18:12:24 +0200 Subject: [PATCH 3/7] test(observability): cover watchdog wiring + worker_tasks exposure Lock in that start_workers adds greffer-watchdog when enabled (default on) and omits it when greffer_watchdog_enabled=False, and that lifespan populates app.state.worker_tasks (the introspection /readyz and the watchdog depend on). Co-Authored-By: Claude Opus 4.8 --- tests/test_lifespan.py | 49 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/tests/test_lifespan.py b/tests/test_lifespan.py index 725acf90..6438acbf 100644 --- a/tests/test_lifespan.py +++ b/tests/test_lifespan.py @@ -72,6 +72,55 @@ async def _noop_worker(_app): assert expected.isdisjoint(leftover) +async def _noop_worker(_app): + await asyncio.sleep(3600) # sleep forever; cancellable + + +def _patch_all_workers(): + """Patch every worker (incl. watchdog) so none does real work; the real + watchdog would otherwise ping docker / could SIGTERM the test process.""" + from contextlib import ExitStack + + stack = ExitStack() + for name in ("register_worker", "monitor_worker", "crl_sync_worker", + "heartbeat_worker", "reregister_worker", "watchdog_worker"): + stack.enter_context(patch(f"app.workers.{name}", new=_noop_worker)) + return stack + + +@pytest.mark.asyncio +async def test_lifespan_includes_watchdog_and_exposes_worker_tasks( + settings: Settings, +) -> None: + """Watchdog is started (on by default) and ``app.state.worker_tasks`` is + populated so /readyz and the watchdog can introspect worker liveness + (Feature #3).""" + settings.greffer_workers_enabled = True # type: ignore[misc] + assert settings.greffer_watchdog_enabled is True # default on + app = create_app(token="t", settings=settings) + with _patch_all_workers(): + async with lifespan(app): + assert "greffer-watchdog" in app.state.worker_tasks + assert "greffer-monitor" in app.state.worker_tasks + names = {t.get_name() for t in asyncio.all_tasks() if not t.done()} + assert "greffer-watchdog" in names + + +@pytest.mark.asyncio +async def test_lifespan_omits_watchdog_when_disabled( + settings: Settings, +) -> None: + """``greffer_watchdog_enabled=False`` → no watchdog task, other workers + unaffected.""" + settings.greffer_workers_enabled = True # type: ignore[misc] + settings.greffer_watchdog_enabled = False # type: ignore[misc] + app = create_app(token="t", settings=settings) + with _patch_all_workers(): + async with lifespan(app): + assert "greffer-watchdog" not in app.state.worker_tasks + assert "greffer-monitor" in app.state.worker_tasks + + def test_greffer_workers_enabled_env_var_binds( monkeypatch: pytest.MonkeyPatch, ) -> None: From 18346fc8759242e063d6d47268f243775a01a6d0 Mon Sep 17 00:00:00 2001 From: Omar Sy Date: Sun, 14 Jun 2026 19:34:23 +0200 Subject: [PATCH 4/7] fix(observability): mirror self-health compose into CLI template + honor GREFFER_TOKEN (codex P2) Two P2s from codex review on greffer#72: - Mirror the Feature #3 compose additions into the CLI template (cli/greffer_cli/templates/compose.yml), which is what `greffer up` renders for operator/published-image deployments. It now carries the same x-logging anchor + per-service logging and the /readyz healthcheck, so operator installs get the health visibility and own-service log caps, not only source-tree users. - The healthcheck now resolves the token the way create_app does (resolve_token = GREFFER_TOKEN env, else the persisted .greffer-token file) instead of always reading the file. Deployments that set GREFFER_TOKEN (or fall back to an in-memory token) previously authenticated /readyz with a stale/absent file token and reported the greffer unhealthy forever. Applied to both compose files. A missing token (no env + no file) still exits 0 so a healthy greffer is never shown perpetually-unhealthy. Both compose files validate; full suite 397 passing. Co-Authored-By: Claude Opus 4.8 --- cli/greffer_cli/templates/compose.yml | 35 +++++++++++++++++++++++++++ docker-compose.yml | 17 +++++++------ 2 files changed, 45 insertions(+), 7 deletions(-) diff --git a/cli/greffer_cli/templates/compose.yml b/cli/greffer_cli/templates/compose.yml index b79384cf..26cf1323 100644 --- a/cli/greffer_cli/templates/compose.yml +++ b/cli/greffer_cli/templates/compose.yml @@ -26,6 +26,15 @@ version: "3.8" # any operator-chosen --config-dir. name: greffer +# Log rotation for the greffer's OWN containers (greffer-observability epic, +# Feature #3). Mirrors greffer/docker-compose.yml; the greffon INSTANCE +# containers get the same treatment via the greffer's create_compose injection. +x-logging: &default-logging + driver: json-file + options: + max-size: "10m" + max-file: "3" + services: greffer: # Image refs match what .github/workflows/docker-publish.yml pushes: @@ -36,6 +45,7 @@ services: # tags and bump cli/IMAGE_TAG in lockstep with each cut. image: greffon/greffer: restart: unless-stopped + logging: *default-logging networks: - internal env_file: @@ -57,10 +67,34 @@ services: # mounted so proxy-mode deployments don't need a separate compose # layer; the sidecar only starts when --profile tunnel is passed. - rathole-client-config:/config + # Self-health visibility (Feature #3) — mirrors greffer/docker-compose.yml. + # Targets /readyz so `docker compose ps` shows when the greffer is wedged; + # NOT the restart trigger (plain compose does not act on `unhealthy` — the + # in-process watchdog restarts on a sustained FATAL readyz). A greffer + # pending acceptance is DEGRADED -> 200 -> healthy. The probe resolves the + # token like create_app (GREFFER_TOKEN env, else the persisted file); a + # missing token exits 0 so a healthy greffer is never shown perpetually- + # unhealthy. + healthcheck: + test: + - CMD-SHELL + - >- + python -c "import urllib.request,os; + p=os.path.join(os.getenv('GREFFON_PATH','/data'),'.greffer-token'); + t=os.getenv('GREFFER_TOKEN') or + (open(p).read().strip() if os.path.exists(p) else ''); + t and urllib.request.urlopen(urllib.request.Request( + 'http://localhost:8000/readyz', + headers={'X-GREFFON-TOKEN': t}), timeout=4)" + interval: 30s + timeout: 5s + retries: 3 + start_period: 60s nginx: image: greffon/greffer-nginx: restart: unless-stopped + logging: *default-logging networks: - internal extra_hosts: @@ -86,6 +120,7 @@ services: profiles: ["tunnel"] network_mode: host restart: unless-stopped + logging: *default-logging depends_on: - greffer extra_hosts: diff --git a/docker-compose.yml b/docker-compose.yml index ec4500b4..214e280a 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -65,19 +65,22 @@ services: # exits the process on a sustained FATAL readyz, and `restart: # unless-stopped` recovers it. A greffer pending acceptance is DEGRADED -> # 200 -> healthy, so it is not flapped. start_period covers ops-migrations + - # uvicorn bind + token resolve before failures count. A missing token file - # (first boot before it is persisted, or an ephemeral-token deployment on an - # unwritable volume where the greffer holds the token only in memory) exits - # 0 rather than crashing the probe, so a healthy greffer is never shown - # perpetually-unhealthy; a present token + FATAL /readyz (503) raises and is - # reported unhealthy as intended. + # uvicorn bind + token resolve before failures count. The probe resolves the + # token the way create_app does (resolve_token = GREFFER_TOKEN env, else the + # persisted file), so an operator-set GREFFER_TOKEN authenticates correctly + # instead of reading a stale/absent file. A missing token (no env + no file: + # an ephemeral-token deployment on an unwritable volume) exits 0 rather than + # crashing the probe, so a healthy greffer is never shown perpetually- + # unhealthy; a present token + FATAL /readyz (503) raises and is reported + # unhealthy as intended. healthcheck: test: - CMD-SHELL - >- python -c "import urllib.request,os; p=os.path.join(os.getenv('GREFFON_PATH','/data'),'.greffer-token'); - t=(open(p).read().strip() if os.path.exists(p) else ''); + t=os.getenv('GREFFER_TOKEN') or + (open(p).read().strip() if os.path.exists(p) else ''); t and urllib.request.urlopen(urllib.request.Request( 'http://localhost:8000/readyz', headers={'X-GREFFON-TOKEN': t}), timeout=4)" From 540e3aeebd771c5d060d21220e4028b7a26fea00 Mon Sep 17 00:00:00 2001 From: Omar Sy Date: Sun, 14 Jun 2026 19:45:43 +0200 Subject: [PATCH 5/7] fix(observability): bound the watchdog readiness probe (codex P2) The earlier offload moved the blocking docker ping off the event loop, but the watchdog still awaited the probe thread with no timeout. A HUNG (not down) docker daemon would block the probe inside the ping, so the watchdog would never advance fatal_since or reach _terminate() for exactly the docker failure it exists to heal, and shutdown cancellation could be held behind the same call. Wrap the evaluation in asyncio.wait_for(timeout=greffer_watchdog_probe_timeout, default 5s) with anyio abandon_on_cancel=True. A probe that exceeds the timeout is itself treated as fatal (reasons=['readiness_probe_timeout']) so the grace clock advances and the restart fires; abandon_on_cancel lets the timeout and shutdown cancellation return promptly instead of waiting on the stuck thread. Applied the same bound to /readyz so a hung daemon reports 503 instead of holding the request open. Adds a probe-timeout watchdog test; suite 398 passing. Co-Authored-By: Claude Opus 4.8 --- app/routers/health.py | 16 +++++++++++++--- app/settings.py | 6 ++++++ app/workers/watchdog.py | 23 +++++++++++++++++++---- tests/test_workers_watchdog.py | 21 +++++++++++++++++++-- 4 files changed, 57 insertions(+), 9 deletions(-) diff --git a/app/routers/health.py b/app/routers/health.py index 27842ddc..82158c71 100644 --- a/app/routers/health.py +++ b/app/routers/health.py @@ -1,11 +1,13 @@ from __future__ import annotations +import asyncio + import anyio from fastapi import APIRouter, Depends, Request from fastapi.responses import JSONResponse from app.auth import require_token -from app.readiness import evaluate_readiness +from app.readiness import Readiness, evaluate_readiness router = APIRouter() @@ -46,8 +48,16 @@ async def readyz(request: Request) -> JSONResponse: """ # ``evaluate_readiness`` pings docker (a blocking SDK call). Offload it so a # hung daemon can't stall the uvicorn event loop (mirrors the heartbeat - # worker's anyio.to_thread offload). - r = await anyio.to_thread.run_sync(evaluate_readiness, request.app) + # worker's anyio.to_thread offload), and bound it so a HUNG daemon reports + # fatal promptly instead of holding the request open. + timeout = request.app.state.settings.greffer_watchdog_probe_timeout + try: + r = await asyncio.wait_for( + anyio.to_thread.run_sync( + evaluate_readiness, request.app, abandon_on_cancel=True), + timeout=timeout) + except asyncio.TimeoutError: + r = Readiness(fatal=True, reasons=["readiness_probe_timeout"]) return JSONResponse( { "id": request.app.state.settings.greffer_id, diff --git a/app/settings.py b/app/settings.py index 0e4186ff..dfb2fd2a 100644 --- a/app/settings.py +++ b/app/settings.py @@ -151,6 +151,12 @@ def _heartbeat_interval_in_range(cls, v): greffer_watchdog_enabled: bool = True greffer_watchdog_interval: int = 10 greffer_watchdog_grace: int = 30 + # Upper bound on a single readiness probe so a HUNG (not just down) docker + # daemon can't block the watchdog inside the ping forever — otherwise it + # would never advance the grace clock or reach the restart for exactly the + # docker failure it exists to heal. A probe that exceeds this is itself + # treated as fatal. Keep < interval and < grace. + greffer_watchdog_probe_timeout: int = 5 # Compose log rotation for the greffon INSTANCE containers the greffer # renders (the real disk risk: an instance can log unbounded under the diff --git a/app/workers/watchdog.py b/app/workers/watchdog.py index 998f2be1..717f121a 100644 --- a/app/workers/watchdog.py +++ b/app/workers/watchdog.py @@ -23,7 +23,7 @@ import anyio from fastapi import FastAPI -from app.readiness import evaluate_readiness +from app.readiness import Readiness, evaluate_readiness from app.settings import Settings logger = logging.getLogger("greffer") @@ -45,9 +45,24 @@ async def watchdog_worker(app: FastAPI) -> None: try: while True: await asyncio.sleep(settings.greffer_watchdog_interval) - # Offload the docker-pinging evaluation so a hung daemon cannot - # block the event loop the other workers share. - readiness = await anyio.to_thread.run_sync(evaluate_readiness, app) + # Offload the docker-pinging evaluation (so a hung daemon cannot + # block the shared event loop) AND bound it: a probe that runs past + # the timeout is itself the FATAL docker-hang the watchdog exists to + # heal, so synthesize that rather than blocking here forever. + # ``abandon_on_cancel`` lets the timeout (and shutdown cancellation) + # return promptly instead of waiting on the stuck ping thread. + try: + readiness = await asyncio.wait_for( + anyio.to_thread.run_sync( + evaluate_readiness, app, abandon_on_cancel=True), + timeout=settings.greffer_watchdog_probe_timeout) + except asyncio.TimeoutError: + logger.warning( + "watchdog: readiness probe exceeded %ss (docker likely " + "hung); treating as FATAL", + settings.greffer_watchdog_probe_timeout) + readiness = Readiness( + fatal=True, reasons=["readiness_probe_timeout"]) if not readiness.fatal: if fatal_since is not None: logger.info( diff --git a/tests/test_workers_watchdog.py b/tests/test_workers_watchdog.py index af9ec555..783f56f8 100644 --- a/tests/test_workers_watchdog.py +++ b/tests/test_workers_watchdog.py @@ -19,9 +19,10 @@ WD = "app.workers.watchdog" -def _app(interval: int = 0, grace: int = 0): +def _app(interval: int = 0, grace: int = 0, probe_timeout: int = 5): return SimpleNamespace(state=SimpleNamespace(settings=SimpleNamespace( - greffer_watchdog_interval=interval, greffer_watchdog_grace=grace))) + greffer_watchdog_interval=interval, greffer_watchdog_grace=grace, + greffer_watchdog_probe_timeout=probe_timeout))) @pytest.mark.asyncio @@ -35,6 +36,22 @@ async def test_terminates_on_sustained_fatal(): term.assert_called_once() +@pytest.mark.asyncio +async def test_probe_timeout_is_fatal_and_terminates(): + # A HUNG docker ping makes the probe time out; that must itself be treated + # as fatal so the watchdog can self-heal the very docker-hang it exists for + # (codex P2 on greffer#72) — not block forever inside the probe. + async def _timeout(awaitable, *a, **k): + awaitable.close() # avoid an un-awaited-coroutine warning + raise asyncio.TimeoutError + + with patch(f"{WD}.asyncio.sleep", new=AsyncMock()), \ + patch(f"{WD}.asyncio.wait_for", new=_timeout), \ + patch(f"{WD}._terminate") as term: + await watchdog_worker(_app(grace=0)) + term.assert_called_once() + + @pytest.mark.asyncio async def test_does_not_terminate_on_degraded(): degraded = Readiness(fatal=False, reasons=["registration_pending"]) From 1aaaf8aa6fce6f65db2e8c194c973bd783eaf820 Mon Sep 17 00:00:00 2001 From: Omar Sy Date: Sun, 14 Jun 2026 20:04:39 +0200 Subject: [PATCH 6/7] fix(observability): fail-fast docker ping + tolerant log-max-file (codex P2 x2) Two more P2s from codex review on greffer#72: - Bound the docker ping at the SOURCE, not just the await. abandon_on_cancel stops waiting on the probe thread but does not stop client.ping(), and AnyIO worker threads are non-daemon, so a hung daemon left a stuck thread that keeps the process alive past the watchdog's graceful SIGTERM -> restart: unless-stopped never sees a clean exit, defeating the self-heal. Give the readiness ping its own short-timeout client (docker.from_env(timeout=4)) so the ping itself fails fast and the thread completes; the wait_for bound stays as a secondary net. - A typo in GREFFER_INSTANCE_LOG_MAX_FILE (e.g. "2x") made pydantic raise a ValidationError at startup BEFORE _inject_instance_log_rotation's fallback could apply, crashing the greffer and blocking all instance operations over an optional logging knob. Add a before-validator that coerces a malformed value to the default 3, mirroring the inject-side fallback. Suite 400 passing. Co-Authored-By: Claude Opus 4.8 --- app/readiness.py | 27 ++++++++++++++++++++++----- app/settings.py | 12 ++++++++++++ tests/test_settings.py | 18 ++++++++++++++++++ 3 files changed, 52 insertions(+), 5 deletions(-) diff --git a/app/readiness.py b/app/readiness.py index ff2f9605..05a0917b 100644 --- a/app/readiness.py +++ b/app/readiness.py @@ -29,6 +29,16 @@ # fatal here. FATAL_WORKERS = ("greffer-monitor", "greffer-crl-sync", "greffer-heartbeat") +# A short-timeout client dedicated to the readiness ping. The shared +# apps.utils.docker client uses the SDK default (~60s), so a HUNG (not down) +# daemon would leave the ping blocked. anyio's abandon_on_cancel stops WAITING +# on that thread but does not stop the ping, and the AnyIO worker threads are +# non-daemon, so a stuck ping keeps the process alive past the watchdog's +# graceful SIGTERM and `restart: unless-stopped` never sees a clean exit (codex +# P2 on greffon/greffer#72). A bounded client makes the ping itself fail fast. +_DOCKER_PING_TIMEOUT_SECONDS = 4 +_ping_client = None + @dataclass class Readiness: @@ -43,19 +53,26 @@ def status(self) -> str: def _docker_ok() -> bool: - """Ping the docker daemon. Imported lazily so unit tests run without the - docker SDK initializing its ``from_env()`` client at import (mirrors + """Ping the docker daemon with a short-timeout client so a hung daemon fails + fast (see ``_DOCKER_PING_TIMEOUT_SECONDS`` above). Imported lazily so unit + tests run without the docker SDK initializing a client at import (mirrors status_collect / the monitor).""" + global _ping_client try: - from apps.utils.docker.base import client + import docker - client.ping() + if _ping_client is None: + _ping_client = docker.from_env( + timeout=_DOCKER_PING_TIMEOUT_SECONDS) + _ping_client.ping() return True except Exception: # A readiness probe must treat ANY ping failure as "daemon unreachable" # (the docker SDK raises APIError / connection / socket errors of - # several types); logging keeps it from being a silent swallow. + # several types); logging keeps it from being a silent swallow. Drop a + # possibly-broken client so the next probe rebuilds it. logger.warning("readiness: docker ping failed", exc_info=True) + _ping_client = None return False diff --git a/app/settings.py b/app/settings.py index dfb2fd2a..24c9b734 100644 --- a/app/settings.py +++ b/app/settings.py @@ -166,6 +166,18 @@ def _heartbeat_interval_in_range(cls, v): greffer_instance_log_max_size: str = "10m" greffer_instance_log_max_file: int = 3 + @field_validator("greffer_instance_log_max_file", mode="before") + @classmethod + def _coerce_log_max_file(cls, v): + # An operator typo (e.g. GREFFER_INSTANCE_LOG_MAX_FILE=2x) must NOT crash + # the app at pydantic parse and take down ALL instance operations over an + # optional logging knob; fall back to the default (codex P2 on + # greffon/greffer#72). Mirrors _inject_instance_log_rotation's fallback. + try: + return int(v) + except (TypeError, ValueError): + return 3 + logger_name: str = "greffer" diff --git a/tests/test_settings.py b/tests/test_settings.py index 86541c81..6f32e302 100644 --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -20,6 +20,24 @@ def test_loads_greffer_id_from_env(monkeypatch: pytest.MonkeyPatch) -> None: assert s.greffer_id == "abc-123" +def test_malformed_log_max_file_falls_back_not_raises( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # A typo in this optional knob must NOT crash startup (codex P2 on #72): a + # ValidationError here would take down every instance operation. + monkeypatch.setenv("GREFFER_ID", "x") + monkeypatch.setenv("GREFFER_INSTANCE_LOG_MAX_FILE", "2x") + s = Settings() + assert s.greffer_instance_log_max_file == 3 + + +def test_valid_log_max_file_is_honored(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("GREFFER_ID", "x") + monkeypatch.setenv("GREFFER_INSTANCE_LOG_MAX_FILE", "5") + s = Settings() + assert s.greffer_instance_log_max_file == 5 + + def test_defaults_apply_when_env_unset(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setenv("GREFFER_ID", "x") s = Settings() From 70b1b0cb76bd36e21df6ff4277c6007064f08562 Mon Sep 17 00:00:00 2001 From: Omar Sy Date: Sun, 14 Jun 2026 20:12:28 +0200 Subject: [PATCH 7/7] fix(observability): treat reregister supervisor death as fatal (codex P2) I had excluded greffer-reregister from FATAL_WORKERS as "recoverable", but it is the ONLY consumer of reregister_requested. If it dies, a later heartbeat 403 clears `registered` and sets an event nobody reads, so heartbeats park forever and the greffer can't recover without a restart. Add it to FATAL_WORKERS so /readyz reports fatal and the watchdog restarts it. Adds a test. Co-Authored-By: Claude Opus 4.8 --- app/readiness.py | 15 +++++++++++---- tests/test_readiness.py | 11 +++++++++++ 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/app/readiness.py b/app/readiness.py index 05a0917b..1dc2e459 100644 --- a/app/readiness.py +++ b/app/readiness.py @@ -24,10 +24,17 @@ # Long-lived worker tasks whose death means the greffer is wedged (the loop is # gone until a restart). ``greffer-register`` is one-shot (it exits normally -# after success) and ``greffer-reregister`` is an idle supervisor (its death -# only delays a 403-driven re-register, which is recoverable), so neither is -# fatal here. -FATAL_WORKERS = ("greffer-monitor", "greffer-crl-sync", "greffer-heartbeat") +# after success), so it is excluded. ``greffer-reregister`` IS included: it is an +# idle supervisor, but it is the ONLY consumer of ``reregister_requested``, so if +# it dies a later heartbeat 403 parks heartbeats forever (the heartbeat clears +# ``registered`` and sets an event nobody reads) and the greffer cannot recover +# without a restart (codex P2 on greffon/greffer#72). +FATAL_WORKERS = ( + "greffer-monitor", + "greffer-crl-sync", + "greffer-heartbeat", + "greffer-reregister", +) # A short-timeout client dedicated to the readiness ping. The shared # apps.utils.docker client uses the SDK default (~60s), so a HUNG (not down) diff --git a/tests/test_readiness.py b/tests/test_readiness.py index ba95a17d..bdfbcea2 100644 --- a/tests/test_readiness.py +++ b/tests/test_readiness.py @@ -56,6 +56,17 @@ def test_fatal_when_long_lived_worker_dead(): assert "worker_dead:greffer-monitor" in r.reasons +def test_fatal_when_reregister_supervisor_dead(): + # A dead reregister supervisor permanently wedges 403-recovery (heartbeats + # park forever with no consumer of reregister_requested), so it is fatal + # (codex P2 on #72). + wt = {"greffer-reregister": _task(done=True)} + with patch("app.readiness._docker_ok", return_value=True): + r = evaluate_readiness(_app(registered=True, worker_tasks=wt)) + assert r.fatal + assert "worker_dead:greffer-reregister" in r.reasons + + def test_alive_long_lived_worker_not_fatal(): wt = {"greffer-heartbeat": _task(done=False)} with patch("app.readiness._docker_ok", return_value=True):