#!/bin/bash
#
# Reproducer for 0001.  DestroyParallelContext() detaches the DSM segment
# before waiting for the workers to exit, so a worker that is still starting
# up when a parallel query is canceled fails to map the segment or to attach
# to the DSA or the SharedFileSet, and logs an error.
#
# The script cancels a 4 worker parallel hash join with statement_timeout
# set to 1..30 ms, ROUNDS times each, and counts those worker errors in the
# server log.
#
# Usage: detach_order_repro.sh [bindir] [rounds]
#   bindir  directory with initdb, pg_ctl, psql (default: pg_config --bindir)
#   rounds  sweeps of 1..30 ms (default 40, so 1200 canceled queries)
#   PGPORT  TCP port for the throwaway cluster (default 54329)

set -eu
BIN=${1:-$(pg_config --bindir)}
ROUNDS=${2:-40}
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 -c max_worker_processes=16 -c max_parallel_workers=16" \
	start >/dev/null || { cat "$DIR/log"; exit 1; }

echo "## $(psql -X -At -c 'select version()')"
psql -X -q <<'SQL'
CREATE TABLE t AS SELECT g AS id, md5(g::text) AS pad FROM generate_series(1, 300000) g;
ANALYZE t;
ALTER DATABASE postgres SET parallel_setup_cost = 0;
ALTER DATABASE postgres SET parallel_tuple_cost = 0;
ALTER DATABASE postgres SET min_parallel_table_scan_size = 0;
ALTER DATABASE postgres SET max_parallel_workers_per_gather = 4;
SQL
psql -X -At -c "EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, BUFFERS OFF) SELECT count(*) FROM t a JOIN t b USING (id)" |
	grep -E 'Workers Launched|Parallel Hash Join|Execution'

OFF=$(wc -c < "$DIR/log")
for r in $(seq 1 "$ROUNDS"); do for ms in $(seq 1 30); do
	echo "SET statement_timeout = '${ms}ms';"
	echo "SELECT count(*) FROM t a JOIN t b USING (id);"
done; done > "$DIR/run.sql"
psql -X -q -f "$DIR/run.sql" > /dev/null 2> "$DIR/err" || true
sleep 2
tail -c +$((OFF+1)) "$DIR/log" > "$DIR/newlog"

echo "queries canceled: $(grep -c 'statement timeout' "$DIR/err" || true) of $((ROUNDS*30))"
echo "## worker errors in the server log"
for p in 'could not map dynamic shared memory segment' \
         'could not attach to dynamic shared area' \
         'could not attach to a SharedFileSet that is already destroyed'; do
	printf '%6d  %s\n' "$(grep -c "$p" "$DIR/newlog" || true)" "$p"
done
echo "## crashes: $(grep -Ec 'TRAP|PANIC|was terminated by signal' "$DIR/newlog" || true)"
