Your Jenkins backup job ends in Finished: SUCCESS every night. Then someone finally reads the output and finds mysqldump: Couldn't execute 'SHOW FUNCTION STATUS WHERE Db = '...'': Cannot load from mysql.proc. The table is probably corrupted (1728), or Host key verification failed, followed by a line that says the step was “complete”. That was my job. The cause was a script that never checked an exit code, built on ssh host "mysqldump ..." | gzip > file.sql.gz, a pipeline whose exit status is gzip’s and not mysqldump’s.

This is for anyone who owns a scheduled database backup they did not write. You will end up with a bash backup script that fails loudly when any dump fails, a heartbeat that alerts when the job does not run at all, a scheduled restore test into a throwaway database, and the steps to repair a corrupt mysql.proc table without making things worse. It assumes you can read a shell script and have SSH access to the database server and the backup host.

Last verified: December 2026. Versions used: GNU bash 5.2 (scripts tested on Ubuntu 24.04 with stand-in commands, not against a live database), MariaDB documentation for the current 11.x series, Jenkins Publish Over SSH plugin 409.v73ca_23a_5b_48e, Healthchecks.io HTTP API.

What Happened

A Jenkins job used the Publish Over SSH plugin’s “Send files or execute commands over SSH” step to run a backup script on a backup host. Its console showed SSH: EXEC: completed after 712,690 ms, then Finished: SUCCESS. Not one line from the script in twelve minutes.

The script was itself a reconstruction: its header said it had been rebuilt from two Jenkins run logs in May 2026. Reading it explained everything:

  • It had set -u but no pipefail, and nothing checked an exit code.
  • exec >> "${LOG_FILE}" 2>&1 near the top sent all output to a file on the backup host, so the Jenkins console never saw any of it.
  • Each helper printed “… complete” unconditionally after its rsync or dump.
  • Database dumps ran as ssh host "mysqldump --single-transaction --quick --routines --triggers <db>" | gzip > <db>.sql.gz.

The first failures that surfaced were Host key verification failed followed by rsync error: unexplained error (code 255) on several hosts, each one followed by the script’s own “complete” line. I added the hosts’ keys to known_hosts with ssh-keyscan -H and confirmed each with ssh -o BatchMode=yes <host> hostname in a loop.

Then I rewrote the helpers: set -o pipefail, an exit check on every rsync and dump, a FAILURES counter, gzip -t and [ -s file ] on each archive, and exit 1 at the end if anything failed. I also changed the logging line to exec > >(tee -a "${LOG_FILE}") 2>&1 so output went to both the log file and Jenkins.

The next run showed what had been hiding:

Copied!
mysqldump: Got error: 1049: "Unknown database '<old_name>'" when selecting the database
mysqldump: Couldn't execute 'SHOW FUNCTION STATUS WHERE Db = '<db>'': Cannot load from mysql.proc. The table is probably corrupted (1728)

The first was a database name in the script that did not exist on the server; I replaced it with the one that did. The second hit every dump on one MariaDB server, four databases once the name was fixed. One of those dumps ran for about four minutes before failing, because mysqldump writes table data first and asks for stored routines last. My first reaction was “we never had this problem before.” We had. The old script simply never said so. I had even seen error 1728 before, when it stopped a schema deployment script at a DROP PROCEDURE statement in December 2025.

I checked whether those databases had any stored routines, then repaired the table with mysqlcheck --repair mysql proc. The next run was clean: every target completed, the script exited 0, and Jenkins reported SUCCESS after about 17 minutes. That was the first SUCCESS that meant anything. How long the corrupt table had been there I can’t say.

Two things were left open that day: proving the dumps restore, and working out how far back the gaps went. My final script also stopped at gzip -t plus [ -s ], which prove less than they look like they do. The steps below go further than what I ran that day, because a backup that is not verified is a hope.

How It Works

A pipeline’s exit status is the last command’s

The bash manual says it directly: the exit status of a pipeline is the exit status of the last command in it, unless pipefail is enabled. In mysqldump db | gzip > db.sql.gz the last command is gzip. gzip read whatever arrived on its input, compressed it, wrote a file and exited 0. The dump’s exit status 2 was thrown away.

You can see both numbers in PIPESTATUS, an array bash fills with the exit status of every command in the most recent foreground pipeline:

