#!/bin/sh
# Data damage that follows from a prepared transaction going missing after crash
# recovery (PostgreSQL 17, 18).
#
# What this shows
#   twophase-crash-repro.sh shows a prepared transaction absent from
#   pg_prepared_xacts after crash recovery, and back after one more restart.
#   This script goes on from there. While the transaction is absent its xid
#   reads as aborted and it holds no locks, so ordinary statements treat its
#   changes as dead. After the restart that brings it back, COMMIT PREPARED
#   succeeds, and the script checks for two outcomes:
#
#   1. Committed, with none of its changes. Table "seen" is read once by a
#      sequential scan while the transaction is absent. After COMMIT PREPARED,
#      pg_xact_status() says committed and the table holds none of what the
#      transaction did to it.
#
#   2. Two live rows under one primary key. In table "hit" another session
#      updates, by primary key, a row the prepared transaction had updated.
#      It doesn't wait, because the lock is gone. After COMMIT PREPARED the
#      table holds both sessions' versions of that row, and amcheck reports
#      the page.
#
#   On a server that keeps the prepared transaction, the same statements run
#   against a transaction that is present: the scan can't hurt it, the other
#   session's update waits on the row lock and gives up at lock_timeout, and
#   both tables end up correct.
#
# How the crash is emulated
#   As in twophase-crash-repro.sh: global/pg_control is saved after an earlier
#   checkpoint, a later CHECKPOINT writes the state file, the server is stopped
#   with "pg_ctl -m immediate stop", and the saved pg_control is put back. See
#   that script's header for the gdb recipe that gives the same result with a
#   real crash.
#
# Usage
#   PGBIN=/path/to/bin ./twophase-damage-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)
#   TMPDIR      where the scratch cluster goes (default /tmp); it is 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)
#
#   amcheck is used if the build has it (contrib). Without it the two outcomes
#   are still checked by query.
#
# Output: PASS if both tables are correct at the end, FAIL if either outcome is
# seen or the server did not start, INCONCLUSIVE if the other session's update
# was not planned as an index scan (the duplicate needs one). 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

WORK=$(mktemp -d "${TMPDIR:-/tmp}/twophase-damage.XXXXXX") || exit 2
D=$WORK/data
LOG=$WORK/server.log
sql() { "${PGBIN}psql" -X -q -h "$WORK" -p "$PORT" -d postgres "$@"; }
SEQ="set enable_indexscan = off; set enable_bitmapscan = off; set enable_indexonlyscan = off;"

"${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'
autovacuum = off
EOF
"${PGBIN}pg_ctl" -D "$D" -l "$LOG" -w start > /dev/null || { echo "server did not start, see $LOG"; exit 2; }

amcheck=0
sql -c "create extension amcheck" > /dev/null 2>&1 && amcheck=1
[ "$amcheck" = 1 ] || echo "amcheck is not available in this build; checking by query only"

sql -c "create table seen(id int primary key, bal int)" \
    -c "create table hit(id int primary key, bal int, note text)" \
    -c "insert into seen select g, 100 from generate_series(1, 10000) g" \
    -c "insert into hit select g, 100, 'orig' from generate_series(1, 10000) g" \
    -c "vacuum analyze seen" -c "vacuum analyze hit" \
    -c "create table filler(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 filler values (0)"
    i=$((i + 1))
done
sql <<'SQL'
begin;
update seen set bal = bal + 1000 where id = 10000;
insert into seen values (20001, 500);
update hit set bal = bal + 1000, note = 'updated by kept' where id = 10000;
prepare transaction 'kept';
SQL
xid=$(sql -Atc "select transaction from pg_prepared_xacts where gid = 'kept'")
echo "prepared 'kept': xid $xid"
echo "  it adds 1000 to seen.bal for id 10000 and inserts id 20001 (bal 500): committed, seen holds 10001 rows, sum(bal) 1001500"
echo "  it adds 1000 to hit.bal for id 10000: committed, hit holds 10000 rows, sum(bal) 1001000"

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"
present=$(sql -Atc "select count(*) from pg_prepared_xacts where gid = 'kept'")
if [ "$present" = 1 ]; then
    echo "after crash recovery: 'kept' is present in pg_prepared_xacts"
else
    echo "after crash recovery: 'kept' is MISSING from pg_prepared_xacts; pg_xact_status($xid) says $(sql -Atc "select pg_xact_status('$xid'::xid8)")"
fi

echo "--- before the next restart, session A reads table seen once:"
sql -c "explain (costs off) select count(*), sum(bal) from seen" -c "select count(*), sum(bal) from seen"

