#!/bin/bash
# Measurements for
#   ERROR: could not resize shared memory segment "/PostgreSQL.NNN" to N bytes:
#          No space left on device                     (SQLSTATE 53100, disk_full)
#
# Starts five containers from one official postgres image, each with a 3 GB
# memory limit and two tables of 3 million rows (about 500 MB per container):
#   <prefix>-shm64    Docker's default /dev/shm (64 MB)
#   <prefix>-shm256   --shm-size=256m
#   <prefix>-shm1g    --shm-size=1g
#   <prefix>-mmap     64 MB /dev/shm, dynamic_shared_memory_type=mmap
#   <prefix>-sysv     64 MB /dev/shm, dynamic_shared_memory_type=sysv
# and runs a parallel hash join under different settings. It prints every
# result, the peak use of /dev/shm, and the error with its SQLSTATE. Nothing is
# published on the host. The containers are removed by name at the end (KEEP=1
# keeps them). An existing container with the same name is replaced; nothing
# else is touched. The password "example" is a test value.
#
#   ./run.sh 2>&1 | tee results.txt
#   IMAGE=postgres:16 PREFIX=pgshm16 ./run.sh 2>&1 | tee results-16.txt
#
# Needs Docker, about 3 GB of disk, a few GB of RAM and 10 to 15 minutes. Byte
# numbers, peaks, timings and how many concurrent sessions fail will be your
# own: the sessions start as separate docker exec calls, so they do not start
# at exactly the same moment.
set -u
PREFIX=${PREFIX:-pgshm}
IMAGE=${IMAGE:-postgres:17}
ALL="shm64 shm256 shm1g mmap sysv"

cleanup() {
  [ "${KEEP:-0}" = 1 ] && return
  for s in $ALL; do docker rm -f -v "$PREFIX-$s" >/dev/null 2>&1; done
}
trap cleanup EXIT

section() { echo; echo "=================== $*"; }

