Skip to content

Harvester health watchdog (AISD-121)

An observe-only systemd service that runs on each sources-harvester instance (harvest-05 / 07 / 08), samples system health every ~20s, and on trouble pushes a structured JSON event to that instance's CloudWatch Log Group. It catches both ends of the failure spectrum: CPU spikes (box pegged) and CPU stalls (box "up but dead"), plus stuck/hung luigi tasks and pre-wedge memory/fork pressure.

The watchdog is pure stdlib plus boto3 (already a harvester dependency) -- no new packages. The runtime modules avoid f-strings so the daemon stays compatible with the older Python on the instances.

What it watches

Each ~20s sample (watchdog.py) collects, from /proc and ss:

  • overall CPU% (from /proc/stat jiffy deltas) and load average,
  • free memory and used swap (/proc/meminfo),
  • total / python / luigi process counts (/proc/<pid>/cmdline),
  • CLOSE_WAIT and ESTABLISHED socket counts (ss -tan),
  • per-process CPU% (from /proc/<pid>/stat utime+stime deltas, divided by the measured wall-clock elapsed between the two samplings -- not the nominal SAMPLE_INTERVAL -- so a slow tick does not skew the reported pcpu),
  • luigi scheduler signals (RUNNING / PENDING / DONE counts, per-task time_running, worker liveness) from http://localhost:8082,
  • cron and luigid liveness (systemctl is-active).

Detectors

Type Fires when
spike overall CPU > CPU_SPIKE_PCT for SPIKE_SUSTAIN_SAMPLES consecutive samples (debounced). Snapshots the top CPU processes by PID + sanitized argv, mapping each to its luigi task.
stuck a scheduler RUNNING task whose time_running exceeds STUCK_MINUTES (reason: long_running), or a RUNNING task whose correlated worker process sits at or below STUCK_IDLE_CPU_CEILING% CPU for STUCK_IDLE_SAMPLES consecutive samples (reason: running_idle -- the hung/backoff wedge). The worker PID is correlated via the scheduler worker list; when no PID correlation is available the task falls back to the time-based check only.
stall mean CPU over STALL_MINUTES below STALL_CPU_CEILING and no task progress (stale last-DONE, or PENDING>0 with RUNNING==0, or cron/luigid inactive), within EXPECTED_WORK_HOURS. The progress guard prevents a genuine no-work lull from raising a false stall.
health free memory below MEM_FLOOR_MB (reason: low_mem), or the OOM/fork-exhaustion precursor: used swap rising by at least HEALTH_SWAP_RISE_MB and process count climbing by at least HEALTH_PROC_RISE across the last HEALTH_TREND_SAMPLES samples (reason: swap_and_proc_rising), even when free memory is still above the floor.

Each detector is debounced per type via ALERT_COOLDOWN_SEC so one episode yields one event, not a storm.

Event schema

Every detector emits the same dict shape (secrets already masked):

{
  "type": "spike",
  "ts": 1718900000.0,
  "host": "prd-harvest-05-sources",
  "instance_id": "i-095db983d739ed4fb",
  "metrics": {
    "cpu": 99.0, "load": 8.1, "mem_free_mb": 240, "swap_used_mb": 0,
    "procs": 412, "python_procs": 30, "luigi_procs": 12,
    "close_wait": 4299, "established": 51
  },
  "offenders": [
    {"pid": 12345, "pcpu": 198.0, "task_name": "RevenueSyncWrapper", "params": ["--module", "pipes.tasks.revenue_sync", "..."]}
  ],
  "signals": {
    "running": 3, "pending": 7, "done": 120, "last_done_age_s": 42,
    "cron": true, "luigid": true
  }
}

Where events go (config-table lookup, no hardcoding)

cloudwatch_sink.py:

  1. Self-identifies via IMDS: the instance-id and the Name tag.
  2. Reads the DynamoDB config table, item config_key="targets" (region us-east-1), walks the repo -> env -> instances[] tree, and matches this host by name_tag to read its watchdog_log_group field.
  3. Creates a per-day log stream (<instance-id>-<YYYY-MM-DD>) and calls put_log_events. The resolved group is cached for the process lifetime.

The group name is therefore single-sourced from the config table -- flip the value there and the watchdog redirects with no code change. WATCHDOG_LOG_GROUP can override the lookup (handy for testing).