Copied!
fake_dump() { printf 'CREATE TABLE t (id int);\n'; return 2; }
fake_dump | gzip > a.sql.gz; echo "exit=$?"
fake_dump | gzip > a.sql.gz; echo "PIPESTATUS=${PIPESTATUS[*]}"
set -o pipefail
fake_dump | gzip > a.sql.gz; echo "exit=$?"
Copied!
exit=0
PIPESTATUS=2 0
exit=2

With pipefail on, the pipeline returns the status of the rightmost command that exited non-zero, or zero if all succeeded. ssh cooperates: it exits with the remote command’s exit status, or 255 if ssh itself failed, so a failed remote dump or a refused host key both reach the pipeline.

Why a failed dump still looks like a backup

MariaDB’s dump client source explains it. For a single database it dumps every table, then the routines. When the routine query fails, it prints the Couldn't execute ... error and exits with code 2 (unless --force is set) before writing its footer. The footer is where the last line, -- Dump completed on <date>, comes from (-- Dump completed with --skip-dump-date; no line at all with --skip-comments or --compact).

So the file on disk was valid gzip containing real table data that stops before the end. gzip -t passes, because the gzip stream is fine. [ -s file.sql.gz ] passes too, and it would pass even if the dump wrote nothing at all, because compressing empty input still produces a 20-byte gzip file:

Copied!
false | gzip > empty.sql.gz; echo "exit=$?"; gzip -t empty.sql.gz && echo "gzip -t OK"; wc -c < empty.sql.gz
Copied!
exit=0
gzip -t OK
20

The checks that do catch it are the exit status of the dump, and the -- Dump completed line at the end of the SQL.

What set -euo pipefail does and where it stops

  • -e (errexit) exits the script when a command fails.
  • -u (nounset) makes expanding an unset variable an error.
  • -o pipefail makes a pipeline fail if any part of it fails.

-e has exceptions that bite exactly the kind of script a backup is. Per the bash manual, it is ignored for commands in an if or while test, for any command in an && or || list except the last, and for commands negated with !. If a function runs in one of those contexts, -e is ignored for its whole body. So this keeps going:

Copied!
set -e
backup_db() { false; echo "still running after false"; }
if backup_db; then echo "backup_db returned 0"; fi
Copied!
still running after false
backup_db returned 0

Three more that I tested on bash 5.2:

  • local out=$(cmd) always succeeds, because the status is local’s, and local returns zero unless it was misused. Declare first, assign on the next line.
  • ((count++)) returns 1 when count was 0, so set -e kills the script. Use count=$((count + 1)).
  • zcat big.sql.gz | head under pipefail can return 141: head exits early, zcat dies of SIGPIPE, and the pipeline reports it.

Command substitution also drops -e inside the subshell unless you set shopt -s inherit_errexit. My rule: set -euo pipefail is a safety net, and any function called from if checks every command explicitly.

How Jenkins and cron decide success

Jenkins reads one number. A freestyle “Execute shell” step runs the script with sh -xe by default and fails the build on a non-zero exit. A Pipeline sh step throws an error on a non-zero exit unless you ask for returnStatus. The Publish Over SSH plugin fails the publish if the exec command exits non-zero, but by default a failed publish sets the build to UNSTABLE, not FAILED. Its “Fail the build if an error occurs” option changes that.

cron reads nothing. crontab(5) describes mailing a job’s output to MAILTO; it does not describe acting on the exit status. With cron, a script that fails quietly and a script that never ran look the same: silence.

Neither notices a job that never runs: a disabled job or a dead Jenkins controller produces no failed build. A heartbeat (dead man’s switch) covers that: the job pings a monitor after each run, and the monitor alerts when a ping is late.

What mysql.proc is

In MariaDB, mysql.proc is the system table that stores the definitions and bodies of stored procedures and functions. Current MariaDB documentation lists it as an Aria table, which matters because REPAIR TABLE and mariadb-check --repair work on Aria, MyISAM, Archive and CSV tables but not InnoDB. mariadb-dump --routines reads it (that option requires SELECT on mysql.proc), starting with SHOW FUNCTION STATUS WHERE Db = '<db>'. When the server cannot use the table it returns error 1728, ER_CANNOT_LOAD_FROM_TABLE_V2: Cannot load from mysql.proc. The table is probably corrupted.

