#!/usr/bin/env bash
#
# Concurrency benchmark for the GiST intrapage-indexing (skip tuples) patch.
# Answers the review question: do concurrent inserts descending THROUGH a skip
# tuple hurt lock contention, throughput, or bloat, versus plain GiST?
#
# For each build it: preloads a GiST index, then runs N concurrent clients each
# inserting single rows (pgbench, fixed transaction count so both builds do the
# same work), while a background sampler polls pg_stat_activity wait events.
# Reports: overall time + tps, index size growth (bloat) via pgstattuple, and a
# wait-event histogram (lock contention).
#
# Portable bash 3.2+. Private cluster on a Unix socket; cleans up on exit.
#
# USAGE: concurrency_bench.sh BASE_BINDIR TEST_BINDIR [PRELOAD] [CLIENTS] [TXNS_PER_CLIENT]
#   defaults: PRELOAD=3000000  CLIENTS=8  TXNS_PER_CLIENT=100000
#   (so CLIENTS*TXNS_PER_CLIENT single-row inserts total per build)
#
# ENV: KEYRANGE (default 1000000) is the coordinate range each client inserts
#   into. Set it small (e.g. KEYRANGE=2000) for a HOTSPOT run where every client
#   funnels into the same subtree / internal page / skip group -- the adversarial
#   case for "concurrent inserts through the same skip tuple".
#
set -u
KEYRANGE=${KEYRANGE:-1000000}
BASE_BIN=${1:?usage: concurrency_bench.sh BASE_BINDIR TEST_BINDIR [PRELOAD] [CLIENTS] [TXNS]}
TEST_BIN=${2:?need TEST_BINDIR}
PRELOAD=${3:-3000000}; CLIENTS=${4:-8}; TXNS=${5:-100000}

PGBIN=""; DATADIR=""; SAMPLER_PID=""
cleanup() {
  [ -n "$SAMPLER_PID" ] && kill "$SAMPLER_PID" 2>/dev/null
  [ -n "$DATADIR" ] && [ -d "$DATADIR" ] && {
    "$PGBIN/pg_ctl" -D "$DATADIR" -m immediate -w stop >/dev/null 2>&1
    rm -rf "$DATADIR"
  }
}
trap cleanup EXIT INT TERM

