#!/usr/bin/env bash # Logical backup of the WorkPilot database (and optionally the DBOS system database). # # WP_BACKUP_DATABASE_URL=postgresql://workpilot_backup:...@host:5432/workpilot \ # deploy/scripts/backup.sh [--out DIR] [--with-dbos] # --with-dbos needs WP_BACKUP_DBOS_URL # # * Custom format (pg_dump -Fc): compressed, restorable table by table with pg_restore. # * EVERYTHING is included: tenant tables, audit_log (hash chains), approvals, runs, the # LangGraph checkpoint tables (checkpoints, checkpoint_blobs, checkpoint_writes, # checkpoint_migrations: waiting runs resume from them after a restore), RLS policies, # grants and default privileges. Nothing tenant-critical is excluded. # * The role MUST bypass RLS (superuser, or the workpilot_backup role from # deploy/sql/bootstrap_managed.sql: LOGIN BYPASSRLS + pg_read_all_data). The app and owner # roles are subject to FORCE ROW LEVEL SECURITY, so pg_dump refuses to run as them # ("query would be affected by row-level security policy"). # * Managed Postgres (Neon, Supabase, RDS) also has its own point-in-time recovery: use that # first for "undo the last hour". This script is the portable, provider-independent copy # (move providers, offline archive, restore drill). See docs/deployment.md. # # Exit code is non-zero on any failure. The dump file is written atomically (tmp + mv). set -euo pipefail OUT_DIR="${WP_BACKUP_DIR:-./backups}" WITH_DBOS=0 while [[ $# -gt 0 ]]; do case "$1" in --out) OUT_DIR="$2"; shift 2 ;; --with-dbos) WITH_DBOS=1; shift ;; -h|--help) sed -n '2,24p' "$0"; exit 0 ;; *) echo "unknown argument: $1" >&2; exit 2 ;; esac done : "${WP_BACKUP_DATABASE_URL:?set WP_BACKUP_DATABASE_URL (a role that bypasses RLS)}" PG_DUMP="${PG_DUMP:-pg_dump}" STAMP="$(date -u +%Y%m%dT%H%M%SZ)" mkdir -p "$OUT_DIR" umask 077 # dumps contain customer data dump() { # dump local url="$1" name="$2" target="$OUT_DIR/$2-$STAMP.dump" "$PG_DUMP" --format=custom --compress=6 --no-password --file="$target.tmp" --dbname="$url" mv "$target.tmp" "$target" # Self-check: the archive's table of contents must be readable. "${PG_RESTORE:-pg_restore}" --list "$target" > /dev/null echo "$target" } dump "$WP_BACKUP_DATABASE_URL" workpilot if [[ "$WITH_DBOS" == 1 ]]; then # DBOS keeps workflow state (queued dispatches, schedules) in its own database. Losing it # is recoverable (events are re-enqueued by the stale-event sweep), but keeping it avoids # duplicate retries after a restore. : "${WP_BACKUP_DBOS_URL:?set WP_BACKUP_DBOS_URL (the _dbos_sys database) for --with-dbos}" dump "$WP_BACKUP_DBOS_URL" workpilot_dbos_sys fi