The server in my case was MariaDB. MySQL 8.0 and later have no mysql.proc at all: the routines and parameters data dictionary tables replaced it. If you see this error on MySQL 8, it is about a different table.

The old pipeline and the new one

Before: a failed mysqldump feeds gzip, which exits 0, and the job reports SUCCESS. After: dump with pipefail, gzip -t, trailer check, checksum and rename, where any failed check makes the script exit 1 Left: what the old script did with a failed dump. Right: every check can fail the run. With Publish Over SSH, “build fails” means UNSTABLE unless you tick “Fail the build if an error occurs”.

A VM snapshot of the database server is not a backup of it: it lives on the same storage and dies with it (see Snapshot Before You Touch Production). This article is about the off-host copy.

Prerequisites

  • A MariaDB server (the commands use mariadb-dump, mariadb-check and mariadb; the old mysql* names still work as links but the mysqldump name is deprecated from MariaDB 11.0). For MySQL, swap in mysqldump and mysqlcheck; the bash logic is identical, but the account setup in Step 1 and the mysql.proc material are MariaDB-specific.
  • A backup host with bash, GNU coreutils, gzip, flock (util-linux), curl and an SSH key for the account that runs the job (<JOB_USER> below; it does not need to be root).
  • sudo on both machines.
  • For the restore test: a separate, disposable server running the same or a newer MariaDB version.
  • Values to have on hand: the database server’s name (examples use db1.example.com), each database name (<DB_NAME>), and a backup directory (examples use /srv/backup/databases).

Step 1: Give the Backup a Least-Privilege Account

The original script connected as root to every server. If the backup host is compromised, that key opens every database server with full control. A dedicated account that can only read the databases it dumps limits the damage. On the database server, create an OS user and a matching MariaDB account that authenticates through the Unix socket, so there is no password to store. (Debian and Ubuntu already have a system user called backup, so use a different name.)

Copied!
sudo useradd --create-home --shell /bin/bash dbbackup
sudo mariadb
Copied!
CREATE USER 'dbbackup'@'localhost' IDENTIFIED VIA unix_socket;
GRANT SELECT, SHOW VIEW, TRIGGER ON `<DB_NAME>`.* TO 'dbbackup'@'localhost';
GRANT SELECT ON mysql.proc TO 'dbbackup'@'localhost';
EXIT;

Repeat the first GRANT for each database. If a dump later reports a missing privilege, the error message names it.

Now authorize the backup host’s public key for this account. Open the file with vim (press i to insert, paste the key, then Esc and :wq to save and quit):

Copied!
sudo install -d -m 700 -o dbbackup -g dbbackup /home/dbbackup/.ssh
sudo vim /home/dbbackup/.ssh/authorized_keys
sudo chown dbbackup:dbbackup /home/dbbackup/.ssh/authorized_keys
sudo chmod 600 /home/dbbackup/.ssh/authorized_keys

Step 2: Trust Host Keys Before the Job Needs Them

BatchMode=yes makes ssh fail instead of prompting, which is what you want in a job, and also why an unknown host key killed every rsync in my script. ssh-keyscan trusts whatever answers, so compare its fingerprint with the server’s own before adding it. On the database server:

Copied!
ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub

On the backup host, as the user that runs the job:

Copied!
ssh-keygen -lf <(ssh-keyscan -t ed25519 db1.example.com 2>/dev/null)

If the two fingerprints match, add the key and test a non-interactive login:

Copied!
ssh-keyscan -H -t ed25519 db1.example.com >> ~/.ssh/known_hosts
ssh -o BatchMode=yes dbbackup@db1.example.com hostname

The second command should print the server’s hostname with no prompt. Then check the account can produce a complete dump:

Copied!
ssh -o BatchMode=yes dbbackup@db1.example.com \
    'mariadb-dump --single-transaction --quick --routines --triggers <DB_NAME>' | tail -n 1
Copied!
-- Dump completed on 2026-12-02  3:00:01

If you see error 1728 here instead, go to Step 8 before going further.

Step 3: Install the Hardened Backup Script

Save this as db-backup on the backup host, then fill in the configuration block.

Copied!
#!/usr/bin/env bash
#
# db-backup: dump MariaDB databases over SSH, verify every dump,
# keep checksums, and exit non-zero if anything failed.
#
set -euo pipefail
shopt -s inherit_errexit
umask 077