echo "--- before the next restart, session B updates hit by primary key (lock_timeout 2s):"
plan=$(sql -Atc "explain (costs off) update hit set bal = bal - 30, note = 'updated by session B' where id = 10000")
echo "$plan"
case "$plan" in
    *"Index Scan using hit_pkey"*) ;;
    *)
        "${PGBIN}pg_ctl" -D "$D" -m fast -w stop > /dev/null
        echo "INCONCLUSIVE: the planner did not choose an index scan for session B's update, so the duplicate-key outcome can't be judged"
        exit 2
        ;;
esac
if PGOPTIONS="-c lock_timeout=2s" sql -c "update hit set bal = bal - 30, note = 'updated by session B' where id = 10000" 2> "$WORK/session-b.err"; then
    sessionb=updated
    echo "session B: UPDATE succeeded without waiting"
else
    sessionb=blocked
    echo "session B: $(cat "$WORK/session-b.err")"
    echo "session B: was made to wait by the prepared transaction's row lock, as it should be"
fi

"${PGBIN}pg_ctl" -D "$D" -m fast -w stop > /dev/null
"${PGBIN}pg_ctl" -D "$D" -l "$LOG" -w start > /dev/null
echo "--- after one more clean restart:"
sql -c "select gid, transaction from pg_prepared_xacts"
sql -c "commit prepared 'kept'" && echo "COMMIT PREPARED 'kept' succeeded"
echo "pg_xact_status($xid): $(sql -Atc "select pg_xact_status('$xid'::xid8)")"

bad=0

echo "--- outcome 1: table seen (correct: 10001 rows, sum(bal) 1001500)"
seen=$(sql -Atc "$SEQ select count(*) || ' rows, sum(bal) ' || sum(bal) from seen")
echo "seen holds $seen"
sql -c "$SEQ select xmin, xmax, ctid, * from seen where id in (10000, 20001) order by id, ctid"
if [ "$seen" = "10001 rows, sum(bal) 1001500" ]; then
    echo "outcome 1: not seen, the committed changes are there"
else
    echo "outcome 1: SEEN, the transaction is committed and its changes to this table are not there"
    bad=1
fi

echo "--- outcome 2: table hit (correct: 10000 rows, one row per id)"
hit=$(sql -Atc "$SEQ select count(*) || ' rows, sum(bal) ' || sum(bal) from hit")
dups=$(sql -Atc "$SEQ select id || ' x' || count(*) from hit group by id having count(*) > 1 order by id")
echo "hit holds $hit"
echo "ids with more than one live row (sequential scan): ${dups:-none}"
echo "rows for id 10000 by sequential scan:"
sql -c "$SEQ select xmin, xmax, ctid, * from hit where id = 10000 order by ctid"
echo "rows for id 10000 by index scan:"
sql -c "set enable_seqscan = off; set enable_bitmapscan = off; select xmin, xmax, ctid, * from hit where id = 10000 order by ctid"
if [ -z "$dups" ] && [ "${hit%%,*}" = "10000 rows" ]; then
    echo "outcome 2: not seen, one live row per primary key"
else
    echo "outcome 2: SEEN, more than one live row under one primary key"
    bad=1
fi

if [ "$amcheck" = 1 ]; then
    echo "--- amcheck"
    for check in "select bt_index_check('hit_pkey', true)" "select bt_index_check('seen_pkey', true)"; do
        if err=$(sql -Atc "$check" 2>&1 > /dev/null) && [ -z "$err" ]; then
            echo "$check: clean"
        else
            echo "$check: $err"
            bad=1
        fi
    done
    for tab in hit seen; do
        rows=$(sql -Atc "select blkno || ',' || offnum || ': ' || msg from verify_heapam('$tab')")
        if [ -z "$rows" ]; then
            echo "verify_heapam('$tab'): clean"
        else
            echo "verify_heapam('$tab'):"
            echo "$rows"
            bad=1
        fi
    done
fi
"${PGBIN}pg_ctl" -D "$D" -m fast -w stop > /dev/null

if [ "$bad" = 0 ] && [ "$present" = 1 ] && [ "$sessionb" = blocked ]; then
    echo "PASS: prepared transaction kept through crash recovery, both tables correct"
    exit 0
fi
if [ "$bad" = 0 ]; then
    echo "FAIL: no damage found, but the prepared transaction was missing after crash recovery or failed to hold its row lock"
    exit 1
fi
echo "FAIL: data damage after a prepared transaction went missing in crash recovery"
exit 1
