#!/bin/bash
#
# pg_rewind_redo_repro.sh - standalone reproducer, stock PostgreSQL only (no Patroni, no Kubernetes).
#
# Claim being tested:
#   pg_rewind keeps the target's WAL segments only from the segment of the last common checkpoint RECORD
#   onward (findLastCheckpoint() -> keepwal_add_entry()), but writes a backup_label whose START WAL LOCATION is
#   that checkpoint's REDO point. The REDO point is taken when the checkpoint STARTS; the record is written when
#   it ENDS. When these are in different WAL segments, the segments in between that are not on the source are
#   deleted from the target by pg_rewind, and the rewound server then cannot start recovery:
#       waiting for WAL to become available at <REDO>
#       FATAL: could not receive data from WAL stream: ERROR: requested WAL segment ... has already been removed
#
# A has wal_keep_size=1GB (as a real old primary would), so A's own WAL survives its crash recovery;
# B has wal_keep_size=0, so after promotion it recycles everything it does not need.
# Scenario (tiny 1 MB WAL segments so the gap is a few MB, runs in about 3 minutes):
#   1. A = primary, B = streaming standby. A runs a writer with timed, spread-out checkpoints.
#   2. Wait for a checkpoint on A whose REDO is >= MIN_SEG_GAP segments before its record.
#   3. Stop B, let A write a little more (WAL that exists only on A), crash A (stop -m immediate).
#   4. Save A's pg_wal (for the control), promote B (new timeline), checkpoint B so it recycles old WAL.
#   5. pg_rewind A from B (--debug), write recovery config, start A as a standby of B.
#   6. Report: REDO segment in backup_label, whether it still exists in A's pg_wal, A's log.
#   7. Control: put the segments pg_rewind deleted back from the saved copy; A then recovers.
#
# Usage:   ./pg_rewind_redo_repro.sh            (run as a non-root user; needs PostgreSQL 14+ binaries)
# Config (environment variables, all optional):
#   PGBIN=/usr/lib/postgresql/15/bin   directory with initdb, pg_ctl, pg_rewind, pg_basebackup, psql
#   BASE=/tmp/pg_rewind_redo_repro     work directory (deleted at start)
#   PORT_A=55501 PORT_B=55502          TCP ports on 127.0.0.1
#   MIN_SEG_GAP=20                     required distance, in WAL segments, between checkpoint REDO and record
#   KEEP=1                             keep the work directory at the end
# Exit code: 0 = reproduced and control passed, 2 = not reproduced, 1 = setup error.
#
set -u

PGBIN=${PGBIN:-$(dirname "$(command -v pg_ctl 2>/dev/null || echo /usr/lib/postgresql/15/bin/pg_ctl)")}
BASE=${BASE:-/tmp/pg_rewind_redo_repro}
PORT_A=${PORT_A:-55501}
PORT_B=${PORT_B:-55502}
MIN_SEG_GAP=${MIN_SEG_GAP:-20}
KEEP=${KEEP:-0}
SEG_BYTES=1048576   # --wal-segsize=1
A=$BASE/A; B=$BASE/B

export PATH="$PGBIN:$PATH"
[ "$(id -u)" != 0 ] || { echo "run as a non-root user (postgres refuses to run as root)"; exit 1; }
for t in initdb pg_ctl pg_rewind pg_basebackup psql pg_controldata; do command -v $t >/dev/null || { echo "missing $t in $PGBIN"; exit 1; }; done