############################################
# Configuration
############################################
BACKUP_ROOT="/srv/backup/databases"
LOG_DIR="/var/log/db-backup"
RETENTION_DAYS=30
HEARTBEAT_URL="${HEARTBEAT_URL:-}"   # e.g. https://hc-ping.com/<CHECK_UUID>; empty disables
SSH_OPTS=(-o BatchMode=yes -o ConnectTimeout=30)
DUMP_OPTS="--single-transaction --quick --routines --triggers"

# One "<ssh target> <database>" pair per line.
JOBS=(
    "dbbackup@db1.example.com <DB_NAME_1>"
    "dbbackup@db1.example.com <DB_NAME_2>"
)

############################################
# Setup: logging, lock, heartbeat
############################################
DATE="$(date +%Y%m%d)"
DEST="${BACKUP_ROOT}/${DATE}"
LOG_FILE="${LOG_DIR}/backup-$(date +%F).log"
FAILURES=0
CURRENT_TMP=""

mkdir -p "${DEST}" "${LOG_DIR}"
# Everything goes to the log file AND to stdout, so Jenkins sees it too.
exec > >(tee -a "${LOG_FILE}") 2>&1

log() { printf '%s %s\n' "$(date '+%F %T')" "$*"; }

heartbeat() {   # heartbeat <start|exit status>
    [ -n "${HEARTBEAT_URL}" ] || return 0
    curl -fsS -m 10 --retry 3 -o /dev/null "${HEARTBEAT_URL}/$1" \
        || log "WARNING: heartbeat ping '$1' failed"
}

on_exit() {
    local rc=$?
    if [ -n "${CURRENT_TMP}" ]; then
        rm -f -- "${CURRENT_TMP}"
    fi
    heartbeat "${rc}"
}
trap on_exit EXIT
# Without these, a run killed by a signal can reach on_exit with $? = 0
# and report success.
trap 'exit 129' HUP
trap 'exit 130' INT
trap 'exit 143' TERM

exec 9> "${BACKUP_ROOT}/.lock"
if ! flock -n 9; then
    log "ERROR: another backup run is still holding the lock"
    exit 1
fi

heartbeat start

############################################
# backup_db <ssh target> <database>
# Returns 0 only if the dump is complete, valid and in place.
# Called inside an if, so set -e is OFF in here: check everything by hand.
############################################
backup_db() {
    local target="$1" db="$2"
    local host="${target#*@}"
    local outdir="${DEST}/${host}"
    local final="${outdir}/${db}.sql.gz"
    local tmp="${final}.partial"
    local check tables state sum

    log "START ${db} @ ${host}"
    mkdir -p "${outdir}" || return 1
    CURRENT_TMP="${tmp}"

    # 1. Dump and compress. With pipefail, a failure in ssh or
    #    mariadb-dump fails the whole pipeline, not just gzip.
    if ! ssh "${SSH_OPTS[@]}" "${target}" \
            "mariadb-dump ${DUMP_OPTS} $(printf '%q' "${db}")" \
            | gzip > "${tmp}"; then
        log "ERROR ${db} @ ${host}: dump pipeline failed (ssh/dump, gzip: ${PIPESTATUS[*]})"
        return 1
    fi

    # 2. The archive must be intact gzip.
    if ! gzip -t "${tmp}"; then
        log "ERROR ${db} @ ${host}: gzip -t failed"
        return 1
    fi

    # 3. The SQL inside must contain tables and end with the trailer
    #    mariadb-dump writes only when it finishes.
    if ! check="$(gzip -dc "${tmp}" | awk '
            /^CREATE TABLE/ { tables++ }
            { last = $0 }
            END { printf "%d %s\n", tables, (last ~ /^-- Dump completed/) ? "complete" : "truncated" }')"; then
        log "ERROR ${db} @ ${host}: could not read back the dump"
        return 1
    fi
    read -r tables state <<< "${check}"
    if [ "${state}" != "complete" ]; then
        log "ERROR ${db} @ ${host}: no '-- Dump completed' trailer, dump is truncated"
        return 1
    fi
    if [ "${tables}" -lt 1 ]; then
        log "ERROR ${db} @ ${host}: dump contains no CREATE TABLE statements"
        return 1
    fi

    # 4. Checksum, then rename into place (atomic on the same filesystem).
    if ! sum="$(sha256sum < "${tmp}")"; then
        log "ERROR ${db} @ ${host}: sha256sum failed"
        return 1
    fi
    sum="${sum%% *}"
    if ! mv -f -- "${tmp}" "${final}"; then
        log "ERROR ${db} @ ${host}: could not move dump into place"
        return 1
    fi
    CURRENT_TMP=""
    if ! printf '%s  %s\n' "${sum}" "${db}.sql.gz" > "${final}.sha256"; then
        log "ERROR ${db} @ ${host}: could not write checksum file"
        return 1
    fi

    log "OK ${db} @ ${host}: ${tables} tables, $(du -h "${final}" | cut -f1)"
}

