#!/bin/bash
#
# A statement_timeout that fires while a successful parallel hash join is
# cleaning up (dsm_detach() deleting its temp files with interrupts held)
# makes the NEXT statement fail with "canceling statement due to statement
# timeout".
#
# Default settings except statement_timeout.  A 3M row self join spills into
# batches, and the timeout is swept across +-30% of its run time.  The script
# counts trivial "SELECT 'marker'" queries that fail right after a join that
# returned its result.
#
# Usage: stray_timeout_repro.sh [bindir] [tries]
#   bindir  directory with initdb, pg_ctl, psql (default: pg_config --bindir)
#   tries   join + marker pairs (default 120)
#   PGPORT  TCP port for the throwaway cluster (default 54329)

set -eu
BIN=${1:-$(pg_config --bindir)}
N=${2:-120}
PORT=${PGPORT:-54329}
PATH=$BIN:$PATH
export PGHOST=localhost PGPORT=$PORT PGDATABASE=postgres
export LC_ALL=${LC_ALL:-C}	# macOS with an empty LANG refuses to start

DIR=$(mktemp -d)
cleanup() {
	pg_ctl -D "$DIR/data" -m immediate stop >/dev/null 2>&1 || true
	rm -rf "$DIR"
}
trap cleanup EXIT

initdb -D "$DIR/data" >/dev/null
pg_ctl -D "$DIR/data" -l "$DIR/log" -w \
	-o "-p $PORT -c listen_addresses=localhost" start >/dev/null ||
	{ cat "$DIR/log"; exit 1; }

echo "## $(psql -X -At -c 'select version()')"
psql -X -q -c "CREATE TABLE big AS SELECT g AS id, md5(g::text) AS pad FROM generate_series(1, 3000000) g" \
	-c "ANALYZE big"
Q="SELECT count(*) FROM big a JOIN big b USING (id)"
psql -X -At -c "EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, BUFFERS OFF) $Q" |
	grep -E 'Workers Launched|Batches|Execution'

# fastest of five runs, in ms (the minimum is less sensitive to a busy machine)
D=$(for i in 1 2 3 4 5; do
	psql -X -At -c '\timing on' -c "$Q" | awk '/^Time/ {print int($2)}'
done | sort -n | head -1)
echo "## join takes ${D} ms, statement_timeout swept from $((D*70/100)) to $((D*130/100)) ms"

# Line L of the script: L%3==1 SET, L%3==2 join, L%3==0 marker.
SQL=$DIR/run.sql
for i in $(seq 1 "$N"); do
	ms=$(( D*70/100 + (D*60/100) * (i-1) / (N-1) ))
	echo "SET statement_timeout = '${ms}ms';"
	echo "$Q;"
	echo "SELECT 'marker $ms' AS m;"
done > "$SQL"
psql -X -At -f "$SQL" > "$DIR/out" 2> "$DIR/err" || true

# "line error" for every error, then keep markers whose join did not fail.
sed -nE 's/.*:([0-9]+): (ERROR.*)/\1 \2/p' "$DIR/err" > "$DIR/errs"
awk '$1%3==2 {bad[$1]=1} $1%3==0 && !(($1-1) in bad)' "$DIR/errs" > "$DIR/victims"
echo "joins canceled:                 $(awk '$1%3==2' "$DIR/errs" | wc -l | tr -d ' ') of $N"
echo "markers failed after a success: $(wc -l < "$DIR/victims" | tr -d ' ') of $N"
echo "## first failed markers"
head -3 "$DIR/victims" |
while read -r L rest; do
	echo "  $(sed -n "$((L-1))p" "$SQL")  -- returned a count"
	echo "  $(sed -n "${L}p" "$SQL")"
	echo "  $rest"
done
