#!/bin/sh
# A prepared transaction that is missing from a restored base backup, with no
# crash anywhere (PostgreSQL 17, 18).
#
# What this shows
#   pg_basebackup runs against a healthy server. While it is streaming files, a
#   transaction is prepared and a CHECKPOINT writes its state file to
#   pg_twophase. The backup then holds that state file, and its backup_label
#   names the checkpoint taken when the backup began, whose nextXid is below the
#   prepared transaction's xid. Started as a new server, the backup comes up
#   without the prepared transaction: it is absent from pg_prepared_xacts until
#   that server is restarted once more. The source server has it throughout.
#
# How the timing is pinned down
#   The backup is throttled (-r) over a padding table so that it lasts several
#   seconds, and the script waits until pg_stat_progress_basebackup reports
#   "streaming database files" before it prepares the transaction and runs the
#   checkpoint. Whether pg_twophase is copied after that checkpoint depends on
#   the order in which the server walks the data directory, which this script
#   cannot control. So before judging it checks the backup itself: the state
#   file must be in the backup's pg_twophase, and the transaction's xid must be
#   above the nextXid of the checkpoint the backup began with. If either does
#   not hold the run proves nothing and the script says INCONCLUSIVE.
#
# Usage
#   PGBIN=/path/to/bin ./twophase-basebackup-repro.sh
#   PGBIN       directory holding initdb, pg_ctl, psql, pg_basebackup
#               (default: use PATH)
#   PGPORT      port for the scratch servers (default 54439)
#   XACTS       committed transactions between the start of the backup and the
#               prepared one (default 2)
#   PADROWS     rows in the padding table (default 60000, about 35 MB)
#   RATE        pg_basebackup transfer rate (default 4M)
#   TMPDIR      where the scratch clusters go (default /tmp); left in place
#   PGCTLTIMEOUT  seconds pg_ctl waits for a start or stop (default here 300;
#               pg_ctl's own default of 60 can be too short for crash recovery
#               on a slow or busy disk, and a start that times out would be
#               misread as a server that did not come up)
#
# Output: PASS if the prepared transaction is present when the restored backup
# first starts, FAIL if it is missing or that server did not start,
# INCONCLUSIVE if the backup did not capture the state file. Exit status 0, 1
# or 2.

set -u
PGBIN=${PGBIN:-}
[ -n "$PGBIN" ] && PGBIN="$PGBIN/"
PORT=${PGPORT:-54439}
XACTS=${XACTS:-2}
PGCTLTIMEOUT=${PGCTLTIMEOUT:-300}
export PGCTLTIMEOUT
PADROWS=${PADROWS:-60000}
RATE=${RATE:-4M}

WORK=$(mktemp -d "${TMPDIR:-/tmp}/twophase-bb.XXXXXX") || exit 2
D=$WORK/primary
BK=$WORK/backup
LOG=$WORK/primary.log
BKLOG=$WORK/restored.log
sql() { "${PGBIN}psql" -X -q -h "$WORK" -p "$PORT" -d postgres "$@"; }

"${PGBIN}postgres" --version
echo "scratch directory: $WORK"
"${PGBIN}initdb" -D "$D" -A trust > "$WORK/initdb.log" 2>&1 || { echo "initdb failed, see $WORK/initdb.log"; exit 2; }
cat >> "$D/postgresql.conf" <<EOF
max_prepared_transactions = 10
port = $PORT
listen_addresses = ''
unix_socket_directories = '$WORK'
EOF
"${PGBIN}pg_ctl" -D "$D" -l "$LOG" -w start > /dev/null || { echo "server did not start, see $LOG"; exit 2; }

sql -c "create table t(i int)" \
    -c "create table pad as select g, repeat('x', 500) from generate_series(1, $PADROWS) g"