############################################
# Run
############################################
log "Backup run started, writing to ${DEST}"

for job in "${JOBS[@]}"; do
    read -r target db <<< "${job}"
    if ! backup_db "${target}" "${db}"; then
        FAILURES=$((FAILURES + 1))
        if [ -n "${CURRENT_TMP}" ]; then
            rm -f -- "${CURRENT_TMP}"
            CURRENT_TMP=""
        fi
    fi
done

############################################
# Prune, but only after a fully successful run
############################################
if [ "${FAILURES}" -eq 0 ]; then
    CUTOFF="$(date -d "${RETENTION_DAYS} days ago" +%Y%m%d)"
    for d in "${BACKUP_ROOT}"/[0-9]*; do
        [ -d "${d}" ] || continue
        name="$(basename "${d}")"
        if [[ "${name}" =~ ^[0-9]{8}$ ]] && [ "${name}" -lt "${CUTOFF}" ]; then
            log "Pruning ${name}"
            rm -rf -- "${d}"
        fi
    done
else
    log "Skipping prune because this run had failures"
fi

############################################
# Result: the exit code is the only thing Jenkins reads
############################################
if [ "${FAILURES}" -gt 0 ]; then
    log "FAILED: ${FAILURES} of ${#JOBS[@]} database(s) did not back up"
    exit 1
fi
log "OK: all ${#JOBS[@]} database(s) backed up and verified"

Install it so the job user can run it, create the directories it writes to, and check the syntax:

Copied!
sudo install -m 750 -o root -g <JOB_USER> db-backup /usr/local/bin/db-backup
sudo install -d -m 700 -o <JOB_USER> -g <JOB_USER> /srv/backup/databases /var/log/db-backup
sudo vim /usr/local/bin/db-backup
sudo bash -n /usr/local/bin/db-backup && echo "syntax OK"

What each part buys you:

  • The dump goes to .partial first and is renamed only after every check passes. rename(2) replaces the target atomically on the same filesystem, so a file named <db>.sql.gz is always a verified dump, never a half-written one.
  • The trailer and CREATE TABLE checks catch truncated dumps and empty dumps, which gzip -t and [ -s ] cannot.
  • Pruning only after a clean run keeps a broken job from deleting the last good backups while it produces bad ones.
  • flock -n stops a second run from starting while a slow one is still writing the same files.
  • gzip -t and the read-back each decompress the whole file. On large dumps that costs CPU time; I accept it.

Step 4: Test the Failure Paths Before Trusting the Success Path

A check you have never seen fail is a check you have not tested. Temporarily add a database that does not exist and a host you have not trusted to JOBS, run the script by hand, and look at the exit code:

Copied!
sudo -u <JOB_USER> /usr/local/bin/db-backup; echo "exit=$?"

You should see lines like these (the exact error text from mariadb-dump may differ by version), and no .partial files left behind:

Copied!
2026-12-02 03:00:02 START does_not_exist @ db1.example.com
mariadb-dump: Got error: 1049: "Unknown database 'does_not_exist'" when selecting the database
2026-12-02 03:00:02 ERROR does_not_exist @ db1.example.com: dump pipeline failed (ssh/dump, gzip: 2 0)
2026-12-02 03:00:02 START <DB_NAME> @ untrusted.example.com
Host key verification failed.
2026-12-02 03:00:02 ERROR <DB_NAME> @ untrusted.example.com: dump pipeline failed (ssh/dump, gzip: 255 0)
2026-12-02 03:00:02 Skipping prune because this run had failures
2026-12-02 03:00:02 FAILED: 2 of 4 database(s) did not back up
exit=1

