#!/bin/bash
# Noah Misch's 2012 reproducer (pgsql-hackers, "Disabled features on Hot
# Standby", <20120114111719.GA1081@tornado.leadboat.com>), run with each
# table-rewriting command: a hot standby without hot_standby_feedback, a
# REPEATABLE READ snapshot taken there before a DELETE on the primary, then
# a rewrite on the primary. Prints one line per case: the command, the rows
# deleted, how the primary read the old heap (from the command's VERBOSE
# output), and the row count the standby snapshot got or the error that
# ended its session.
# Usage: standby.sh <bindir> <workdir> <port>
set -euo pipefail
BIN=$1; W=$2; P=$3; S=$((P + 1))
export PATH=$BIN:$PATH PGHOST=/tmp PGDATABASE=postgres
rm -rf "$W"; mkdir -p "$W"
initdb -A trust -D "$W/primary" >/dev/null
pg_ctl -s -D "$W/primary" -l "$W/primary.log" \
    -o "-p $P -k /tmp -c listen_addresses='' -c autovacuum=off" start
pg_basebackup -p $P -D "$W/standby" -R
pg_ctl -s -D "$W/standby" -l "$W/standby.log" \
    -o "-p $S -k /tmp -c listen_addresses='' -c hot_standby_feedback=off" start
trap 'pg_ctl -s -D "$W/standby" -m immediate stop; pg_ctl -s -D "$W/primary" -m immediate stop' EXIT

# Run SQL on the primary, then wait until the standby has replayed it.
cat > "$W/on_primary" <<EOF
#!/bin/bash
set -e
psql -XAtq -p $P -v ON_ERROR_STOP=1 -c "\$1"
lsn=\$(psql -XAt -p $P -c 'SELECT pg_current_wal_lsn()')
until [ "\$(psql -XAt -p $S -c "SELECT pg_last_wal_replay_lsn() >= '\$lsn'")" = t ]; do sleep 0.1; done
EOF
chmod +x "$W/on_primary"

postgres --version
echo "standby: hot_standby_feedback = $(psql -XAt -p $S -c 'SHOW hot_standby_feedback')"
echo
printf '%-35s %-10s %-27s %s\n' "rewrite on the primary" "deleted" "old heap read by" "standby count(*)"

# Each table has a primary key on n. t1 to t4 hold 1000 rows in key order,
# 226 to a page, so rows 1 to 10 are on a full page and rows 991 to 1000 on
# the last page, which is less than half full. t5 holds 100000 wider rows
# in random order, for which CLUSTER chooses a sequential scan and sort.
while IFS='|' read -r t rows cols order del cmd; do
    "$W/on_primary" "CREATE TABLE $t AS SELECT $cols FROM generate_series(1, $rows) g(n) ORDER BY $order; ALTER TABLE $t ADD PRIMARY KEY (n)"
    # Clean up dead catalog rows first: their removal would otherwise
    # cancel the standby session with a recovery conflict.
    "$W/on_primary" "VACUUM (ANALYZE)"
    if out=$(psql -XAtq -p $S -v ON_ERROR_STOP=1 2>"$W/err" <<SQL
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT 0 \g /dev/null
\! "$W/on_primary" 'DELETE FROM $t WHERE $del'
\! "$W/on_primary" '$cmd'
SELECT count(*) FROM $t;
COMMIT;
SQL
    ); then
        res="$out of $rows"
        [ "$out" = "$rows" ] || res="$res  <-- wrong result, no error"
    else
        res=$(grep -m1 -E '^(ERROR|FATAL)' "$W/err" || head -n1 "$W/err")
    fi
    how=$(grep -m1 -oE '(using index scan|using sequential scan and sort|in physical order)' "$W/err" || echo '?')
    printf '%-35s %-10s %-27s %s\n' "$cmd" "$del" "${how#using }" "$res"
done <<'CASES'
t1|1000|n|n|n <= 10|VACUUM (FULL, VERBOSE) t1
t2|1000|n|n|n <= 10|REPACK (VERBOSE) t2
t3|1000|n|n|n <= 10|CLUSTER (VERBOSE) t3 USING t3_pkey
t4|1000|n|n|n > 990|CLUSTER (VERBOSE) t4 USING t4_pkey
t5|100000|n, repeat($$x$$, 200) AS pad|random()|n <= 10|CLUSTER (VERBOSE) t5 USING t5_pkey
CASES
