#!/bin/sh
# A prepared transaction that is missing after crash recovery (PostgreSQL 17, 18).
#
# What this shows
#   A server that crashes after a checkpoint has written a prepared transaction's
#   state file to pg_twophase (CheckPointTwoPhase, the last step of CheckPointGuts)
#   and before that checkpoint is recorded in pg_control (UpdateControlFile in
#   CreateCheckPoint) recovers from the checkpoint before. If the transaction's
#   xid is above that older checkpoint's nextXid, startup comes up without the
#   prepared transaction: it is absent from pg_prepared_xacts, holds no locks and
#   cannot be committed or rolled back, until the server is restarted once more.
#
# How the crash is emulated
#   This script does not crash the server inside the checkpoint. It saves
#   global/pg_control after an earlier checkpoint, lets a later CHECKPOINT write
#   the state file, stops the server with "pg_ctl -m immediate stop", and puts
#   the saved pg_control back. That leaves on disk what a crash between
#   CheckPointTwoPhase and UpdateControlFile leaves: a state file in pg_twophase,
#   and a control file naming the older checkpoint.
#
#   The faithful alternative, which gives the same result, is a real crash:
#     1. run the steps below up to and including PREPARE TRANSACTION
#     2. gdb -p <checkpointer pid>
#          (gdb) handle SIGINT nostop noprint pass
#          (gdb) break update_controlfile
#          (gdb) continue
#     3. from another terminal: psql -c checkpoint
#     4. when the breakpoint is hit (backtrace shows CreateCheckPoint), the state
#        file is in pg_twophase and pg_controldata still shows the older
#        checkpoint; kill -9 the postmaster and all its children, then quit gdb
#     5. remove postmaster.pid if left behind, start the server, and look at
#        pg_prepared_xacts and the log
#
# Usage
#   PGBIN=/path/to/bin ./twophase-crash-repro.sh
#   PGBIN       directory holding initdb, pg_ctl, psql (default: use PATH)
#   PGPORT      port for the scratch server (default 54439)
#   XACTS       committed transactions between the older checkpoint and the
#               prepared one (default 2; with 0 the prepared xid equals the older
#               checkpoint's nextXid and the transaction survives)
#   TMPDIR      where the scratch cluster goes (default /tmp); it is left in place
#
# Output: PASS if the prepared transaction is present after crash recovery,
# FAIL if it is missing or the server did not start. Exit status 0 or 1.

set -u
PGBIN=${PGBIN:-}
[ -n "$PGBIN" ] && PGBIN="$PGBIN/"
PORT=${PGPORT:-54439}
XACTS=${XACTS:-2}

WORK=$(mktemp -d "${TMPDIR:-/tmp}/twophase-repro.XXXXXX") || exit 2
D=$WORK/data
LOG=$WORK/server.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 "checkpoint"
cp "$D/global/pg_control" "$WORK/pg_control.older-checkpoint"

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'"
echo "prepared: xid $(sql -Atc "select transaction from pg_prepared_xacts where gid = 'kept'"), $XACTS committed transaction(s) since the older checkpoint"

sql -c "checkpoint"
echo "state file written by the checkpoint: $(ls "$D/pg_twophase")"

"${PGBIN}pg_ctl" -D "$D" -m immediate -w stop > /dev/null
cp "$WORK/pg_control.older-checkpoint" "$D/global/pg_control"

before=$(wc -l < "$LOG")
if ! "${PGBIN}pg_ctl" -D "$D" -l "$LOG" -w start > /dev/null 2>&1; then
    echo "--- server log from the recovery start:"
    tail -n +"$((before + 1))" "$LOG" | grep -E "TRAP|PANIC|FATAL|WARNING|terminated"
    echo "FAIL: server did not come up after crash recovery (an assert-enabled build aborts here)"
    exit 1
fi
echo "--- warnings from crash recovery:"
tail -n +"$((before + 1))" "$LOG" | grep -E "WARNING|PANIC|TRAP"
echo "--- pg_prepared_xacts after crash recovery:"
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 pg_twophase now: $(ls "$D/pg_twophase")"

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

if [ "$present" = 1 ]; then
    echo "PASS: prepared transaction present after crash recovery"
    exit 0
fi
echo "FAIL: prepared transaction missing after crash recovery"
exit 1