I ran these cases, plus a dump that exits 0 without a trailer and one with no tables, against stand-in ssh and mariadb-dump commands; each was caught and none left a partial file. Remove the test entries afterwards.

Step 5: Make Jenkins Fail the Build

If you keep Publish Over SSH, open the job’s build step, expand the step’s own Advanced section (below the server entries) and tick Fail the build if an error occurs. Otherwise a failed run only marks the build UNSTABLE. In the server entry’s Advanced section, tick Verbose output in console: without it the plugin does not copy the remote command’s output into the console at all. Set Exec timeout (ms) comfortably above your longest run, because the publish fails if the command has not returned in time.

The simpler alternative is a freestyle Execute shell step that calls ssh directly, where a non-zero exit fails the build:

Copied!
ssh -o BatchMode=yes <JOB_USER>@<BACKUP_HOST> /usr/local/bin/db-backup

Either way, add the E-mail notification post-build action (or your chat integration) so a failed build reaches a person. If you run the script from cron instead, the heartbeat in the next step is not optional.

Step 6: Alert on Absence with a Heartbeat

The script pings HEARTBEAT_URL/start when it begins and HEARTBEAT_URL/<exit status> when it ends. Healthchecks.io (hosted, or self-hosted from its BSD-licensed source) treats /0 as success and /1 to /255 as failure, and alerts if no ping arrives within the schedule plus a grace time. Create a check, set its schedule to the job’s cron expression and a grace time longer than a normal run, then put the ping URL in the script’s configuration block. Send one failure ping by hand to confirm the alert reaches you:

Copied!
curl -fsS -m 10 -o /dev/null https://hc-ping.com/<CHECK_UUID>/1

The ping URL is effectively a credential: anyone who has it can report success for you. Keep it out of public repositories.

If you already run Zabbix, Nagios or similar, add a freshness check on the backup host as a second signal. This prints a warning when no verified dump has been written in the last 26 hours:

Copied!
find /srv/backup/databases -name '*.sql.gz' -mmin -1560 | grep -q . \
    || echo "WARNING: no verified dump in the last 26 hours"

Step 7: Restore-Test on a Schedule

A dump that passes every check above can still fail to restore. The only real verification is restoring it. Run this on a disposable test server, never on production, as the MariaDB root account (through sudo, which uses the socket). Root avoids a common false failure: recreating routines and triggers whose DEFINER names another user requires the SET USER privilege.

Save as /usr/local/bin/restore-test on the test server:

Copied!
#!/usr/bin/env bash
#
# restore-test: restore one verified dump into a throwaway database,
# check what came back, then drop it. Run on a disposable test server.
# Usage: restore-test <dump.sql.gz> [<sanity SQL that returns one number>]
#
set -euo pipefail
shopt -s inherit_errexit

DUMP="${1:?usage: restore-test <dump.sql.gz> [sanity SQL]}"
SANITY_SQL="${2:-}"
HEARTBEAT_URL="${HEARTBEAT_URL:-}"   # a separate check from the backup job's
SCRATCH_DB="restore_test_$(date +%Y%m%d_%H%M%S)"

log() { printf '%s %s\n' "$(date '+%F %T')" "$*"; }
sql() { mariadb --batch --skip-column-names -e "$1"; }

cleanup() {
    local rc=$?
    sql "DROP DATABASE IF EXISTS \`${SCRATCH_DB}\`" \
        || log "WARNING: could not drop ${SCRATCH_DB}"
    if [ -n "${HEARTBEAT_URL}" ]; then
        curl -fsS -m 10 --retry 3 -o /dev/null "${HEARTBEAT_URL}/${rc}" \
            || log "WARNING: heartbeat ping failed"
    fi
    if [ "${rc}" -eq 0 ]; then
        log "RESTORE TEST PASSED: ${DUMP}"
    else
        log "RESTORE TEST FAILED (exit ${rc}): ${DUMP}"
    fi
}
trap cleanup EXIT
# A signal must not reach cleanup with $? = 0 and report a pass.
trap 'exit 129' HUP
trap 'exit 130' INT
trap 'exit 143' TERM

log "Verifying checksum"
( cd "$(dirname "${DUMP}")" && sha256sum -c --quiet "$(basename "${DUMP}").sha256" )