log()  { printf '%s  %s\n' "$(date +%T)" "$*"; }
hdr()  { printf '\n==== %s ====\n' "$*"; }
psqlA() { psql -X -h 127.0.0.1 -p $PORT_A -U postgres -d postgres -Atq "$@"; }
psqlB() { psql -X -h 127.0.0.1 -p $PORT_B -U postgres -d postgres -Atq "$@"; }
seg_of() { local x=${1%%/*} y=${1##*/}; echo $(( ((16#$x << 32) + 16#$y) / SEG_BYTES )); }          # LSN "X/Y" -> segment number
file_segno() { echo $(( 16#${1:8:8} * (4294967296 / SEG_BYTES) + 16#${1:16:8} )); }                 # WAL file name -> segment number
oldest_seg() { ls "$1/pg_wal" | grep -E '^[0-9A-F]{24}$' | head -1; }
newest_seg() { ls "$1/pg_wal" | grep -E '^[0-9A-F]{24}$' | tail -1; }
cleanup() { [ -n "${WRITER_PID:-}" ] && kill "$WRITER_PID" 2>/dev/null
            pg_ctl -D "$A" stop -m immediate >/dev/null 2>&1; pg_ctl -D "$B" stop -m immediate >/dev/null 2>&1
            [ "$KEEP" = 1 ] || rm -rf "$BASE"; }
trap cleanup EXIT

rm -rf "$BASE"; mkdir -p "$BASE"

COMMON="
listen_addresses='127.0.0.1'
unix_socket_directories='$BASE'
wal_level=replica
wal_log_hints=on
max_wal_senders=5
hot_standby=on
fsync=off
shared_buffers=16MB
log_checkpoints=on
checkpoint_timeout=30s
checkpoint_completion_target=0.9
min_wal_size=2MB
max_wal_size=1GB
wal_keep_size=1GB
archive_mode=off
"

hdr "setup: PostgreSQL $(postgres --version 2>/dev/null | head -1), A on :$PORT_A, B on :$PORT_B, 1 MB WAL segments"
initdb -D "$A" -U postgres -A trust --wal-segsize=1 --no-sync >/dev/null || exit 1
printf '%s\nport=%s\n' "$COMMON" "$PORT_A" >> "$A/postgresql.conf"
pg_ctl -D "$A" -l "$BASE/A.log" -w start >/dev/null || { cat "$BASE/A.log"; exit 1; }
psqlA -c "create table t(id int primary key, v bigint, d text); insert into t select g,0,repeat('x',100) from generate_series(1,50000) g;" || exit 1
pg_basebackup -h 127.0.0.1 -p $PORT_A -U postgres -D "$B" -R -X stream -c fast >/dev/null || exit 1
printf 'port=%s\nmax_wal_size=16MB\nwal_keep_size=0\n' "$PORT_B" >> "$B/postgresql.conf"   # B (the new primary) keeps no extra WAL; A keeps 1GB like a real old leader
pg_ctl -D "$B" -l "$BASE/B.log" -w start >/dev/null || { cat "$BASE/B.log"; exit 1; }
log "B streaming from A: $(psqlA -c "select client_addr||' '||state from pg_stat_replication")"

hdr "step 1: writer on A; wait for a checkpoint with REDO >= $MIN_SEG_GAP segments before its record"
( while true; do psqlA -c "update t set v=v+1, d=md5(random()::text) where id % 25 = $((RANDOM % 25))" >/dev/null 2>&1; sleep 0.15; done ) &
WRITER_PID=$!
end=$((SECONDS+240)); REC_LSN=""; REDO_LSN=""
while [ $SECONDS -lt $end ]; do
  row=$(psqlA -F' ' -c "select checkpoint_lsn, redo_lsn from pg_control_checkpoint()") || { sleep 1; continue; }
  set -- $row; rec=$1; redo=$2
  gap=$(( $(seg_of "$rec") - $(seg_of "$redo") ))
  if [ "$gap" -ge "$MIN_SEG_GAP" ]; then REC_LSN=$rec; REDO_LSN=$redo; break; fi
  sleep 0.2
done
[ -n "$REC_LSN" ] || { log "no checkpoint with a large enough REDO gap within 240 s (raise the write rate or MIN_SEG_GAP)"; exit 1; }
log "last completed checkpoint on A: record=$REC_LSN (segment $(seg_of $REC_LSN))  redo=$REDO_LSN (segment $(seg_of $REDO_LSN))  gap=$gap segments"

hdr "step 2: stop B, let A write WAL that B never gets, crash A"
for i in $(seq 1 100); do [ "$(psqlB -c "select pg_last_wal_replay_lsn() >= '$REC_LSN'")" = t ] && break; sleep 0.1; done
pg_ctl -D "$B" -m fast -w stop >/dev/null
A_BEFORE=$(psqlA -c "select pg_current_wal_lsn()"); sleep 2
A_END=$(psqlA -c "select pg_current_wal_lsn()")
ONLY_A_KB=$(psqlA -c "select (pg_wal_lsn_diff('$A_END','$A_BEFORE')/1024)::bigint")
kill $WRITER_PID 2>/dev/null; WRITER_PID=""
pg_ctl -D "$A" -m immediate -w stop >/dev/null
log "A wrote about $ONLY_A_KB KB after B stopped (WAL that exists only on A); A crashed at about $A_END"
cp -a "$A/pg_wal" "$BASE/A_pg_wal_before_rewind"
log "A's pg_wal before pg_rewind: $(ls "$A/pg_wal" | grep -cE '^[0-9A-F]{24}$') segments, $(oldest_seg "$A") .. $(newest_seg "$A")"

hdr "step 3: promote B (new timeline) and let it recycle old WAL"
sed -i '/^primary_conninfo/d' "$B/postgresql.auto.conf" 2>/dev/null
pg_ctl -D "$B" -l "$BASE/B.log" -w start >/dev/null
pg_ctl -D "$B" -w promote >/dev/null
psqlB -c "checkpoint" >/dev/null   # B's checkpoint REDO is at the fork: recycles A's REDO..record range on B, keeps B's fork segment
log "B timeline $(psqlB -c "select timeline_id from pg_control_checkpoint()"), B's pg_wal now: $(oldest_seg "$B") .. $(newest_seg "$B")"
B_OLDEST_SEG=$(file_segno "$(oldest_seg "$B")")
log "B's oldest segment number $B_OLDEST_SEG vs A's REDO segment $(seg_of $REDO_LSN) and record segment $(seg_of $REC_LSN)"
[ "$B_OLDEST_SEG" -ge "$(seg_of $REC_LSN)" ] && log "B no longer has A's REDO..record range (good)" || log "WARNING: B still has some of A's REDO..record range; pg_rewind would copy those instead of deleting them"

hdr "step 4: pg_rewind A from B"
pg_rewind --debug --progress -D "$A" --source-server="host=127.0.0.1 port=$PORT_B user=postgres dbname=postgres" -R > "$BASE/rewind.log" 2>&1
RC=$?
grep -E "servers diverged|rewinding from last common checkpoint|Done!|no rewind required" "$BASE/rewind.log" | sed 's/^/  /'
log "pg_rewind exit code: $RC"
log "WAL files pg_rewind marked REMOVE on A: $(grep -cE 'pg_wal/[0-9A-F]{24} \(REMOVE\)' "$BASE/rewind.log"); marked COPY: $(grep -cE 'pg_wal/[0-9A-F]{24} \(COPY\)' "$BASE/rewind.log")"
grep -E 'pg_wal/[0-9A-F]{24} \(REMOVE\)' "$BASE/rewind.log" | sed -n '1p;$p' | sed 's|^|  first/last REMOVE: |'
grep -E 'Not removing file.*pg_wal' "$BASE/rewind.log" | sed 's/^/  /' | head -3

hdr "step 5: backup_label written by pg_rewind vs the WAL that is left on A"
head -2 "$A/backup_label" | sed 's/^/  /'
START_FILE=$(sed -n 's/^START WAL LOCATION: .*(file \([0-9A-F]*\)).*/\1/p' "$A/backup_label")
log "A's pg_wal after pg_rewind: $(ls "$A/pg_wal" | grep -cE '^[0-9A-F]{24}$') segments, oldest $(oldest_seg "$A") (segment number $(file_segno "$(oldest_seg "$A")"); checkpoint record is in segment $(seg_of $REC_LSN))"
if [ -e "$A/pg_wal/$START_FILE" ]; then log "START WAL segment $START_FILE: present"; MISSING=0; else log "START WAL segment $START_FILE: MISSING"; MISSING=1; fi
log "present in A's pg_wal BEFORE the rewind: $([ -e "$BASE/A_pg_wal_before_rewind/$START_FILE" ] && echo yes || echo no)"

hdr "step 6: start A as a standby of B"
printf 'port=%s\n' "$PORT_A" >> "$A/postgresql.conf"
pg_ctl -D "$A" -l "$BASE/A2.log" start >/dev/null 2>&1
sleep 15
grep -aE "waiting for WAL to become available|has already been removed|entering standby|consistent recovery state" "$BASE/A2.log" | cut -c1-190 | sed 's/^/  /' | sed -n '1,4p'
REMOVED=$(grep -ac "has already been removed" "$BASE/A2.log")
STUCK=$(grep -ac "waiting for WAL to become available" "$BASE/A2.log")
log "'has already been removed' lines: $REMOVED ; 'waiting for WAL to become available' lines: $STUCK"
pg_ctl -D "$A" -m immediate stop >/dev/null 2>&1

hdr "step 7: control - restore the segments pg_rewind removed (they were on A before the rewind), start A again"
RESTORED=0; REC_SEG=$(seg_of "$REC_LSN")
for f in $(ls "$BASE/A_pg_wal_before_rewind" | grep -E '^[0-9A-F]{24}$'); do
  # only the range [REDO segment, checkpoint-record segment) that pg_rewind should have kept; NOT A's divergent tail
  [ "$(file_segno "$f")" -lt "$REC_SEG" ] || continue
  [ -e "$A/pg_wal/$f" ] || { cp -a "$BASE/A_pg_wal_before_rewind/$f" "$A/pg_wal/$f"; RESTORED=$((RESTORED+1)); }
done
log "restored $RESTORED segment files (segments $(seg_of $REDO_LSN) .. $((REC_SEG-1)), the REDO..record range) from the pre-rewind copy"
pg_ctl -D "$A" -l "$BASE/A3.log" start >/dev/null 2>&1
CTRL_OK=0
for i in $(seq 1 40); do
  if [ "$(psqlA -c "select pg_is_in_recovery()" 2>/dev/null)" = t ] && [ "$(psqlA -c "select count(*) from pg_stat_wal_receiver where status='streaming'" 2>/dev/null)" = 1 ]; then CTRL_OK=1; break; fi
  sleep 1
done
if [ "$CTRL_OK" = 1 ]; then
  sleep 2
  SUM_A=$(psqlA -c "select sum(v) from t"); SUM_B=$(psqlB -c "select sum(v) from t")
  log "control: A is a streaming standby of B; sum(v) A=$SUM_A B=$SUM_B $([ "$SUM_A" = "$SUM_B" ] && echo '(identical)' || echo '(DIFFERENT)')"
else
  log "control: A did NOT recover; last log lines:"; tail -3 "$BASE/A3.log" | sed 's/^/  /'
fi

hdr "RESULT"
if [ "$RC" = 0 ] && [ "$MISSING" = 1 ] && [ "$STUCK" -ge 1 ]; then
  echo "REPRODUCED: pg_rewind exited 0, but backup_label's START WAL segment $START_FILE no longer exists on the target,"
  echo "            recovery waits for it ('already been removed': $REMOVED). It existed before the rewind: pg_rewind deleted it."
  [ "$CTRL_OK" = 1 ] && { echo "CONTROL PASSED: with the removed segments put back, the same target recovers and streams from the new primary."; exit 0; }
  echo "CONTROL DID NOT PASS (see above)"; exit 2
fi
echo "NOT REPRODUCED (rewind rc=$RC, START segment missing=$MISSING, 'waiting for WAL' lines=$STUCK). Work dir: $BASE (set KEEP=1 to keep)"
exit 2