run_one() {   # run_one BINDIR LABEL
  PGBIN="$1"; local LABEL="$2"
  local PORT=7400
  while [ -e "/tmp/.s.PGSQL.$PORT" ]; do PORT=$((PORT+1)); done
  DATADIR=$(mktemp -d /tmp/gistconc.XXXXXX)
  export PATH="$PGBIN:$PATH" DYLD_LIBRARY_PATH="$PGBIN/../lib" LD_LIBRARY_PATH="$PGBIN/../lib"
  export PGHOST=/tmp PGPORT=$PORT PGDATABASE=bench PSQLRC=/dev/null
  initdb -D "$DATADIR" -A trust >/dev/null 2>&1
  cat >>"$DATADIR/postgresql.conf" <<EOC
port=$PORT
unix_socket_directories='/tmp'
listen_addresses=''
shared_buffers=2GB
max_connections=64
autovacuum=off
jit=off
fsync=off
wal_level=replica
max_wal_size=32GB
checkpoint_timeout=1h
track_activities=on
EOC
  pg_ctl -D "$DATADIR" -w start >/dev/null 2>&1; createdb bench 2>/dev/null
  psql -q bench -c "CREATE EXTENSION IF NOT EXISTS pgstattuple" >/dev/null 2>&1
  psql -q bench -c "CREATE EXTENSION IF NOT EXISTS pageinspect" >/dev/null 2>&1
  # preload + index (random 2D points: inserts spread across the tree, so many
  # clients descend through internal pages / skip tuples concurrently)
  psql -q bench <<SQL
CREATE TABLE t (p point);
INSERT INTO t SELECT point(random()*1e6, random()*1e6) FROM generate_series(1,$PRELOAD);
CREATE INDEX t_g ON t USING gist (p);
SQL
  psql -q bench -c "CHECKPOINT" >/dev/null 2>&1
  local sz0; sz0=$(psql -Atq bench -c "SELECT pg_relation_size('t_g')")
  cat >"$DATADIR/ins.sql" <<EOF
\\set x random(0, $KEYRANGE)
\\set y random(0, $KEYRANGE)
INSERT INTO t VALUES (point(:x, :y));
EOF

  # background wait-event sampler (lock contention)
  local SAMP="$DATADIR/waits.txt"; : >"$SAMP"
  ( while :; do
      psql -Atq bench -c "SELECT coalesce(wait_event_type||':'||wait_event,'Running') FROM pg_stat_activity WHERE state='active' AND backend_type='client backend' AND pid<>pg_backend_pid()" 2>/dev/null
      perl -e 'select(undef,undef,undef,0.02)' 2>/dev/null || sleep 1
    done ) >>"$SAMP" 2>/dev/null &
  SAMPLER_PID=$!

  # the concurrent insert run (fixed txns/client -> same work on both builds)
  local s e secs tps
  s=$(date +%s.%N)
  pgbench -n -c "$CLIENTS" -j "$CLIENTS" -t "$TXNS" -f "$DATADIR/ins.sql" bench >"$DATADIR/pgb.out" 2>&1
  e=$(date +%s.%N)
  kill "$SAMPLER_PID" 2>/dev/null; SAMPLER_PID=""
  secs=$(echo "$s $e" | awk '{printf "%.2f", $2-$1}')
  tps=$(awk '/including connections|tps =/{if($0 ~ /tps/){print $3; exit}}' "$DATADIR/pgb.out")

  psql -q bench -c "CHECKPOINT" >/dev/null 2>&1
  local sz1 bloat shape grew
  sz1=$(psql -Atq bench -c "SELECT pg_relation_size('t_g')")
  grew=$(awk -v a="$sz0" -v b="$sz1" 'BEGIN{printf "%.1f", (b-a)/1048576}')
  # bloat: free space % within the index (pgstattuple)
  bloat=$(psql -Atq bench -c "SELECT round(free_percent::numeric,1) FROM pgstattuple('t_g')" 2>/dev/null)
  # leaf/internal page counts after the run
  shape=$(psql -Atq bench -c "WITH lv AS (SELECT (gist_page_opaque_info(get_raw_page('t_g', b::int))).flags f FROM generate_series(0, pg_relation_size('t_g')/8192 - 1) b) SELECT count(*) FILTER (WHERE f @> ARRAY['leaf'])||'/'||count(*) FILTER (WHERE NOT f @> ARRAY['leaf']) FROM lv" 2>/dev/null)
  # wait histogram (top 6)
  local waits totsamp
  waits=$(sort "$SAMP" | uniq -c | sort -rn | head -6 | awk '{printf "%s=%d ", $2, $1}')
  totsamp=$(wc -l <"$SAMP" | tr -d ' ')

  echo "RESULT-CONC $LABEL: clients=$CLIENTS txns/cl=$TXNS inserts=$((CLIENTS*TXNS))"
  echo "   time=${secs}s  tps=${tps}"
  echo "   idx: ${sz0}B -> ${sz1}B  (grew ${grew}MB)  free%=${bloat}  leaf/internal(after)=${shape}"
  echo "   waits(${totsamp} samples): ${waits}"

  pg_ctl -D "$DATADIR" -m immediate -w stop >/dev/null 2>&1
  rm -rf "$DATADIR"; DATADIR=""
}

echo "== GiST intrapage concurrency A/B  (preload=$PRELOAD clients=$CLIENTS txns/client=$TXNS keyrange=$KEYRANGE) =="
run_one "$BASE_BIN" base
run_one "$TEST_BIN" gist