log "Restoring into ${SCRATCH_DB}"
sql "CREATE DATABASE \`${SCRATCH_DB}\`"
gzip -dc "${DUMP}" | mariadb "${SCRATCH_DB}"

expected="$(gzip -dc "${DUMP}" | awk '/^CREATE TABLE/ { n++ } END { print n + 0 }')"
actual="$(sql "SELECT COUNT(*) FROM information_schema.tables
               WHERE table_schema = '${SCRATCH_DB}'
                 AND table_type IN ('BASE TABLE', 'SYSTEM VERSIONED')")"
log "Tables in dump: ${expected}, tables restored: ${actual}"
if [ "${actual}" -lt 1 ] || [ "${actual}" -ne "${expected}" ]; then
    log "ERROR: restored table count does not match the dump"
    exit 1
fi

routines="$(sql "SELECT COUNT(*) FROM information_schema.routines
                 WHERE routine_schema = '${SCRATCH_DB}'")"
log "Stored routines restored: ${routines}"

if [ -n "${SANITY_SQL}" ]; then
    result="$(mariadb --batch --skip-column-names "${SCRATCH_DB}" -e "${SANITY_SQL}")"
    log "Sanity query returned: ${result}"
    if ! [[ "${result}" =~ ^[0-9]+$ ]] || [ "${result}" -lt 1 ]; then
        log "ERROR: sanity query did not return a positive number"
        exit 1
    fi
fi

A single-database dump has no CREATE DATABASE or USE statement, so piping it into mariadb <name> restores it into whatever database you name. The sanity query is where you prove the data is recent, not just present: count rows written in the last two days in a table that always gets writes.

Pull the newest dump and run the test from a small wrapper, /usr/local/bin/restore-test-latest:

Copied!
#!/usr/bin/env bash
set -euo pipefail
export HEARTBEAT_URL="https://hc-ping.com/<RESTORE_CHECK_UUID>"
src="<JOB_USER>@<BACKUP_HOST>:/srv/backup/databases/$(date +%Y%m%d)/db1.example.com"
mkdir -p /srv/restore-test
rsync -a "${src}/<DB_NAME>.sql.gz" "${src}/<DB_NAME>.sql.gz.sha256" /srv/restore-test/
exec /usr/local/bin/restore-test /srv/restore-test/<DB_NAME>.sql.gz \
    "SELECT COUNT(*) FROM <TABLE> WHERE <CREATED_AT_COLUMN> >= NOW() - INTERVAL 2 DAY"

The backup files belong to <JOB_USER> with mode 600, so the wrapper pulls them as that user. Root on the test server needs an SSH key authorized for <JOB_USER> on the backup host, and the backup host’s key in root’s known_hosts (the Step 2 procedure, run on the test server). That key can read every backup, so use it for nothing else. The wrapper looks in today’s dated directory, which assumes the backup starts after midnight.

Make both scripts executable and schedule the wrapper weekly, after the night’s backup has finished, with sudo crontab -e:

Copied!
sudo chmod 755 /usr/local/bin/restore-test /usr/local/bin/restore-test-latest
Copied!
30 6 * * 1 /usr/local/bin/restore-test-latest >> /var/log/restore-test.log 2>&1

If rsync fails, the test never runs and never pings, so the restore check’s own heartbeat goes late and alerts. A clean run logs:

Copied!
2026-12-07 06:30:41 Tables in dump: 42, tables restored: 42
2026-12-07 06:30:41 Stored routines restored: 3
2026-12-07 06:30:41 Sanity query returned: 1874
2026-12-07 06:30:41 RESTORE TEST PASSED: /srv/restore-test/<DB_NAME>.sql.gz

Step 8: Repair a Corrupt mysql.proc, Backup First

Repairs can lose data; MySQL’s own mysqlcheck documentation says to back up a table before repairing it. Do these on the database server.

Confirm the table is the problem:

Copied!
sudo mariadb-check mysql proc

Anything other than OK on the mysql.proc line confirms it. Also read the server’s error log (on systemd distributions it is often in journalctl -u mariadb) for messages about the table.

Take your backups. Table data is still reachable: --routines is off by default, and in my case the tables dumped for minutes before the routine step failed. Dump without it:

