how-to deployer

Sentinel Runbook

Symptom you’re chasing: a country deployment (or the sandbox) is unhealthy — disk filling, /health failing, or the database unreachable — and nobody noticed until an applicant complained. Sentinel exists to close that gap: a small watchdog on each deployment that files a GitHub issue in the factory the moment a probe goes unhealthy, so the resonance daemon can pick it up like any other work item.

Naming note — do not confuse the two “sentinel” words in this repo:

  • Sentinel (this document) = the deployment watchdog described here: a probe container (sentinel/) plus a relay service (relay/) that turns probe failures into GitHub issues.
  • “sentinel matcher” = an unrelated backlog term for a text-matching pattern elsewhere in the factory’s issue-triage vocabulary. If you see “sentinel” in a triage or matcher context, it is almost certainly that — not this watchdog.

1. What leaves the deployment

There are two separate switches, with deliberately opposite defaults. Read this section before answering a ministry that asks what OpenGov sends home.

SwitchDefaultWhat it sends
Problem reporting (OPENGOV_SENTINEL_EGRESS_ENABLED)offWhat broke, and which probe saw it
The liveness ping (OPENGOV_SENTINEL_HEARTBEAT_EGRESS_ENABLED)onOnly that this deployment exists and is running

The liveness ping is one hourly message containing the deployment’s identifier, which version of the watchdog it runs, a counter and a timestamp. That is the entire payload — sentinel/runner.py::build_heartbeat sends empty params, so it carries nothing about what the deployment saw, nothing about any agency, and nothing about any applicant or application.

It is on by default because silence is the signal. If a country’s site dies at 02:00, the pings stop, and a gap is what the weekly fleet digest reads as “this deployment went dark”. Turning it on costs a country no information about itself; leaving it off means nobody outside the machine can tell a working deployment from one that was never started.

Both switches are inert if OPENGOV_SENTINEL_RELAY_URL is unset — there is nowhere to send. To make a deployment emit nothing whatsoever, set OPENGOV_SENTINEL_HEARTBEAT_EGRESS_ENABLED=false; the watchdog still probes and still records locally, and UNREPORTED.txt still appears beside the spool when it notices something it cannot report.

A gap in the ping sequence is expected, not an alarm. When problem reporting is off, an incident consumes a sequence number that is never delivered, so the relay records a gap. That is the wire-level equivalent of UNREPORTED.txt: it says this deployment generated something it was not permitted to send. Do not “fix” it by renumbering.

When problem reporting is also enabled, the additional things that leave are:

  • Typed, validated probe parameters — each probe (health_contract, disk_inode, service_reachability, tls_expiry, see sentinel/events.py:PROBE_IDS) has its own param schema; validate_params (relay-side) enforces a per-probe regex charset allowlist and rejects control characters/newlines before anything is rendered into an issue title or body.
  • Edge-redacted — sentinel scrubs named PII at the probe/spool boundary (sentinel/redact.py) before an event is ever written to spool or sent, so raw log lines or file contents never leave the deployment.
  • Rendered against a fixed, published template catalog — relay/templates.py is the sole source of issue titles/bodies. The relay owns content authority: it re-renders from the typed params server-side and rejects any event whose reported title/body doesn’t match, so a compromised or buggy sentinel cannot inject arbitrary issue text (U5).

Nothing else — no host paths, no raw environment, no arbitrary strings — reaches the relay or GitHub.


