Repository navigation
feat(observability): greffer self-health — /readyz + watchdog + log rotation - #72
Conversation
…otation 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 <noreply@anthropic.com>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: aa83840f43
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| # 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: |
There was a problem hiding this comment.
Mirror compose additions in the CLI template
When greffers are installed via greffer up, the compose file is rendered from cli/greffer_cli/templates/compose.yml; I checked that template and it still lacks both the new /readyz healthcheck and the new x-logging/logging blocks added here. As a result, published-image/operator deployments keep running without the compose health visibility and own-service log caps promised by this change, while only source-tree compose users get them.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. Added the x-logging anchor + per-service logging and the /readyz healthcheck to cli/greffer_cli/templates/compose.yml so greffer up (published-image) deployments get the same health visibility and own-service log caps as the source-tree compose. Both files validate.
| t=open(os.path.join(os.getenv('GREFFON_PATH','/data'), | ||
| '.greffer-token')).read().strip(); |
There was a problem hiding this comment.
Honor explicit tokens in the healthcheck
In deployments that set GREFFER_TOKEN (or when token persistence falls back to the in-memory token), create_app uses that token and does not write it to .greffer-token, but this healthcheck always authenticates with the file contents. Those otherwise-supported deployments will report the greffer as unhealthy forever because /readyz rejects the stale/missing file token; the command should prefer GREFFER_TOKEN before reading the persisted token.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. The healthcheck now resolves the token the way create_app does (resolve_token = settings.greffer_token i.e. GREFFER_TOKEN env, else the persisted file) rather than always reading .greffer-token. So a GREFFER_TOKEN-set (or in-memory-token) deployment authenticates correctly instead of being reported unhealthy forever. Applied to both docker-compose.yml and the CLI template; a missing token (no env + no file) still exits 0.
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
…nor 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 <noreply@anthropic.com>
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 18346fc875
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| 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) |
There was a problem hiding this comment.
Bound the watchdog readiness probe
When the Docker daemon/socket hangs instead of failing fast, evaluate_readiness() can block inside the Docker ping for the client's full blocking wait or longer. Because the watchdog awaits this call without any timeout or abandon_on_cancel, it never advances fatal_since or reaches _terminate() for exactly the Docker failure mode it is supposed to self-heal, and shutdown cancellation can also be held behind the same call. Wrap this evaluation in a bounded timeout and abandon it on cancellation before applying the grace window.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. Wrapped the probe in asyncio.wait_for(timeout=greffer_watchdog_probe_timeout) (default 5s) with anyio abandon_on_cancel=True. A probe that exceeds the timeout is now itself fatal (reasons=["readiness_probe_timeout"]), so a hung docker daemon advances the grace clock and triggers the restart instead of blocking the watchdog forever, and abandon_on_cancel lets the timeout (and shutdown cancellation) return promptly rather than waiting on the stuck ping thread. Applied the same bound to /readyz (503 instead of a hung request). Added a probe-timeout test.
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 <noreply@anthropic.com>
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 540e3aeebd
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| anyio.to_thread.run_sync( | ||
| evaluate_readiness, app, abandon_on_cancel=True), | ||
| timeout=settings.greffer_watchdog_probe_timeout) |
There was a problem hiding this comment.
Bound the Docker ping instead of abandoning it
In the hung-Docker case this path times out by cancelling run_sync, but abandon_on_cancel=True does not stop client.ping(); it leaves the AnyIO worker thread blocked. Because _terminate() later sends a graceful SIGTERM rather than killing the process, those stuck non-daemon threads can keep the PID alive, so Docker's restart: unless-stopped never gets a clean process exit for the exact failure this watchdog is meant to heal. Put a real timeout on the Docker ping or run the probe in something killable before treating the timeout as self-healed.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Good catch — abandon_on_cancel stops waiting on the thread but not client.ping(), and AnyIO worker threads are non-daemon, so a stuck ping would keep the PID alive past the graceful SIGTERM. Fixed at the source: the readiness ping now uses its own short-timeout client (docker.from_env(timeout=4)) so the ping itself fails fast and the thread completes, letting graceful SIGTERM produce a clean exit for restart:unless-stopped. The wait_for bound stays as a secondary net.
| # 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 |
There was a problem hiding this comment.
Keep malformed log-rotation count from aborting startup
When an operator mistypes GREFFER_INSTANCE_LOG_MAX_FILE (for example 2x), pydantic parses this new Settings field before the app boots and raises a validation error. That bypasses the fallback in _inject_instance_log_rotation() that was meant to default malformed values to 3, so an optional logging knob can crash the greffer and prevent all instance operations. Make this field tolerant/string or add a validator with the same fallback.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. Added a field_validator(mode="before") on greffer_instance_log_max_file that coerces a malformed value (e.g. 2x) to the default 3, so pydantic no longer raises at startup and an optional logging knob cannot crash the greffer / block instance operations. Mirrors the inject-side fallback; added tests.
…dex 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 <noreply@anthropic.com>
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1aaaf8aa6f
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| # 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") |
There was a problem hiding this comment.
Treat reregister supervisor death as fatal
If the greffer-reregister task ever exits, the greffer can still become permanently stuck: on a later heartbeat 403, heartbeat_worker clears registered and sets reregister_requested, but with no live supervisor consuming that event, heartbeats stay parked until the process restarts. Because this fatal-worker list excludes greffer-reregister, /readyz remains non-fatal and the watchdog never performs the restart that would recover the supervisor.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed, and it overrides my earlier call. Added greffer-reregister to FATAL_WORKERS: since it is the only consumer of reregister_requested, its death permanently wedges 403-recovery (heartbeats park with registered cleared and nobody to re-register), so /readyz now reports fatal and the watchdog restarts it. Added a test.
… 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 <noreply@anthropic.com>
|
@codex review |
|
Codex Review: Didn't find any major issues. Already looking forward to the next diff. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Feature #3 of the greffer-observability epic (epic.md). Three pieces in one PR:
/readyz — 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, must not be flapped). Auth viaX-GREFFON-TOKEN./healthzunchanged (greffer-cli contract).In-process watchdog — plain
docker composedoes 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) andrestart: unless-stoppedrecovers it. On by default; safety is in the logic (only-fatal, grace window, never on degraded). The compose healthcheck targets/readyzfor visibility only.Compose log rotation — json-file max-size/max-file on the greffer's own services + injected into every rendered greffon INSTANCE compose (the real disk risk), unless the catalog author set their own
logging.Tests: 18 new (readiness / watchdog / readyz / log-rotation), full suite 395 passing, compose config validates. Watchdog defaults per maintainer call (on by default).