Fallback: on any AWS / IMDS / lookup failure -- including the group not being provisioned yet -- the sink writes the same JSON to a local mirror at /var/log/harvester-watchdog/watchdog-<YYYY-MM-DD>.jsonl and keeps running. It never raises into the sample loop.

Secret safety

sanitize.py masks secret-ish keys (client_secret, client_id, token, password, secret, api_key, access_key, ...) out of any argv or JSON before it leaves the process. Provider account payloads carried in luigi task argv contain plaintext client_secret / client_id; these are redacted in both the CloudWatch record and the local mirror.

Configuration (env-overridable defaults)

All thresholds live in config.py and are overridable via env vars of the same name (set them in the systemd unit's Environment= if you need to retune without a deploy):

Var Default Meaning
SAMPLE_INTERVAL 20 seconds between samples
CPU_SPIKE_PCT 95 spike CPU% threshold
SPIKE_SUSTAIN_SAMPLES 6 consecutive over-threshold samples (~2m) before a spike
STUCK_MINUTES 45 RUNNING-task age (minutes) that counts as stuck (long_running)
STUCK_IDLE_CPU_CEILING 1 per-process CPU% at or below which a worker counts as idle for the running_idle cross-check
STUCK_IDLE_SAMPLES 6 consecutive idle samples a RUNNING task's worker must show before running_idle fires
STALL_CPU_CEILING 5 CPU% below which the box is considered idle
STALL_MINUTES 20 idle window for a stall
EXPECTED_WORK_HOURS all all or a CSV of UTC hours the stall detector is active in
MEM_FLOOR_MB 512 free-memory floor for a low_mem health event
HEALTH_TREND_SAMPLES 6 window length (samples) for the swap/proc-growth precursor
HEALTH_SWAP_RISE_MB 64 minimum swap growth (MB) over the trend window to count as "rising"
HEALTH_PROC_RISE 20 minimum process-count growth over the trend window to count as "climbing"
ALERT_COOLDOWN_SEC 600 per-type debounce window
WATCHDOG_LOG_GROUP (unset) override the config-table log-group lookup
WATCHDOG_CONFIG_TABLE / WATCHDOG_CONFIG_KEY config / targets config-table coordinates
WATCHDOG_AWS_REGION us-east-1 region for DynamoDB + Logs
WATCHDOG_LOCAL_DIR /var/log/harvester-watchdog local mirror directory

Deploy + lifecycle

  • The systemd unit is watchdogs/harvester-watchdog.service (Restart=always, runs env/bin/python -m watchdogs.watchdog from /srv/skynet-sources-harvester as root).
  • watchdogs/install_watchdog.sh installs the unit, daemon-reloads, enable --nows (so it survives reboots), restarts it to pick up new code, and verifies systemctl is-active. It is idempotent.
  • The CodeDeploy AfterInstall hook (scripts/after_install) calls install_watchdog.sh and logs the result. It is intentionally non-fatal: if CloudWatch / IAM is not provisioned yet, the watchdog still runs and mirrors locally, so the deploy is never blocked on unprovisioned AWS resources.

AWS / IaC dependency (companion hq PR)

The CloudWatch Log Groups, retention, least-privilege IAM (logs:CreateLogStream + logs:PutLogEvents on the groups, dynamodb:GetItem on the config table), and the per-type metric filters + alarms wired to the existing SNS/Slack topic are provisioned by a separate IaC PR in the hq repository. That PR also writes each watchdog_log_group value into the config table targets item (the single source of truth this code reads).

Until that PR lands, the harvester change degrades gracefully: the watchdog runs and writes to the local mirror, and the deploy hook does not fail.

Tests

watchdogs/tests/ (pure stdlib + unittest, run via pytest like the rest of the repo):

  • test_metrics.py -- CPU% from synthetic /proc/stat deltas; meminfo derivations.
  • test_luigi_parser.py -- argv -> luigi-task parsing on real CampaignSync / RevenueSync argv shapes, including secret masking.
  • test_sanitize.py -- masks client_secret / client_id / token / password in a sample Taboola account JSON and in argv.
  • test_detectors.py -- detector trigger logic (spike only after N sustained; stall does NOT fire when DONE is recent; stuck fires past threshold) + debounce.
  • test_cloudwatch_sink.py -- boto3 mocked: resolves the group from the config table and puts to CloudWatch; asserts local-mirror fallback on lookup failure and that the sink never raises.

Run: env/bin/python -m pytest watchdogs/tests/ -q.