2. Operator controls

  • Problem reporting is off by default. Fresh installs ship with OPENGOV_SENTINEL_EGRESS_ENABLED=false in docker-compose.yml’s sentinel: service. In this mode probes still run and write to the local spool, but no detail of what happened is POSTed anywhere. The liveness ping still goes out (§1) unless it too is switched off.
  • The boot log says which of the three states you are in — full reporting, liveness-only, or fully silent — in plain words, once, at startup. If you are unsure what a deployment is sending, read the first two lines of docker compose logs sentinel; do not infer it from the flags.
  • Per-probe toggles. SentinelConfig.probe_enabled (a dict[str, bool], default all-on) lets an operator disable an individual probe id (health_contract / disk_inode / service_reachability / tls_expiry) without touching the others — sentinel/runner.py checks cfg.probe_enabled.get(probe_id, True) before running it each cycle.
  • tls_expiry needs the public hostname. Set OPENGOV_SENTINEL_TLS_HOST to the deployment’s public https hostname (the cert applicants actually hit) — empty leaves the probe unmeasured (never a false OK). OPENGOV_SENTINEL_TLS_WARN_DAYS (default 14) is the expiry heads-up threshold. The probe reports only days_remaining / port / a coarse failure token — never the hostname, which identifies the country.
  • Enabling egress: flip OPENGOV_SENTINEL_EGRESS_ENABLED=true (and provide a signing key — see §3) for the deployment’s sentinel service, then redeploy.
  • The sentinel: compose service (docker-compose.yml) builds from sentinel/Dockerfile, has restart: unless-stopped, and mounts:
    • sentinel-spool:/var/lib/sentinel — the NDJSON spool (bounded, oldest-dropped).
    • /var/log:/host:ro — narrow, read-only. disk_inode only needs a mount on the filesystem that actually fills; /var/log suffices via statvfs, so the whole root filesystem is deliberately not mounted (would expose other tenants' world-readable files for zero benefit).
    • /var/lib/opengov:/var/lib/opengov:ro — read-only, for the deploy window marker below.
  • Deploy window (OPENGOV_SENTINEL_DEPLOY_MARKER_PATH). When a file at this path contains {"until": <epoch>} and that time is still in the future, the app-availability probes (health_contract, service_reachability, tls_expiry) report unmeasured — the watchdog stays quiet while the stack is down for a deploy it already knows about, instead of filing one issue per rebuild (issue #1452; spec docs/specs/2026-08-16-sentinel-deploy-window.md). The marker is written by the deploy driver (scripts/coolify_stamp.sh) and expires on its own: a site still down after the window is reported normally, and a missing or corrupt marker never suppresses anything. docker-compose.yml wires the path and the mount; empty disables the feature, which is the right default for a country deployment whose deploys this driver never touches. disk_inode is never suppressed — a full disk during a deploy is still reported.
  • Resource caps: the service is capped at 128M memory / 0.25 CPU — Sentinel is a watchdog, not a workload, and must never compete with the app it’s watching.
  • No depends_on on the app services — Sentinel must keep probing (and reporting) even while the thing it watches is down.

3. Key ceremony (Ed25519 signing key)

Every spooled event is signed so the relay can verify it came from a real deployment.

The ceremony is now performed by scripts/generate_secrets.py — run on the operator’s trusted machine during onboarding (never on the deployment host, never in CI). It mints the Ed25519 keypair and:

  1. Private key → enters deployments/<code>/secrets.env as OPENGOV_SENTINEL_SIGNING_KEY, stored as single-line base64 of the PKCS8 PEM (a raw multi-line PEM cannot survive a dotenv/host-env-file line). The _SIGNING_KEY suffix auto-classifies it KEK-tier (secrets.py), so it is excluded from anything pushed to Coolify and must be injected out-of-band. The script prints only the key NAME, not the value — read the base64 value with sops -d deployments/<code>/secrets.env on the trusted machine and inject it verbatim (do not re-wrap or decode it); sentinel/config.py::load_signing_key decodes it, and sentinel/__main__ validates it once at startup (a garbage value is refused loudly, not silently non-delivered).
    • Rollout ordering: the deployment’s sentinel image must already contain this base64 decode (this change). Countries do not auto-pull, so against an OLDER image inject a raw PEM via OPENGOV_SENTINEL_SIGNING_KEY_PATH (or the raw-PEM env value) instead — a base64 value on an old image is treated as raw key bytes and every sign fails. (A value that still starts -----BEGIN is accepted raw.)
    • Fallback: OPENGOV_SENTINEL_SIGNING_KEY_PATH points at a mounted key file.
    • If neither is present, load_signing_key() returns b"" and Sentinel stays observe-only — deliberate fail-safe, not a bug.
  2. Public key → written to deployments/<code>/sentinel.pub.pem, a non-secret, committed artifact. It is the relay trust anchor (registered per §3b). The script also prints the fingerprint — record it; you cross-check it at register time.
  3. Never commit the private key. A pre-commit guard blocks any private-key PEM; only sentinel.pub.pem (a BEGIN PUBLIC KEY) is committable. The deployment_id the relay knows the key by is the code (compose defaults OPENGOV_SENTINEL_DEPLOYMENT_ID to it) — it must match ^[a-z0-9][a-z0-9-]{0,31}$ (validate_deployment.py fails an over-length code before it can be onboarded).

For a targeted rotation (a new signing key without re-rolling the encryption key), mint by hand — see §3c. The primitive is still sentinel/sign.py::generate_keypair (its twin opengov.platform.deployments.sentinel_key.mint_keypair is what generate_secrets.py calls).


3c. Targeted rotation (new signing key, same encryption key)

To rotate only the Sentinel signing key — without re-rolling OPENGOV_ENCRYPTION_KEY (which would orphan all encrypted data) — do NOT re-run generate_secrets.py. Rotate the single key:

# 1. mint a fresh keypair on the trusted machine
python -c "from opengov.platform.deployments.sentinel_key import mint_keypair, encode_private_key_env, fingerprint; \
priv, pub = mint_keypair(); open('deployments/<code>/sentinel.pub.pem','wb').write(pub); \
print('ENV_VALUE', encode_private_key_env(priv)); print('FINGERPRINT', fingerprint(pub))"
# 2. sops-edit secrets.env, replace ONLY OPENGOV_SENTINEL_SIGNING_KEY with the base64 ENV_VALUE
sops deployments/<code>/secrets.env
# 3. commit the new sentinel.pub.pem (+ encrypted secrets.env), open a PR, merge
# 4. relay-first: register the new FINGERPRINT on the relay, THEN swap the edge key + redeploy

Sequence relay-first (as §3b/§5 note): a single key per id, so an event signed by whichever side hasn’t switched is rejected until both match.


4e. Keeping a flapping condition from spamming one issue (#2479/#2245)

Three settings stop the watchdog from talking on every reading and refreshing one GitHub issue forever — the cause of #2479’s 53 comments, alternating “still active”/“recovered” one to three minutes apart:

  • Speak after N failures, go quiet after M successes (sentinel-side). sentinel/runner.py::decide reports a condition ACTIVE only after OPENGOV_SENTINEL_INCIDENT_THRESHOLD (default 3) consecutive unhealthy readings, and RECOVERED only after OPENGOV_SENTINEL_RECOVERY_THRESHOLD (default 2) consecutive healthy readings — a relapse mid-recovery resets the healthy count to zero, so it takes a fresh run of passes, not “one more”. Every probe (service_reachability, health_contract, disk_inode, tls_expiry) goes through this one shared debounce via run_cycle; each probe still records what it actually saw each cycle (prev_state), only what gets REPORTED to the relay is gated.
  • Refresh cadence (relay-side) — throttles REPEATS, not TRANSITIONS. A state change always posts: a condition recovering, or a condition going active again after having recovered, is news and posts every time. Only a same-state repeat — “still active” after “still active”, nothing changed — is throttled, to at most once per OPENGOV_RELAY_REFRESH_INTERVAL_S (default 6 hours) per fingerprint; an ingest in between a repeat and its next due refresh updates nothing on GitHub. The cadence baseline is set at filing time too, so the very next ingest after a fresh issue is filed does not immediately post a redundant refresh.
  • Flap cap (relay-side). If a fingerprint swings active→recovered→active more than OPENGOV_RELAY_FLAP_CYCLE_LIMIT (default 3) times inside OPENGOV_RELAY_FLAP_WINDOW_S (default 24 hours), the relay posts ONE plain-language notice, labels the issue watchdog:flapping, and then posts nothing further for that fingerprint — no refreshes, no reactivation posts, no recovery comments, and (§4b) no Telegram all-clear either — until a person closes the issue. Closing resets both the cadence and the flap history, so a later recurrence gets a fresh issue with a clean slate. Auto-close is still OFF (U8) — this never closes an issue itself.

All six env vars are optional; unset, every default above applies. They are read once, at process import — a changed value needs the sentinel-side container restart for the two OPENGOV_SENTINEL_* ones to take effect.


6. The Coolify sandbox step (recreate, not just redeploy)

Coolify caches the parsed compose at app-creation time. Because the sentinel: service is a new block added to docker-compose.yml, a plain redeploy is not enough — the app must be recreated so Coolify re-parses the compose file. This is documented and required behavior, not a workaround: see docs/reference/deployment-architecture.md:147.

Steps, in order, whenever the compose file changes:

  1. Recreate the Coolify app (not just redeploy).
  2. Re-set the domains (docker_compose_domains) — domains set before the first deploy don’t persist because the compose-parse step nulls them. Set them after the first deploy completes, then redeploy once more.
  3. Confirm the sentinel container is up and logging egress=False (observe-only) before flipping anything on.

7. Known S1 limits

Sentinel’s first shipped scope (S1, sandbox MVP) has known, deliberate gaps — documented here rather than silently implied as “done”:

  • Recovery is comment-only. When a probe recovers, the relay posts a recovery comment on the open issue but does not close it (U8) — closing is a human action. The fingerprint→issue map now has a lifecycle (S2): the weekly digest reconciles it against the live gh open list and clears entries whose issue a human closed, so a recurrence of the same fault files a FRESH issue instead of commenting on the closed one — with up to a week of lag between the human close and the reconcile (a recurrence inside that window still comments on the closed issue). When gh is unavailable nothing is cleared — a blind clear would re-file duplicates of still-open issues.
  • service_reachability only covers postgres-TCP and app-/health. Worker-lag and OIDC/Keycloak reachability legs are explicitly deferred to S2 — an unhealthy worker queue or a broken OIDC leg will not currently trigger a Sentinel event.
  • No storm aggregation. If many probes fail near-simultaneously (e.g. a disk-full event trips multiple deployments at once), each files independently — aggregation is gated on the second country onboarding (C4), not built in S1.
  • No ledger/approval-gate. There is no cost ledger or human approval step in front of issue filing in S1 — that gate is scoped to the first country rollout (C5), not the sandbox pilot.
  • consecutive_failures does not accumulate across cycles in S1. Because the edge only emits on a health transition (not every failing cycle), a service_reachability incident always reports consecutive_failures=1 at the instant of detection; the per-service running streak is not threaded through run_cycle state yet. The value shown is correct-at-detection, not a live streak — wiring the running count is deferred to S2.

Sandbox pilot — evidence

Evidence from the live sandbox pilot (Task 22) is recorded here once run. Until then, this section is empty by design — S1’s acceptance is observable sandbox behavior, not a written claim (CLAUDE.md Rule 5).