"${PGBIN}pg_basebackup" -h "$WORK" -p "$PORT" -D "$BK" -c fast -X stream -r "$RATE" > "$WORK/pg_basebackup.log" 2>&1 &
bb=$!
i=0
phase=
while [ "$i" -lt 300 ]; do
    phase=$(sql -Atc "select phase from pg_stat_progress_basebackup")
    [ "$phase" = "streaming database files" ] && break
    sleep 0.1
    i=$((i + 1))
done
if [ "$phase" != "streaming database files" ]; then
    wait "$bb"
    "${PGBIN}pg_ctl" -D "$D" -m fast -w stop > /dev/null
    echo "INCONCLUSIVE: the backup never reported that it was streaming files (finished too fast?), see $WORK/pg_basebackup.log"
    exit 2
fi
startxid=$(sql -Atc "select next_xid from pg_control_checkpoint()")
echo "backup is streaming files; it began at a checkpoint with nextXid $startxid"

i=0
while [ "$i" -lt "$XACTS" ]; do
    sql -c "insert into t values (0)"
    i=$((i + 1))
done
sql -c "begin; insert into t values (1); prepare transaction 'kept'"
xid=$(sql -Atc "select transaction from pg_prepared_xacts where gid = 'kept'")
sql -c "checkpoint"
echo "prepared: xid $xid; state file written by the checkpoint: $(ls "$D/pg_twophase")"
echo "backup phase after that checkpoint: $(sql -Atc "select phase from pg_stat_progress_basebackup")"

wait "$bb"
bbrc=$?
if [ "$bbrc" -ne 0 ]; then
    "${PGBIN}pg_ctl" -D "$D" -m fast -w stop > /dev/null
    echo "pg_basebackup failed with status $bbrc, see $WORK/pg_basebackup.log"
    exit 2
fi
echo "--- pg_prepared_xacts on the source server after the backup:"
sql -c "select gid, transaction from pg_prepared_xacts"
"${PGBIN}pg_ctl" -D "$D" -m fast -w stop > /dev/null

infile=$(ls "$BK/pg_twophase")
echo "state file(s) in the backup: ${infile:-none}"
grep -E "CHECKPOINT LOCATION|START WAL LOCATION" "$BK/backup_label"
if [ -z "$infile" ]; then
    echo "INCONCLUSIVE: pg_twophase was copied before the checkpoint wrote the state file; nothing is shown either way (try a larger PADROWS or a lower RATE)"
    exit 2
fi
startxid=${startxid#*:}
if [ "$xid" -le "$startxid" ]; then
    echo "INCONCLUSIVE: the prepared xid $xid is not above the backup's starting nextXid $startxid, which is the safe case"
    exit 2
fi

if ! "${PGBIN}pg_ctl" -D "$BK" -l "$BKLOG" -w start > /dev/null 2>&1; then
    echo "--- server log of the restored backup:"
    grep -E "TRAP|PANIC|FATAL|WARNING|terminated" "$BKLOG"
    echo "FAIL: the restored backup did not come up (an assert-enabled build aborts here)"
    exit 1
fi
echo "--- warnings from the restored backup's first start:"
grep -E "WARNING|PANIC|TRAP" "$BKLOG"
echo "--- pg_prepared_xacts in the restored backup, first start:"
sql -c "select gid, transaction from pg_prepared_xacts"
present=$(sql -Atc "select count(*) from pg_prepared_xacts where gid = 'kept'")
echo "state file(s) in the restored backup's pg_twophase now: $(ls "$BK/pg_twophase")"

"${PGBIN}pg_ctl" -D "$BK" -m fast -w stop > /dev/null
"${PGBIN}pg_ctl" -D "$BK" -l "$BKLOG" -w start > /dev/null
echo "--- pg_prepared_xacts in the restored backup after one more clean restart:"
sql -c "select gid, transaction from pg_prepared_xacts"
"${PGBIN}pg_ctl" -D "$BK" -m fast -w stop > /dev/null

if [ "$present" = 1 ]; then
    echo "PASS: prepared transaction present when the restored backup first starts"
    exit 0
fi
echo "FAIL: prepared transaction missing when the restored backup first starts"
exit 1