start() { # short [docker args] [-- server args]
  s=$1; shift; dargs=()
  while [ $# -gt 0 ] && [ "$1" != -- ]; do dargs+=("$1"); shift; done
  [ "${1:-}" = -- ] && shift
  docker rm -f -v "$PREFIX-$s" >/dev/null 2>&1
  docker run -d --name "$PREFIX-$s" --memory 3g ${dargs[@]+"${dargs[@]}"} \
    -e POSTGRES_PASSWORD=example "$IMAGE" "$@" >/dev/null
}

ready() { # wait until the image's init has finished and the server answers
  c=$PREFIX-$1; n=0
  until docker logs "$c" 2>&1 | grep -q 'PostgreSQL init process complete' &&
        docker exec "$c" pg_isready -U postgres -q 2>/dev/null; do
    n=$((n+1))
    if [ "$n" -gt 120 ] || [ "$(docker inspect -f '{{.State.Running}}' "$c" 2>/dev/null)" != true ]; then
      echo "container $c did not come up; its log:"; docker logs --tail 20 "$c" 2>&1; exit 1
    fi
    sleep 1
  done
}

restart() {
  docker restart "$PREFIX-$1" >/dev/null
  until docker exec "$PREFIX-$1" pg_isready -U postgres -q 2>/dev/null; do sleep 1; done
}

load() { # two tables of 3 million rows
  docker exec -i "$PREFIX-$1" psql -U postgres -X -q -At <<'SQL'
CREATE TABLE a AS SELECT g AS id, md5(g::text) || md5((g+1)::text) AS pad FROM generate_series(1,3000000) g;
CREATE TABLE b AS SELECT g AS id, md5(g::text) AS pad FROM generate_series(1,3000000) g;
VACUUM ANALYZE a; VACUUM ANALYZE b;
SELECT 'a ' || pg_size_pretty(pg_total_relation_size('a')) || ', b ' || pg_size_pretty(pg_total_relation_size('b'));
SQL
}

# The join, pushed towards a Parallel Hash Join. Prints the count or the error.
q() { # short workers work_mem [hash_mem_multiplier]
  docker exec -i "$PREFIX-$1" psql -U postgres -X -At -v VERBOSITY=terse 2>&1 <<SQL | grep -v '^SET'
SET max_parallel_workers_per_gather = $2; SET work_mem = '$3'; SET hash_mem_multiplier = ${4:-2};
SET enable_mergejoin = off; SET parallel_setup_cost = 0; SET parallel_tuple_cost = 0;
SELECT count(*) FROM a JOIN b USING (id);
SQL
}

grid() { # short [workers...]
  s=$1; shift; ws=${*:-0 1 2 4}
  for w in $ws; do for wm in 4MB 16MB 32MB 64MB 128MB 256MB 1GB; do
    printf '%-8s workers=%s work_mem=%-6s -> %s\n' "$s" "$w" "$wm" "$(q "$s" "$w" "$wm")"
  done; done
}

# Sample /dev/shm (df) and pg_dynshmem (du) inside the container until stopped.
sample_on() {
  docker exec "$PREFIX-$1" sh -c 'rm -f /tmp/pk.log /tmp/pk.stop
    d=$(psql -U postgres -XAtc "show data_directory")
    (while [ ! -f /tmp/pk.stop ]; do
       echo "$(df -k /dev/shm | tail -1 | awk "{print \$3}") $(du -sk $d/pg_dynshmem | cut -f1) $(ls /dev/shm | wc -l)" >> /tmp/pk.log
     done) >/dev/null 2>&1 &'
  sleep 0.3
}
sample_off() {
  sleep 0.3
  docker exec "$PREFIX-$1" sh -c 'touch /tmp/pk.stop; sleep 0.2
    echo "peak /dev/shm used KB: $(sort -n -k1 /tmp/pk.log | tail -1 | cut -d" " -f1)   peak pg_dynshmem KB: $(sort -n -k2 /tmp/pk.log | tail -1 | cut -d" " -f2)   most files in /dev/shm: $(sort -n -k3 /tmp/pk.log | tail -1 | cut -d" " -f3)   samples: $(wc -l < /tmp/pk.log)"'
}

concurrent() { # short sessions workers work_mem
  s=$1; n=$2
  for i in $(seq 1 "$n"); do (echo "session $i: $(q "$s" "$3" "$4")") & done; wait
}

shm() { docker exec "$PREFIX-$1" df -h /dev/shm | tail -1; }

# ---------------------------------------------------------------------------
section "starting $IMAGE five times (prefix $PREFIX)"
start shm64
start shm256 --shm-size=256m
start shm1g  --shm-size=1g
start mmap   -- -c dynamic_shared_memory_type=mmap
start sysv   -- -c dynamic_shared_memory_type=sysv
for s in $ALL; do ready "$s"; done
docker exec "$PREFIX-shm64" psql -U postgres -XAtc 'select version()'
for s in $ALL; do
  printf '%-8s ShmSize=%s  ' "$s" "$(docker inspect -f '{{.HostConfig.ShmSize}}' "$PREFIX-$s")"; shm "$s"
done
docker exec "$PREFIX-shm64" psql -U postgres -XAt -F ' = ' -c "select name, current_setting(name) from pg_settings
  where name in ('dynamic_shared_memory_type','min_dynamic_shared_memory','max_parallel_workers_per_gather',
                 'work_mem','hash_mem_multiplier','shared_buffers') order by name"

section "loading 2 x 3 million rows into each container"
for s in $ALL; do (echo "$s: $(load "$s")") & done; wait

section "plan (shm1g, work_mem 1GB, 2 workers)"
docker exec -i "$PREFIX-shm1g" psql -U postgres -X -At <<'SQL' | grep -v '^SET'
SET max_parallel_workers_per_gather = 2; SET work_mem = '1GB';
SET enable_mergejoin = off; SET parallel_setup_cost = 0; SET parallel_tuple_cost = 0;
EXPLAIN (COSTS OFF) SELECT count(*) FROM a JOIN b USING (id);
SQL

# ---------------------------------------------------------------------------
section "1. the error in 64 MB: SQLSTATE, location, and the session afterwards"
docker exec -i "$PREFIX-shm64" psql -U postgres -X <<'SQL' 2>&1 | grep -v '^SET'
\set VERBOSITY verbose
SET max_parallel_workers_per_gather = 2; SET work_mem = '1GB';
SET enable_mergejoin = off; SET parallel_setup_cost = 0; SET parallel_tuple_cost = 0;
\timing on
SELECT count(*) FROM a JOIN b USING (id);
\timing off
SELECT 'session still alive' AS after_error, pg_backend_pid() > 0 AS ok;
\echo LAST_ERROR_SQLSTATE = :LAST_ERROR_SQLSTATE
SQL
echo "-- server log, last lines:"
docker logs "$PREFIX-shm64" 2>&1 | grep -E 'could not resize|parallel worker' | tail -6

section "2. work_mem x workers in 64 MB"
grid shm64

section "3. /dev/shm during and after the error (work_mem 1GB, 2 workers)"
echo "before: $(shm shm64)"
sample_on shm64
q shm64 2 1GB
sample_off shm64
echo "after:  $(shm shm64)"

section "4. the same failing query five times"
for i in 1 2 3 4 5; do echo "run $i: $(q shm64 2 1GB)"; done
section "4b. work_mem 8MB, 2 workers: alone, then four sessions at once (3 rounds)"
echo "alone: $(q shm64 2 8MB)"
for r in 1 2 3; do echo "round $r:"; concurrent shm64 4 2 8MB; done
echo "after:  $(shm shm64)"
section "4c. the defaults (work_mem 4MB, 2 workers): four sessions at once (3 rounds)"
for r in 1 2 3; do echo "round $r:"; concurrent shm64 4 2 4MB; done

section "5. hash_mem_multiplier 2 and 1 (work_mem 16MB, 2 workers)"
for h in 2 1; do echo "hash_mem_multiplier=$h -> $(q shm64 2 16MB $h)"; done

section "6. a parallel B-tree build in 64 MB (4 workers, maintenance_work_mem 1GB)"
sample_on shm64
docker exec -i "$PREFIX-shm64" psql -U postgres -X <<'SQL' 2>&1 | grep -v '^SET'
SET max_parallel_maintenance_workers = 4; SET maintenance_work_mem = '1GB';
SET client_min_messages = debug1;
CREATE INDEX a_pad_idx ON a (pad);
RESET client_min_messages;
DROP INDEX a_pad_idx;
SQL
sample_off shm64

# ---------------------------------------------------------------------------
section "7. --shm-size=256m and --shm-size=1g"
grid shm256 1 2 4
grid shm1g 1 2 4
for s in shm256 shm1g; do
  echo "-- $s: one query, work_mem 1GB, up to 4 workers"
  sample_on "$s"; echo "session 1: $(q "$s" 4 1GB)"; sample_off "$s"
  for r in 1 2 3; do
    echo "-- $s: four sessions at once, work_mem 1GB, 2 workers (round $r)"
    sample_on "$s"; concurrent "$s" 4 2 1GB; sample_off "$s"
  done
done

section "8. dynamic_shared_memory_type mmap and sysv (64 MB /dev/shm)"
grid mmap 1 2 4
grid sysv 1 2 4
for s in mmap sysv; do
  echo "-- $s: one query, work_mem 1GB, up to 4 workers"
  sample_on "$s"; echo "session 1: $(q "$s" 4 1GB)"; sample_off "$s"
done
docker exec "$PREFIX-sysv" sh -c 'echo "kernel.shmmax=$(cat /proc/sys/kernel/shmmax) kernel.shmall=$(cat /proc/sys/kernel/shmall)"'
echo "-- time, work_mem 1GB, 2 workers, 3 runs each"
for s in shm1g mmap sysv; do
  for i in 1 2 3; do
    t=$(docker exec -i "$PREFIX-$s" psql -U postgres -X -At 2>&1 <<'SQL' | grep -E 'Time|ERROR'
SET max_parallel_workers_per_gather = 2; SET work_mem = '1GB';
SET enable_mergejoin = off; SET parallel_setup_cost = 0; SET parallel_tuple_cost = 0;
\timing on
SELECT count(*) FROM a JOIN b USING (id);
SQL
)
    echo "$s run $i: $t"
  done
done

# ---------------------------------------------------------------------------
section "9. not the lock table: shared_buffers 1GB and max_locks_per_transaction 10000 in 64 MB"
docker exec "$PREFIX-shm64" psql -U postgres -XAtq -c "ALTER SYSTEM SET shared_buffers = '1GB'" \
  -c "ALTER SYSTEM SET max_locks_per_transaction = 10000"
restart shm64
docker exec "$PREFIX-shm64" psql -U postgres -XAt -c "select name, setting, unit from pg_settings where name in
  ('shared_buffers','max_locks_per_transaction','shared_memory_size','shared_memory_type') order by name"
shm shm64
q shm64 2 1GB
docker exec "$PREFIX-shm64" psql -U postgres -XAtq -c "ALTER SYSTEM RESET shared_buffers" \
  -c "ALTER SYSTEM RESET max_locks_per_transaction"
restart shm64

section "10. min_dynamic_shared_memory = 256MB in 64 MB /dev/shm (on $IMAGE)"
docker exec "$PREFIX-shm64" psql -U postgres -XAtq -c "ALTER SYSTEM SET min_dynamic_shared_memory = '256MB'"
restart shm64
docker exec "$PREFIX-shm64" psql -U postgres -XAtc 'show min_dynamic_shared_memory'
shm shm64
for w in 2 4; do for wm in 16MB 1GB; do
  echo "workers=$w work_mem=$wm -> $(q shm64 "$w" "$wm")"
done; done
echo "-- four sessions at once, work_mem 1GB, 2 workers"
sample_on shm64; concurrent shm64 4 2 1GB; sample_off shm64
docker exec "$PREFIX-shm64" psql -U postgres -XAtq -c "ALTER SYSTEM RESET min_dynamic_shared_memory"
restart shm64
echo "after reset: $(q shm64 2 1GB)"

section "done"
