Sub topic 11
Alerting on failure and on silence
A scheduled agent job fails in two ways. It can run and report a problem, or it can fail to run at all. This chapter covers how to detect both. It assumes you already have a wrapper script that applies a timeout and returns a meaningful exit status, and that it writes logs to a known path. It also assumes you can read a short shell script and have a webhook or email destination to send alerts to.
Two kinds of failure
A failure alert answers the question "did the run go wrong?" The wrapper script sees a non-zero exit status, so it can send a message at that moment.
A silence alert answers the question "did the run happen at all?" If the machine is down, the crontab was overwritten, or the timer was never enabled, no code runs, so nothing can send a failure message. The job's absence is the problem, and only an outside observer can notice it.
| Problem | Failure alert catches it | Silence alert catches it |
|---|---|---|
| Agent exits non-zero | Yes | Yes, if the success ping is skipped |
| Agent hits the timeout (status 124) | Yes | Yes |
| Output fails validation | Yes | Yes |
| Host is powered off | No | Yes |
| Timer or crontab entry removed | No | Yes |
| Every run skipped by the lock | No, skips exit 0 | Yes |
| The alert channel itself is broken | No | Partly, if the monitor uses a different channel |
You need both. Failure alerts give fast, specific detail. Silence alerts cover the cases where the script never got to speak.
Alerting from the wrapper script
Put the notification logic in its own small script, so the wrapper, systemd, and CI can all call it. Build the JSON payload with jq instead of string concatenation. A log line containing a double quote would otherwise break the payload.
#!/usr/bin/env bash
# notify.sh SUBJECT [DETAIL]
# Sends one message to a chat webhook. ALERT_WEBHOOK_URL comes from the environment.
set -u
: "${ALERT_WEBHOOK_URL:?set ALERT_WEBHOOK_URL}"
subject="${1:?usage: notify.sh SUBJECT [DETAIL]}"
detail="${2:-}"
payload=$(jq -n --arg text "$subject
$detail" '{text: $text}')
curl -fsS -m 10 --retry 2 \
-H 'Content-Type: application/json' \
-d "$payload" "$ALERT_WEBHOOK_URL" > /dev/null \
|| echo "alert delivery failed: $subject" >&2The payload field name (text here) depends on your chat service, so check its documentation. The script uses -m 10 so a hung network connection cannot stall the job. If delivery fails, it prints to stderr and does not change the wrapper's exit status. The agent's result matters more than the messenger's.
Now extend the end of the wrapper from the earlier chapter. After status=$? and the timeout check, replace the final exit with this:
HOST="$(hostname -s)"
if [ "$status" -eq 0 ]; then
# Success: tell the external monitor we are alive.
curl -fsS -m 10 --retry 3 "${HEARTBEAT_URL:?set HEARTBEAT_URL}" > /dev/null \
|| echo "heartbeat ping failed" >&2
else
"$HOME/bin/notify.sh" \
"nightly-agent FAILED on $HOST (status $status)" \
"log: $LOG"
fi
exit "$status"The success ping is sent only when the run succeeds, and the failure message is sent only when it does not. Because a failed run never pings, the monitor's deadline will also expire and raise a silence alert. That second alert is redundant but harmless, and it protects you if the failure message itself is lost.
What goes in the message
A good alert lets someone decide in ten seconds whether to act. Include:
- The job name and host, since you may run several jobs.
- The exit status, with 124 labelled as a timeout.
- The log file path, so the reader can go straight to the details.
- A UTC timestamp, so there is no time-zone ambiguity.
Send the path to the log and not the log contents. Agent logs can contain file contents, command output, and text taken from untrusted sources. Pasting them into a chat channel can leak secrets and puts attacker-controlled text in front of people. If you must include a snippet, keep it to the last few lines and treat it as untrusted.
Detecting silence with a heartbeat
A heartbeat monitor (also called a dead man's switch) is an external service that expects a request to a unique URL on a schedule. If no request arrives within the expected period plus a grace time, it alerts you. Hosted services of this kind exist, and you can also build one with a small always-on service on a different machine. What matters is that the monitor runs somewhere other than the job's host and does not depend on the scheduler.
Set the monitor's schedule to match the job's schedule, not just "every 24 hours". For a weekday 02:00 job, use the monitor's cron-style schedule support if it has one. Otherwise set a period long enough to cover a weekend, and accept slower detection on Mondays.
Set the grace time from observed run durations. If the job normally takes 8 minutes and has a 20-minute timeout, a grace time of 30 minutes means the monitor will not alert while a slow run is still in progress.
Do not send a heartbeat when the lock causes a skip. A skipped run did no work. If every run is skipped because a stuck process holds the lock, the missing heartbeats are exactly the signal you want.
Scheduler-level hooks
Each scheduler has its own way to react to failure, and it works even if your wrapper script crashes before it can notify.
With cron, set MAILTO in the crontab. Cron mails any output a job produces. This only works if the host has a working mail transfer agent, which many servers do not, so verify delivery before relying on it.
With systemd, OnFailure= starts another unit when a service enters the failed state:
# /etc/systemd/system/nightly-agent.service (add to the [Unit] section)
[Unit]
Description=Nightly coding agent run
OnFailure=nightly-agent-alert@%n.service
# /etc/systemd/system/[email protected]
[Unit]
Description=Alert for failed unit %i
[Service]
Type=oneshot
EnvironmentFile=/etc/nightly-agent.env
ExecStart=/home/deploy/bin/notify.sh "systemd unit failed: %i" "run: journalctl -u %i"The %n in the first file expands to the failing unit's name, and %i in the template unit receives it. This catches failures the wrapper cannot report, such as the service exceeding TimeoutStartSec and being killed.
With CI schedules, use the platform's workflow failure notifications, or add a final step that runs only on failure (if: failure() in GitHub Actions) and calls notify.sh. CI platforms may disable scheduled workflows in repositories with no recent activity, which is a silence failure. A heartbeat monitor catches it.
Failures that exit 0
Exit status is not enough. An agent can exit 0 after doing nothing useful, for example when it could not reach a service and wrote a polite explanation. If you asked for structured output, validate it before the success ping:
if ! jq -e '.status == "ok" and (.changed_files | type == "array")' result.json > /dev/null; then
"$HOME/bin/notify.sh" "nightly-agent output invalid on $(hostname -s)" "file: $PWD/result.json"
exit 1
fiPlace this check before the heartbeat, so a run with malformed output counts as a failure and also triggers a silence alert if you miss the message.
Keeping alerts useful
Alerts that fire constantly get ignored. A few habits help:
- Alert once per failed run, not once per retry attempt. Send the message after the final attempt.
- Do not alert on expected skips. Track them in a log and let the heartbeat catch a long streak.
- Use a dedicated channel for job alerts so humans can scan it quickly.
- Test the alert path itself. Every few months, make a job fail on purpose and confirm the message arrives.
Exercise
Your nightly job runs on a server that is rebooted for maintenance and, by mistake, the cron daemon is never re-enabled. The wrapper script sends a message on every non-zero exit. Why will you receive no failure alert, and what single addition would tell you the job stopped running?
Show answer
The wrapper never starts, so no code exists to detect a failure or send a message. Add a heartbeat monitor on a separate system. The wrapper pings its URL after each successful run, and the monitor sends a silence alert when no ping arrives within the expected period plus a grace time.
Exercise
A run exits with status 0, but result.json contains {"status": "error", "changed_files": []}. Using only what this chapter covers, where in the wrapper do you catch this, and should the heartbeat be sent?
Show answer
Run the jq -e validation after the agent finishes and before the heartbeat ping. The check fails because status is not "ok", so the script sends a failure alert and exits non-zero. The heartbeat is not sent, because the run did not succeed in the sense you care about.