#!/usr/bin/env bash
# One-host reproducer: a synchronized failover logical slot on a standby is invalidated by a
# catalog cleanup replayed from the primary, despite hot_standby_feedback = on.
#
# Two PostgreSQL instances on one machine (primary and physical standby), a pgoutput slot with
# failover = true, pg_recvlogical as the consumer, slot synchronization on the standby. The gap
# between the copy and the primary's slot is created by pausing sync_replication_slots for PAUSE
# seconds while the consumer keeps acknowledging. Overlapping transactions longer than a sync
# cycle are part of the workload: without them the published catalog_xmin did not move backward
# in our runs. The run is timing dependent and writes a few GB of WAL and a large DEBUG2 log.
#
# Usage: PGBIN=/path/to/bin ./repro-one-host.sh BASE_DIR     (BASE_DIR must not exist yet)
#   PAUSE   seconds with slot sync off (default 180)
#   WAIT    wall-clock seconds to wait for an invalidation after sync is back on (default 720)
#   PPORT/SPORT  ports (default 54321/54322)
# Exit code: 0 = invalidation reproduced, 1 = not reproduced within WAIT, 2 = setup or workload error.
set -uo pipefail

PGBIN=${PGBIN:-$(pg_config --bindir 2>/dev/null || true)}
[ -n "$PGBIN" ] && [ -x "$PGBIN/postgres" ] || { echo "postgres not found; set PGBIN or add pg_config to PATH" >&2; exit 2; }
[ $# -ge 1 ] || { echo "usage: $0 BASE_DIR" >&2; exit 2; }
case $1 in /*) BASE=$1;; *) BASE=$PWD/$1;; esac
[ -e "$BASE" ] && { echo "$BASE exists, use a fresh directory" >&2; exit 2; }
case $BASE in *"'"*|*'\'*) echo "base path must not contain quotes or backslashes" >&2; exit 2;; esac
PAUSE=${PAUSE:-180}; WAIT=${WAIT:-720}; PPORT=${PPORT:-54321}; SPORT=${SPORT:-54322}
for v in PAUSE WAIT PPORT SPORT; do [[ ${!v} =~ ^[0-9]+$ ]] || { echo "$v must be a number" >&2; exit 2; }; done
[ "$PPORT" != "$SPORT" ] || { echo "PPORT and SPORT must differ" >&2; exit 2; }

P=$BASE/primary; S=$BASE/standby; LOG=$BASE/log
mkdir -p "$LOG" || exit 2
psqlp() { "$PGBIN/psql" -X -qAt -v ON_ERROR_STOP=1 -h localhost -p "$PPORT" -d postgres "$@"; }
psqls() { "$PGBIN/psql" -X -qAt -v ON_ERROR_STOP=1 -h localhost -p "$SPORT" -d postgres "$@"; }
ts() { date -u +%T; }
fail() { echo "[$(ts)] ERROR: $*" >&2; exit 2; }

CHILDREN=(); STARTED=()
cleanup() {
  trap - EXIT INT TERM
  for pid in ${CHILDREN[@]+"${CHILDREN[@]}"}; do pkill -P "$pid" 2>/dev/null; kill "$pid" 2>/dev/null; done
  for d in ${STARTED[@]+"${STARTED[@]}"}; do "$PGBIN/pg_ctl" -D "$d" stop -m fast -s 2>/dev/null; done
  for pid in ${CHILDREN[@]+"${CHILDREN[@]}"}; do wait "$pid" 2>/dev/null; done
}
trap cleanup EXIT; trap 'exit 130' INT; trap 'exit 143' TERM

echo "[$(ts)] $("$PGBIN/postgres" --version), base $BASE, pause ${PAUSE}s, wait ${WAIT}s"

# ---- primary -------------------------------------------------------------------------------
"$PGBIN/initdb" -D "$P" -A trust > "$LOG/initdb-primary.log" 2>&1 || fail "initdb primary, see $LOG/initdb-primary.log"
cat >> "$P/postgresql.conf" <<EOF
port = $PPORT
listen_addresses = 'localhost'
wal_level = logical
max_wal_senders = 10
max_replication_slots = 10
max_slot_wal_keep_size = -1
max_wal_size = '2GB'
checkpoint_timeout = '15min'
autovacuum_naptime = '1s'
log_autovacuum_min_duration = 0
log_line_prefix = '%m [%p] %a '
log_timezone = 'UTC'
logging_collector = on
log_directory = '$LOG'
log_filename = 'primary.log'
log_rotation_age = 0
log_rotation_size = 0
EOF
"$PGBIN/pg_ctl" -D "$P" -l "$LOG/pgctl-primary.log" start -w -s || fail "primary did not start"
STARTED+=("$P")
psqlp <<'SQL' >/dev/null || fail "primary setup SQL"
select pg_create_physical_replication_slot('standby_slot');
create table t (id bigserial primary key, v text);
create table filler (id bigserial primary key, pad text);
create publication pub for table t;
select pg_create_logical_replication_slot('siphon_slot', 'pgoutput', false, false, true);
SQL
for i in $(seq 1 200); do echo "create table c$i (id int primary key, v text); insert into c$i select g, md5(g::text) from generate_series(1,100) g;"; done | psqlp >/dev/null || fail "creating the 200 small tables"

# consumer: acknowledges every second
"$PGBIN/pg_recvlogical" -h localhost -p "$PPORT" -d postgres --slot siphon_slot --start \
  -o proto_version=4 -o publication_names=pub --status-interval=1 --fsync-interval=1 -f /dev/null > "$LOG/consumer.log" 2>&1 &
CONSUMER=$!; CHILDREN+=("$CONSUMER")

# ---- standby -------------------------------------------------------------------------------
"$PGBIN/pg_basebackup" -d "host=localhost port=$PPORT dbname=postgres" -D "$S" -X stream -S standby_slot -R -c fast > "$LOG/basebackup.log" 2>&1 || fail "pg_basebackup, see $LOG/basebackup.log"
grep -q "dbname=postgres" "$S/postgresql.auto.conf" || fail "primary_conninfo lacks dbname, slot sync needs it"
cat >> "$S/postgresql.conf" <<EOF
port = $SPORT
hot_standby = on
hot_standby_feedback = on
sync_replication_slots = on
wal_receiver_status_interval = 1
log_min_messages = debug2
log_line_prefix = '%m [%p] %a '
log_filename = 'standby.log'
EOF
"$PGBIN/pg_ctl" -D "$S" -l "$LOG/pgctl-standby.log" start -w -s || fail "standby did not start"
STARTED+=("$S")
SLOG=$LOG/standby.log

echo "[$(ts)] waiting for the synced copy"
st=""
for i in $(seq 1 60); do
  st=$(psqls -c "select case when synced and not temporary and invalidation_reason is null then 'ready' else 'not ready' end from pg_replication_slots where slot_name='siphon_slot'" 2>/dev/null)
  [ "$st" = "ready" ] && break; sleep 2
done
[ "$st" = "ready" ] || fail "copy never became sync-ready (state: ${st:-no row})"
echo "[$(ts)] copy is synced and persistent"

# ---- workload ------------------------------------------------------------------------------
# WAL and xids (table truncated regularly), pg_statistic churn, overlapping 60 s transactions
( n=0; while true; do
    psqlp -c "insert into filler (pad) select repeat(md5(random()::text), 32) from generate_series(1,1000)" >/dev/null || exit 1
    psqlp -c "insert into t (v) select md5(random()::text) from generate_series(1,100)" >/dev/null || exit 1
    n=$((n+1)); [ $((n % 100)) -eq 0 ] && { psqlp -c "truncate filler" >/dev/null || exit 1; }
  done ) & CHILDREN+=($!); WAL_PID=$!
( while true; do for i in $(seq 1 200); do echo "analyze c$i;"; done | psqlp >/dev/null || exit 1; done ) & CHILDREN+=($!); ANALYZE_PID=$!
( while true; do psqlp -c "begin; insert into t (v) values ('long'); select pg_sleep(60); commit;" >/dev/null 2>&1 & sleep 10; done ) & CHILDREN+=($!); LONG_PID=$!
check_workload() {
  for pid in "$CONSUMER" "$WAL_PID" "$ANALYZE_PID" "$LONG_PID"; do kill -0 "$pid" 2>/dev/null || fail "a workload process or the consumer died (pid $pid), see $LOG"; done
}
sleep 60; check_workload
echo "[$(ts)] workload running, $(psqlp -c "select pg_size_pretty(pg_current_wal_lsn()-'0/0'::pg_lsn)") of WAL so far"

# ---- pause slot sync, let the primary's slot run ahead of the copy ------------------------------
echo "[$(ts)] pausing slot sync for $PAUSE s (the copy stands still, the consumer moves on)"
psqls -c "alter system set sync_replication_slots = off" >/dev/null || fail "alter system"
psqls -c "select pg_reload_conf()" >/dev/null || fail "reload"
n=""
for i in $(seq 1 30); do
  n=$(psqls -c "select count(*) from pg_stat_activity where backend_type = 'slotsync worker'"); [ "$n" = "0" ] && break; sleep 1
done
[ "$n" = "0" ] || fail "slot sync worker did not stop"
before=$(psqls -c "select catalog_xmin from pg_replication_slots where slot_name='siphon_slot'")
sleep "$PAUSE"; check_workload
remote=$(psqlp -c "select catalog_xmin from pg_replication_slots where slot_name='siphon_slot'")
echo "[$(ts)] copy catalog_xmin $before, primary slot catalog_xmin $remote, resuming slot sync"
OFF=$(wc -c < "$SLOG")                    # scan only what the standby logs from here on
since() { tail -c +$((OFF+1)) "$SLOG"; }
psqls -c "alter system set sync_replication_slots = on" >/dev/null || fail "alter system"
psqls -c "select pg_reload_conf()" >/dev/null || fail "reload"

# ---- wait for the invalidation -----------------------------------------------------------------
echo "[$(ts)] waiting up to $WAIT s for an invalidation"
result=1; deadline=$((SECONDS + WAIT))
while [ $SECONDS -lt $deadline ]; do
  if since | grep -F 'invalidating obsolete replication slot "siphon_slot"' >/dev/null; then result=0; break; fi
  check_workload; sleep 5
done
echo
echo "== standby: published catalog_xmin going backward (prev -> cur) since resume"
since | grep "sending hot standby feedback" | awk '{c=$(NF-2)+0; if (p!="" && c>0 && c<p) print "  DROP", $2, p, "->", c; if (c>0) p=c}' | head -5
echo "== standby: key lines since resume"
since | grep -E "starting logical decoding|to release replication slot|conflicted with|invalidating obsolete|dropped replication slot|newly created" | cut -c1-160 | head -12
echo "== copy now"; psqls -c "select slot_name, synced, temporary, catalog_xmin, invalidation_reason from pg_replication_slots"
if [ $result -eq 0 ]; then echo "[$(ts)] RESULT: synced copy INVALIDATED (bug reproduced)"; else echo "[$(ts)] RESULT: no invalidation within $WAIT s"; fi
exit $result
