#!/usr/bin/env bash # Verification for: tune-table-join-buffer # Self-contained. Prints PASS / FAIL / SKIP per claim, AND re-runs the benchmark # whose numbers appear in the article, so you can compare against your own hardware. # # Scratch schema: hw_rw_joinbuf_. Rows are deleted at the end; the empty schema is # left behind because the environment this was written in blocks DROP DATABASE. The exact # cleanup command is printed at the end. # # Override the client with: MYSQL_CMD="mysql -u root -p'...' -h 127.0.0.1" ./verify-...sh # Shorten the run with: ITERS=3 ./verify-...sh set -u PASS=0; FAIL=0; SKIP=0 ok() { echo "PASS $*"; PASS=$((PASS+1)); } no() { echo "FAIL $*"; FAIL=$((FAIL+1)); } skip() { echo "SKIP $*"; SKIP=$((SKIP+1)); } MYSQL_CMD="${MYSQL_CMD:-mysql -u root}" ITERS="${ITERS:-7}" ROWS="${ROWS:-200000}" DISTINCT="${DISTINCT:-5000}" DB="hw_rw_joinbuf_$$" SCRATCH="$(mktemp -d "${TMPDIR:-/tmp}/hw_rw_jb.XXXXXX")" cleanup() { rm -rf "$SCRATCH"; } trap cleanup EXIT M() { $MYSQL_CMD "$@"; } MD() { $MYSQL_CMD "$DB" "$@"; } echo "=== join_buffer_size — claim verification + benchmark ===" echo "date: $(date -u '+%Y-%m-%dT%H:%M:%SZ') host: $(uname -srm)" echo if ! M -e 'SELECT 1' >/dev/null 2>&1; then echo "FATAL: cannot connect with: $MYSQL_CMD" exit 2 fi # --------------------------------------------------------------------------- # CLAIM 0: environment facts the article states. # --------------------------------------------------------------------------- VER="$(M -N -B -e 'SELECT VERSION()')" BP="$(M -N -B -e 'SELECT @@innodb_buffer_pool_size')" JBDEF="$(M -N -B -e 'SELECT @@GLOBAL.join_buffer_size')" echo " server: MySQL $VER innodb_buffer_pool_size=$BP global join_buffer_size=$JBDEF" case "$VER" in 8.0.2[0-9]*|8.0.[3-9]*|8.[1-9]*|9.*) ok "C0 server is $VER — 8.0.20 or later, so hash join is the block-nested-loop replacement" ;; *) skip "C0 server is $VER — the article describes 8.0.20+ behaviour" ;; esac # --------------------------------------------------------------------------- # Build the dataset. # --------------------------------------------------------------------------- echo " building dataset: 2 x $ROWS rows, $DISTINCT distinct join keys, no index on the join column..." M -e "CREATE DATABASE IF NOT EXISTS $DB;" MD -e " CREATE TABLE IF NOT EXISTS orders_a (id INT NOT NULL, k INT NOT NULL, pad CHAR(40) NOT NULL, PRIMARY KEY (id)) ENGINE=InnoDB; CREATE TABLE IF NOT EXISTS orders_b (id INT NOT NULL, k INT NOT NULL, pad CHAR(40) NOT NULL, PRIMARY KEY (id)) ENGINE=InnoDB;" MD -e "DELETE FROM orders_a WHERE id > 0; DELETE FROM orders_b WHERE id > 0;" MD -e " SET SESSION cte_max_recursion_depth = 100000000; INSERT INTO orders_a (id, k, pad) WITH RECURSIVE n(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM n WHERE x < $ROWS) SELECT x, (x % $DISTINCT) + 1, RPAD(CONCAT('a', x), 40, '.') FROM n; INSERT INTO orders_b (id, k, pad) WITH RECURSIVE n(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM n WHERE x < $ROWS) SELECT x, ((x * 7919) % $DISTINCT) + 1, RPAD(CONCAT('b', x), 40, '.') FROM n;" CNT="$(MD -N -B -e 'SELECT (SELECT COUNT(*) FROM orders_a), (SELECT COUNT(*) FROM orders_b), (SELECT COUNT(DISTINCT k) FROM orders_a)')" echo " a_rows/b_rows/distinct_keys: $CNT" # --------------------------------------------------------------------------- # CLAIM 1: an unindexed equi-join uses a hash join, NOT a "sort-merge join". # --------------------------------------------------------------------------- MD --vertical -e "EXPLAIN FORMAT=TREE SELECT COUNT(*) FROM orders_a a JOIN orders_b b ON a.k = b.k" > "$SCRATCH/plan.txt" 2>&1 if grep -qi 'hash join' "$SCRATCH/plan.txt"; then ok "C1 unindexed equi-join plan is: $(grep -i 'hash join' "$SCRATCH/plan.txt" | sed 's/^ *//' | head -1)" else no "C1 no hash join in the plan:"; sed 's/^/ /' "$SCRATCH/plan.txt" fi if grep -qi 'sort.merge' "$SCRATCH/plan.txt"; then no "C2 the plan mentions a sort-merge join" else ok "C2 the plan contains no 'sort-merge join' — MySQL has never implemented one" fi # --------------------------------------------------------------------------- # CLAIM 3: the MySQL manual's join pages never mention a sort-merge join. # --------------------------------------------------------------------------- # Doc pages embed markup mid-sentence, so strip tags before matching prose. detag() { python3 -c 'import sys,re,html; t=html.unescape(re.sub(r"<[^>]+>"," ",sys.stdin.read())); print(re.sub(r"\s+"," ",t))'; } HITS=0; NET_OK=1 for U in https://dev.mysql.com/doc/refman/8.4/en/nested-loop-joins.html \ https://dev.mysql.com/doc/refman/8.4/en/hash-joins.html \ https://dev.mysql.com/doc/refman/8.4/en/bnl-bka-optimization.html; do PAGE="$(curl -s --max-time 25 "$U" || true)" [ -z "$PAGE" ] && { NET_OK=0; break; } N="$(printf '%s' "$PAGE" | detag | grep -oci 'sort.merge' || true)" HITS=$((HITS + N)) done if [ "$NET_OK" -eq 0 ]; then skip "C3 MySQL manual grep for 'sort-merge' (needs network)" elif [ "$HITS" -eq 0 ]; then ok "C3 'sort-merge' appears 0 times across the MySQL 8.4 manual's three join-algorithm pages" else no "C3 'sort-merge' appears $HITS times in the MySQL join docs" fi # --------------------------------------------------------------------------- # CLAIM 4: block nested loop was removed as a join algorithm in 8.0.20 (documented). # --------------------------------------------------------------------------- BNL="$(curl -s --max-time 25 https://dev.mysql.com/doc/refman/8.0/en/bnl-bka-optimization.html | detag || true)" if [ -z "$BNL" ]; then skip "C4 BNL-removal wording (needs network)" elif printf '%s' "$BNL" | grep -qi 'Beginning with MySQL 8.0.20, the flag controls hash joins only, and the block nested loop algorithm is no longer supported'; then ok "C4 manual: 'Beginning with MySQL 8.0.20, the flag controls hash joins only, and the block nested loop algorithm is no longer supported.'" else no "C4 could not find the documented 8.0.20 BNL-removal wording" fi # --------------------------------------------------------------------------- # CLAIM 5: the manual says join_buffer_size caps hash-join memory and that # exceeding it spills to files on disk. # --------------------------------------------------------------------------- HJ="$(curl -s --max-time 25 https://dev.mysql.com/doc/refman/8.4/en/hash-joins.html | detag || true)" if [ -z "$HJ" ]; then skip "C5 hash-join memory wording (needs network)" elif printf '%s' "$HJ" | grep -qi 'a hash join cannot use more memory than this amount'; then ok "C5 manual: join_buffer_size caps hash-join memory; excess is handled 'by using files on disk'" else no "C5 could not find the documented join_buffer_size/hash-join wording" fi # --------------------------------------------------------------------------- # CLAIM 6: adding an index on the join column moves the plan off hash join entirely. # --------------------------------------------------------------------------- MD -e "CREATE INDEX idx_hw_rw_b_k ON orders_b (k);" >/dev/null 2>&1 MD --vertical -e "EXPLAIN FORMAT=TREE SELECT COUNT(*) FROM orders_a a JOIN orders_b b ON a.k = b.k" > "$SCRATCH/plan-idx.txt" 2>&1 if grep -qi 'Nested loop' "$SCRATCH/plan-idx.txt" && grep -qi 'idx_hw_rw_b_k' "$SCRATCH/plan-idx.txt"; then ok "C6 with an index the plan becomes a nested-loop join with an index lookup (no join buffer involved)" else no "C6 unexpected indexed plan:"; sed 's/^/ /' "$SCRATCH/plan-idx.txt" fi MD -e "DROP INDEX idx_hw_rw_b_k ON orders_b;" >/dev/null 2>&1 # --------------------------------------------------------------------------- # CLAIM 7: THE BENCHMARK. Timing is measured inside the server (NOW(6) brackets), # so client connect time is excluded. Warmup run, then $ITERS timed runs, # median reported. Created_tmp_files delta shows hash-join spill. # --------------------------------------------------------------------------- echo echo " --- benchmark: SELECT COUNT(*) FROM orders_a a JOIN orders_b b ON a.k = b.k ---" echo " $ITERS timed iterations per size after one warmup; median reported." printf ' %-18s %10s %10s %10s %18s\n' "join_buffer_size" "median_ms" "min_ms" "max_ms" "Created_tmp_files" Q="SELECT COUNT(*) INTO @c FROM orders_a a JOIN orders_b b ON a.k = b.k;" RESULTS="$SCRATCH/results.txt" : > "$RESULTS" for KB in 128 256 512 1024 2048 4096 8192 16384 65536; do B=$((KB*1024)) MD -N -B -e "SET SESSION join_buffer_size=$B; $Q" >/dev/null 2>&1 # warmup TF_BEFORE="$(M -N -B -e "SHOW GLOBAL STATUS LIKE 'Created_tmp_files'" | awk '{print $2}')" : > "$SCRATCH/times.txt" I=1 while [ "$I" -le "$ITERS" ]; do MD -N -B -e "SET SESSION join_buffer_size=$B; SET @t0=NOW(6); $Q SELECT ROUND(TIMESTAMPDIFF(MICROSECOND,@t0,NOW(6))/1000,1);" >> "$SCRATCH/times.txt" 2>/dev/null I=$((I+1)) done TF_AFTER="$(M -N -B -e "SHOW GLOBAL STATUS LIKE 'Created_tmp_files'" | awk '{print $2}')" TF=$(( (TF_AFTER - TF_BEFORE) / ITERS )) sort -n "$SCRATCH/times.txt" > "$SCRATCH/sorted.txt" MED="$(awk -v n="$ITERS" 'NR==int((n+1)/2)' "$SCRATCH/sorted.txt")" MIN="$(head -1 "$SCRATCH/sorted.txt")" MAX="$(tail -1 "$SCRATCH/sorted.txt")" printf ' %-18s %10s %10s %10s %18s\n' "${KB}KB" "$MED" "$MIN" "$MAX" "$TF" echo "$KB $MED $TF" >> "$RESULTS" done SMALL_MED="$(awk '$1==128 {print $2}' "$RESULTS")" BIG_MED="$(awk '$1==65536 {print $2}' "$RESULTS")" SMALL_TF="$(awk '$1==128 {print $3}' "$RESULTS")" BIG_TF="$(awk '$1==65536 {print $3}' "$RESULTS")" echo if [ "${SMALL_TF:-0}" -gt 0 ] && [ "${BIG_TF:-1}" -eq 0 ]; then ok "C7 hash join spills to disk at 128KB ($SMALL_TF temp files per run) and not at 64MB ($BIG_TF) — this is the mechanism" else no "C7 spill pattern not as described: 128KB=$SMALL_TF files, 64MB=$BIG_TF files" fi DELTA="$(awk -v a="$SMALL_MED" -v b="$BIG_MED" 'BEGIN{ if (a>0) printf "%.1f", (a-b)/a*100; else print "NA" }')" echo " total improvement from 128KB to 64MB on this run: ${DELTA}% (${SMALL_MED}ms -> ${BIG_MED}ms)" IS_SMOOTH22="$(awk -v d="$DELTA" 'BEGIN{ print (d>=20 && d<=24) ? "yes" : "no" }')" if [ "$IS_SMOOTH22" = "no" ]; then ok "C8 the improvement is NOT the ~22% smooth curve the old article tabulated (measured ${DELTA}%)" else skip "C8 measured ${DELTA}% here — close to the old article's 22%; check whether the CURVE is smooth or a single step" fi # --------------------------------------------------------------------------- # Cleanup. # --------------------------------------------------------------------------- MD -e "DELETE FROM orders_a WHERE id > 0; DELETE FROM orders_b WHERE id > 0;" >/dev/null 2>&1 echo " (rows deleted; empty schema left behind. Remove with: $MYSQL_CMD -e 'DROP DATABASE $DB;')" echo echo "=== summary: $PASS passed, $FAIL failed, $SKIP skipped ===" [ "$FAIL" -eq 0 ]