Copied!
sudo mariadb-dump --single-transaction --quick --triggers <DB_NAME> | gzip > ~/<DB_NAME>-pre-repair.sql.gz
echo "dump=${PIPESTATUS[0]} gzip=${PIPESTATUS[1]}"

Both numbers should be 0. This is the same lesson in miniature: without the second line you would not know.

Snapshot the VM if it is one (see the snapshot article linked above). Then copy the table’s own files with the server stopped (a short outage). Check datadir first; /var/lib/mysql is the usual default. The copy runs inside sudo sh -c because your own user cannot read that directory, so your shell could not expand the proc.* glob:

Copied!
sudo mariadb -e "SELECT @@datadir"
sudo systemctl stop mariadb
sudo mkdir -p /root/proc-backup
sudo sh -c 'cp -a /var/lib/mysql/mysql/proc.* /root/proc-backup/'
sudo systemctl start mariadb

Repair, then re-run the exact query the dump failed on:

Copied!
sudo mariadb-check --repair mysql proc
sudo mariadb -e "SHOW FUNCTION STATUS WHERE Db = '<DB_NAME>'"

The repair should report OK, and the query should return rows or an empty result with no error. Finish with the Step 2 dump test and look for the -- Dump completed line.

If the repair does not clear it, mariadb-upgrade --force updates the system tables to the structure the running server expects and checks every other table. MariaDB recommends backing up all databases before running it. I fixed my case with mysqlcheck --repair and did not record what had corrupted the table, so I can’t tell you which of the two your server needs. The error log is the place to look.

Verify

  1. Run sudo -u <JOB_USER> /usr/local/bin/db-backup; echo "exit=$?" and confirm exit=0 and one OK line per database.
  2. Confirm each dump has a matching checksum: sudo -u <JOB_USER> bash -c 'cd /srv/backup/databases/$(date +%Y%m%d)/db1.example.com && sha256sum -c *.sha256'.
  3. Break one thing on purpose (a wrong database name), trigger the Jenkins job, and confirm the build fails and the heartbeat check shows a failure.
  4. Disable the job for one schedule period and confirm the heartbeat alerts on absence. Re-enable it.
  5. Run sudo /usr/local/bin/restore-test-latest on the test server and confirm RESTORE TEST PASSED.

Troubleshooting

  • Jenkins shows Finished: SUCCESS but no script output: with Publish Over SSH, first tick “Verbose output in console”; the plugin only connects the remote command’s stdout and stderr to the console when it is on. If it is already on (the console shows SSH: EXEC: STDOUT/STDERR from command), the script sends its output elsewhere, usually exec >> logfile 2>&1. Use exec > >(tee -a "${LOG_FILE}") 2>&1.
  • A failed run marks the build UNSTABLE, not FAILED: that is Publish Over SSH’s default. Tick “Fail the build if an error occurs”.
  • Host key verification failed and rsync error: unexplained error (code 255): the job’s user has no known_hosts entry for that host and BatchMode=yes refuses to prompt. Do Step 2 for that host, as the same user the job runs as.
  • Got error: 1049: "Unknown database": the script names a database that does not exist. Compare with SHOW DATABASES;, fix the name, then find out how long the real one went without a backup.
  • Error 1728, Cannot load from mysql.proc: see Step 8. Do not just delete --routines from the script: it gets the job green and stops backing up every stored procedure on every server.
  • The script exits silently right after a counter increment: ((n++)) returned 1 under set -e. Use n=$((n + 1)).
  • A pipeline with head returns 141: SIGPIPE under pipefail. Read the whole stream (as the script’s awk does) or don’t use pipefail for that one line.
  • The trailer check fails even though the dump exited 0: someone added --skip-comments or --compact, which remove the -- Dump completed line. Remove it. If someone added --force, take that out too: it makes the dump continue past SQL errors and still write the footer, so the file looks complete even though the exit status is 2.
  • The restore fails on the first line of the dump: recent mariadb-dump releases write a sandbox-mode command at the top of every dump, and clients older than 11.4.2, 10.11.8 or 10.6.18 (and the matching releases of other series) do not understand it. Restore with a client at least as new as the one that made the dump.
  • The restore fails with access denied while creating a routine or trigger: the DEFINER names another user, which needs SET USER. Run the restore test as root on the disposable server.

Sources and further reading