1
0

ab.sh 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. #!/usr/bin/env bash
  2. #
  3. # A/B throughput comparison between two git refs.
  4. #
  5. # Usage: ./ab.sh [--base REF] [--head REF] [--rounds N] [--duration S]
  6. # [--connections N] [--threads N] [--path PATH] [--tls]
  7. # [--large-mib N] [--timeout S] [--no-keep-alive]
  8. #
  9. # --path selects the workload. The harness serves:
  10. # / small body via set_content(); the response line, the
  11. # headers and the body already share a single write(), so
  12. # this is the least sensitive case
  13. # /large large body via set_content()
  14. # /static/small.js 1 KiB file from a mount point, where the headers and the
  15. # body are two separate writes
  16. # /static/large.bin same, with the body large enough to dominate
  17. #
  18. # --large-mib sizes the two large workloads (default 1).
  19. #
  20. # --tls runs the same workload over HTTPS, which writes through
  21. # SSLSocketStream instead of SocketStream.
  22. #
  23. # --no-keep-alive opens a new connection for every request, which measures
  24. # the cost of accepting and setting up a connection.
  25. #
  26. # --timeout is bombardier's per-request timeout. Its 2s default aborts large
  27. # TLS responses, and the run then fails on the non-2xx check.
  28. #
  29. # Absolute numbers from a single run are meaningless: on a quiet 8-core laptop
  30. # the same binary varies by +/-20% run to run, and shared CI runners are worse.
  31. # So both refs are built and then measured alternately in the same session, and
  32. # only the ratio of the medians is reported.
  33. #
  34. # Requires: bombardier, python3, g++ (or $CXX), git.
  35. set -euo pipefail
  36. BASE_REF="master"
  37. HEAD_REF="HEAD"
  38. ROUNDS=5
  39. DURATION="5s"
  40. CONNECTIONS=10
  41. THREADS=""
  42. PORT=8080
  43. REQ_PATH="/"
  44. TLS=0
  45. LARGE_MIB=1
  46. TIMEOUT="30s"
  47. NO_KEEP_ALIVE=0
  48. while [ $# -gt 0 ]; do
  49. case "$1" in
  50. --base) BASE_REF="$2"; shift 2 ;;
  51. --head) HEAD_REF="$2"; shift 2 ;;
  52. --rounds) ROUNDS="$2"; shift 2 ;;
  53. --duration) DURATION="$2"; shift 2 ;;
  54. --connections) CONNECTIONS="$2"; shift 2 ;;
  55. --threads) THREADS="$2"; shift 2 ;;
  56. --path) REQ_PATH="$2"; shift 2 ;;
  57. --large-mib) LARGE_MIB="$2"; shift 2 ;;
  58. --timeout) TIMEOUT="$2"; shift 2 ;;
  59. --tls) TLS=1; shift ;;
  60. --no-keep-alive) NO_KEEP_ALIVE=1; shift ;;
  61. *) echo "Unknown option: $1" >&2; exit 1 ;;
  62. esac
  63. done
  64. # bombardier's default fasthttp client ignores -a, so close each connection
  65. # with the request header instead.
  66. CLOSE_HEADER=()
  67. if [ "$NO_KEEP_ALIVE" -eq 1 ]; then CLOSE_HEADER=(-H "Connection: close"); fi
  68. command -v bombardier >/dev/null || { echo "Error: bombardier not found" >&2; exit 1; }
  69. command -v python3 >/dev/null || { echo "Error: python3 not found" >&2; exit 1; }
  70. REPO_ROOT=$(git rev-parse --show-toplevel)
  71. CXX=${CXX:-g++}
  72. # Default the thread pool to the core count. The committed benchmark Makefile
  73. # hardcodes 16, which heavily oversubscribes a 2-4 vCPU CI runner and inflates
  74. # the variance we are trying to see through.
  75. if [ -z "$THREADS" ]; then
  76. THREADS=$(python3 -c 'import os; print(os.cpu_count() or 4)')
  77. fi
  78. WORKDIR=$(mktemp -d)
  79. cleanup() {
  80. pkill -f "$WORKDIR/.*/server-ab" 2>/dev/null || true
  81. git -C "$REPO_ROOT" worktree remove --force "$WORKDIR/base" 2>/dev/null || true
  82. git -C "$REPO_ROOT" worktree remove --force "$WORKDIR/head" 2>/dev/null || true
  83. rm -rf "$WORKDIR"
  84. }
  85. trap cleanup EXIT
  86. BASE_SHA=$(git -C "$REPO_ROOT" rev-parse --short "$BASE_REF")
  87. HEAD_SHA=$(git -C "$REPO_ROOT" rev-parse --short "$HEAD_REF")
  88. echo "==> base: $BASE_REF ($BASE_SHA)"
  89. echo "==> head: $HEAD_REF ($HEAD_SHA)"
  90. echo "==> rounds=$ROUNDS duration=$DURATION connections=$CONNECTIONS threads=$THREADS"
  91. echo "==> path=$REQ_PATH tls=$TLS large=${LARGE_MIB}MiB"
  92. echo ""
  93. if [ "$BASE_SHA" = "$HEAD_SHA" ]; then
  94. echo "Note: base and head are the same commit; this measures harness noise."
  95. echo ""
  96. fi
  97. # --- Toolchain bits that depend on --tls ---
  98. SCHEME="http"
  99. INSECURE=""
  100. TLS_CXXFLAGS=""
  101. TLS_LDFLAGS=""
  102. TLS_ARGS=""
  103. if [ "$TLS" = "1" ]; then
  104. SCHEME="https"
  105. INSECURE="-k"
  106. TLS_CXXFLAGS="-DCPPHTTPLIB_OPENSSL_SUPPORT"
  107. TLS_LDFLAGS="-lssl -lcrypto"
  108. if command -v pkg-config >/dev/null 2>&1 && pkg-config --exists openssl; then
  109. TLS_CXXFLAGS="$TLS_CXXFLAGS $(pkg-config --cflags openssl)"
  110. TLS_LDFLAGS="$(pkg-config --libs openssl)"
  111. elif command -v brew >/dev/null 2>&1 && brew --prefix openssl >/dev/null 2>&1; then
  112. OPENSSL_PREFIX=$(brew --prefix openssl)
  113. TLS_CXXFLAGS="$TLS_CXXFLAGS -I$OPENSSL_PREFIX/include"
  114. TLS_LDFLAGS="-L$OPENSSL_PREFIX/lib -lssl -lcrypto"
  115. fi
  116. if [ "$(uname -s)" = "Darwin" ]; then
  117. TLS_LDFLAGS="$TLS_LDFLAGS -framework CoreFoundation -framework Security"
  118. fi
  119. TLS_ARGS="--cert $REPO_ROOT/test/cert.pem --key $REPO_ROOT/test/key.pem"
  120. for f in "$REPO_ROOT/test/cert.pem" "$REPO_ROOT/test/key.pem"; do
  121. [ -f "$f" ] || { echo "Error: $f not found" >&2; exit 1; }
  122. done
  123. fi
  124. # --- Build both refs ---
  125. # The harness source always comes from the invoking worktree, so both refs run
  126. # an identical workload and a ref that predates a harness change stays
  127. # measurable. Only httplib.h varies, through -I.
  128. HARNESS="$REPO_ROOT/benchmark/cpp-httplib/main.cpp"
  129. [ -f "$HARNESS" ] || { echo "Error: $HARNESS not found" >&2; exit 1; }
  130. build() {
  131. local name=$1 ref=$2
  132. git -C "$REPO_ROOT" worktree add --detach --quiet "$WORKDIR/$name" "$ref"
  133. "$CXX" -o "$WORKDIR/$name/server-ab" -O2 -std=c++11 \
  134. -I"$WORKDIR/$name" \
  135. -DCPPHTTPLIB_THREAD_POOL_COUNT="$THREADS" \
  136. $TLS_CXXFLAGS \
  137. "$HARNESS" -lpthread $TLS_LDFLAGS
  138. }
  139. echo "==> Building..."
  140. build base "$BASE_REF"
  141. build head "$HEAD_REF"
  142. # --- Measure one ref once, echo rps ---
  143. measure() {
  144. local name=$1
  145. local json rc
  146. "$WORKDIR/$name/server-ab" --port "$PORT" --dir "$WORKDIR/$name-www" \
  147. --large-mib "$LARGE_MIB" $TLS_ARGS >/dev/null 2>&1 &
  148. local pid=$!
  149. # Wait for the listener (no dependency on nc)
  150. local i
  151. for i in $(seq 1 200); do
  152. if (exec 3<>/dev/tcp/127.0.0.1/$PORT) 2>/dev/null; then exec 3>&- 3<&-; break; fi
  153. sleep 0.05
  154. done
  155. set +e
  156. json=$(bombardier -c "$CONNECTIONS" -d "$DURATION" -t "$TIMEOUT" -o json -p r $INSECURE ${CLOSE_HEADER[@]+"${CLOSE_HEADER[@]}"} \
  157. "$SCHEME://127.0.0.1:$PORT$REQ_PATH" 2>/dev/null)
  158. rc=$?
  159. set -e
  160. kill "$pid" 2>/dev/null || true
  161. wait "$pid" 2>/dev/null || true
  162. # Wait for the port to be released before the next run
  163. for i in $(seq 1 200); do
  164. if ! (exec 3<>/dev/tcp/127.0.0.1/$PORT) 2>/dev/null; then break; fi
  165. exec 3>&- 3<&-
  166. sleep 0.05
  167. done
  168. if [ $rc -ne 0 ] || [ -z "$json" ]; then
  169. echo "Error: bombardier failed for $name" >&2
  170. exit 1
  171. fi
  172. python3 -c '
  173. import json, sys
  174. r = json.load(sys.stdin)["result"]
  175. total = sum(r[k] for k in ("req1xx","req2xx","req3xx","req4xx","req5xx","others"))
  176. bad = total - r["req2xx"]
  177. if bad:
  178. sys.stderr.write("Error: %d non-2xx/error responses\n" % bad)
  179. sys.exit(1)
  180. print("%.1f" % (total / r["timeTakenSeconds"]))
  181. ' <<<"$json"
  182. }
  183. # --- Alternate, flipping the order each round to cancel ordering bias ---
  184. BASE_RESULTS=()
  185. HEAD_RESULTS=()
  186. echo ""
  187. echo "==> Measuring..."
  188. for ((r = 1; r <= ROUNDS; r++)); do
  189. if (( r % 2 == 1 )); then order=("base" "head"); else order=("head" "base"); fi
  190. line=" round $r:"
  191. for name in "${order[@]}"; do
  192. rps=$(measure "$name")
  193. if [ "$name" = "base" ]; then BASE_RESULTS+=("$rps"); else HEAD_RESULTS+=("$rps"); fi
  194. line="$line $name=$rps"
  195. done
  196. echo "$line"
  197. done
  198. # --- Report ---
  199. SUMMARY=$(python3 -c '
  200. import statistics, sys
  201. from itertools import combinations
  202. base = [float(x) for x in sys.argv[1].split()]
  203. head = [float(x) for x in sys.argv[2].split()]
  204. bm, hm = statistics.median(base), statistics.median(head)
  205. def spread(v):
  206. return (max(v) - min(v)) / statistics.median(v) * 100
  207. def u_stat(a, b):
  208. """Mann-Whitney U: number of (a, b) pairs where a > b, ties count a half."""
  209. return sum((x > y) + 0.5 * (x == y) for x in a for y in b)
  210. def exact_p(a, b):
  211. """Two-sided permutation p-value. A single slow round cannot swing this
  212. the way a min/max spread check can."""
  213. n1, n2 = len(a), len(b)
  214. pooled = a + b
  215. observed = abs(u_stat(a, b) - n1 * n2 / 2)
  216. total = extreme = 0
  217. for idx in combinations(range(n1 + n2), n1):
  218. s = set(idx)
  219. ga = [pooled[i] for i in idx]
  220. gb = [pooled[i] for i in range(n1 + n2) if i not in s]
  221. total += 1
  222. if abs(u_stat(ga, gb) - n1 * n2 / 2) >= observed:
  223. extreme += 1
  224. return extreme / total
  225. print("| | median req/s | min | max | spread |")
  226. print("|---|---|---|---|---|")
  227. print("| base | %.0f | %.0f | %.0f | %.1f%% |" % (bm, min(base), max(base), spread(base)))
  228. print("| head | %.0f | %.0f | %.0f | %.1f%% |" % (hm, min(head), max(head), spread(head)))
  229. print("")
  230. print("**ratio: %.3fx** (%+.1f%%)" % (hm / bm, (hm / bm - 1) * 100))
  231. print("")
  232. if len(base) + len(head) > 20:
  233. print("> %d rounds: skipping the permutation test (too many combinations)."
  234. % len(base))
  235. else:
  236. p = exact_p(base, head)
  237. if p <= 0.05:
  238. print("> Separation is consistent across rounds (permutation p = %.3f)." % p)
  239. else:
  240. print("> Not separated from noise (permutation p = %.3f). Inconclusive;" % p)
  241. print("> raise --rounds or --duration, or run on a quieter machine.")
  242. min_p = exact_p(list(range(len(base))),
  243. list(range(len(base), len(base) + len(head))))
  244. if min_p > 0.05:
  245. print(">")
  246. print("> With %d rounds even perfect separation only reaches p = %.3f,"
  247. % (len(base), min_p))
  248. print("> so this test can never call a win. Use --rounds 4 or more.")
  249. ' "${BASE_RESULTS[*]}" "${HEAD_RESULTS[*]}")
  250. echo ""
  251. echo "$SUMMARY"
  252. if [ -n "${GITHUB_STEP_SUMMARY:-}" ]; then
  253. {
  254. echo "## Benchmark A/B"
  255. echo ""
  256. echo "- base: \`$BASE_REF\` ($BASE_SHA)"
  257. echo "- head: \`$HEAD_REF\` ($HEAD_SHA)"
  258. echo "- rounds=$ROUNDS duration=$DURATION connections=$CONNECTIONS threads=$THREADS"
  259. echo ""
  260. echo "$SUMMARY"
  261. } >> "$GITHUB_STEP_SUMMARY"
  262. fi