diff --git a/README.md b/README.md index 369884f5b0..ae8d401c86 100644 --- a/README.md +++ b/README.md @@ -48,7 +48,7 @@ The reply states which baseline it used, and profiles the other framework does n | Category | Profiles | Description | |----------|----------|-------------| | Connection | `baseline`, `pipelined` *, `limited-conn` | Mixed GET/POST with query parsing (4K conns), 16× batched pipelining (reference-only, shown faded, excluded from the composite score), short-lived connections that close after 10 requests | -| Concurrency | `async` | `GET /delay/{ms}` with the wait named in the route, 32K held connections. Isolates what a framework does while a request is pending, with no database or I/O in the way. Scored for frameworks and engines, not for infrastructure, since the spec settled at a flat 10 ms over 32K connections | +| Concurrency | `async`, `connections-1m`, `connections-1m-tls`, `connections-5m` * | `GET /delay/{ms}` with the wait named in the route, 32K held connections. Isolates what a framework does while a request is pending, with no database or I/O in the way. Scored for frameworks and engines, not for infrastructure, since the spec settled at a flat 10 ms over 32K connections. The held-connection profiles keep a fleet of keep-alive connections open with one request per connection every 4 s: `connections-1m` (CON-1M) a million at 250K req/s on zrk 3.0.2, `connections-1m-tls` (CON-1M-TLS) a million over TLS 1.3 on gcannon, both scored on CPU per request, memory, p50 and p99; `connections-5m` (CON-5M) five million at 1.25M req/s, reference-only and run only for the entries on `scripts/connections-5m-allowlist.json`. They need a listener on 0.0.0.0 or [::] and an idle timeout of 5 s or more | | Efficiency | `latency-1m`, `latency-10k` | One million req/s offered at a fixed rate with zrk; the metric is CPU spent per request, read exactly from the container's cgroup rather than sampled. Everyone who finishes serves the same million, so what separates them is the bill. Scored on its own 0-100 formula rather than on rps, since the rate is pinned. `latency-10k` is the identical setup - same cores, connections and endpoint - at a near-idle 10K req/s, so what it reports is the standing cost of being a running server rather than of serving load, and it is scored the same way. Both score CPU at 0.50, p99 at 0.25 and mean latency at 0.25, the mean being the queueing signal: ten times the best mean is worth nothing. | | Workload | `json-comp`, `json-tls`, `8gbit`, `static-tls` * | JSON serialization, gzip/brotli compression, HTTP/1.1 over TLS, a 10 KB body echoed over TLS at a pinned 50K req/s so ingest and egress load together - scored on the same 0-100 formula as the latency profiles, since its rate is pinned too, 20-file static asset serving over TLS (reference-only for frameworks and engines, scored for infrastructure) | | Database | `async-db`, `fortunes` | Postgres-backed HTTP/1.1, on their own board: an async range query, and a DB query + HTML template render (TechEmpower-style Fortunes). The server gets 32 logical CPUs, the load generator 32 and Postgres the rest | diff --git a/docker/gcannon.Dockerfile b/docker/gcannon.Dockerfile index 389f75ff71..e8779ae4b7 100644 --- a/docker/gcannon.Dockerfile +++ b/docker/gcannon.Dockerfile @@ -5,8 +5,10 @@ ARG GCANNON_REF=main # stale git-clone layer. Without this, edits pushed to the gcannon repo # are invisible until the user manually runs --no-cache. ARG CACHE_BUST=0 +# libssl-dev: gcannon 0.7.0 and later do the TLS handshake with OpenSSL (the +# runtime image's libssl3 serves the binary), and fail to build without it. RUN apt-get update && apt-get install -y --no-install-recommends \ - gcc libc6-dev make git ca-certificates && rm -rf /var/lib/apt/lists/* + gcc libc6-dev make git ca-certificates libssl-dev && rm -rf /var/lib/apt/lists/* WORKDIR /deps RUN git clone --branch liburing-2.9 --depth 1 https://github.com/axboe/liburing.git && \ cd liburing && ./configure --prefix=/usr && make -j"$(nproc)" -C src && make install -C src diff --git a/docker/zrk.Dockerfile b/docker/zrk.Dockerfile index 567452ac8b..0853c90015 100644 --- a/docker/zrk.Dockerfile +++ b/docker/zrk.Dockerfile @@ -10,6 +10,9 @@ # across entries and across rounds, so a generator that drifts under it # invalidates every comparison it was measured against, including old ones. # Bumping the version is a deliberate act that re-baselines the profile. +# +# connections-1m builds this file a second time as zrk:3.0.2, passing +# ZRK_VERSION and ZRK_SHA256 (tools/zrk.sh), and leaves zrk:local as it is. FROM ubuntu:24.04 AS build ARG ZRK_VERSION=2.3.0 ARG ZRK_SHA256=ab6f1c1ce34ce73f52afd106419d15e5c494bd1cedd475afa56babb85b09a816 diff --git a/frameworks/actix/meta.json b/frameworks/actix/meta.json index f9dc980033..b6b2c6dde5 100644 --- a/frameworks/actix/meta.json +++ b/frameworks/actix/meta.json @@ -19,6 +19,9 @@ "baseline", "async", "latency-1m", + "connections-5m", + "connections-1m-tls", + "connections-1m", "latency-10k", "pipelined", "limited-conn", diff --git a/frameworks/actix/src/main.rs b/frameworks/actix/src/main.rs index e089869d9e..bebdc63701 100644 --- a/frameworks/actix/src/main.rs +++ b/frameworks/actix/src/main.rs @@ -401,6 +401,13 @@ async fn main() -> io::Result<()> { .service(Files::new("/static", "/data/static").try_compressed()) }) .workers(workers) + // Connections per worker. actix-server stops accepting at 25,600 per + // worker by default, 1.64M across 64 workers, short of connections-5m's + // five million (78,125 per worker). It is a counter, not an allocation, + // and the resilience suite's slow attacks hold 32,768 connections - under + // even the default cap of its 2-CPU box - so only the held-connection + // profiles ever reach it. + .max_connections(100_000) .tcp_nodelay(true) .bind("0.0.0.0:8080")?; diff --git a/frameworks/aspnet-minimal/meta.json b/frameworks/aspnet-minimal/meta.json index 05fef882ab..0458884864 100644 --- a/frameworks/aspnet-minimal/meta.json +++ b/frameworks/aspnet-minimal/meta.json @@ -20,6 +20,9 @@ "baseline", "pipelined", "limited-conn", "async", "latency-1m", "latency-10k", + "connections-5m", + "connections-1m-tls", + "connections-1m", "json-comp", "json-tls", "8gbit", diff --git a/frameworks/bun/meta.json b/frameworks/bun/meta.json index 57f16bbc8f..9d31cddc47 100644 --- a/frameworks/bun/meta.json +++ b/frameworks/bun/meta.json @@ -18,6 +18,9 @@ "baseline", "async", "latency-1m", "latency-10k", + "connections-5m", + "connections-1m-tls", + "connections-1m", "pipelined", "limited-conn", "json-comp", diff --git a/frameworks/fib/meta.json b/frameworks/fib/meta.json index 0c67457aa0..3be7ca8b7d 100644 --- a/frameworks/fib/meta.json +++ b/frameworks/fib/meta.json @@ -20,6 +20,9 @@ "limited-conn", "async", "latency-1m", + "connections-5m", + "connections-1m-tls", + "connections-1m", "latency-10k", "json-comp", "json-tls", diff --git a/frameworks/genhttp-ioxide/Dockerfile b/frameworks/genhttp-ioxide/Dockerfile index 4f15e0e31a..1c9d74362c 100644 --- a/frameworks/genhttp-ioxide/Dockerfile +++ b/frameworks/genhttp-ioxide/Dockerfile @@ -3,7 +3,7 @@ FROM mcr.microsoft.com/dotnet/sdk:11.0 AS build # GenHTTP built from source: the branch of Kaliumhexacyanoferrat/GenHTTP#953 # (update-ioxide-0.20.396) rather than the 11.3.0 release. Pinned to one commit, # because a build on cached layers would otherwise keep whichever it cloned first. -ARG GENHTTP_COMMIT=28b0cd107bb36321408a3a1f892f3bb45225e9d7 +ARG GENHTTP_COMMIT=5967f5c6bf64d3d67a0eed7a669fa2f8c846dd02 RUN git init -q /genhttp \ && git -C /genhttp fetch -q --depth 1 https://github.com/Kaliumhexacyanoferrat/GenHTTP.git "$GENHTTP_COMMIT" \ && git -C /genhttp checkout -q FETCH_HEAD diff --git a/frameworks/genhttp-ioxide/meta.json b/frameworks/genhttp-ioxide/meta.json index 3c494db0a5..c1d8c6c4ac 100644 --- a/frameworks/genhttp-ioxide/meta.json +++ b/frameworks/genhttp-ioxide/meta.json @@ -19,6 +19,9 @@ "baseline", "async", "latency-1m", + "connections-5m", + "connections-1m-tls", + "connections-1m", "latency-10k", "pipelined", "limited-conn", diff --git a/frameworks/node/meta.json b/frameworks/node/meta.json index bd36d466ce..2cf06923d8 100644 --- a/frameworks/node/meta.json +++ b/frameworks/node/meta.json @@ -8,6 +8,9 @@ "enabled": true, "tests": [ "baseline", "latency-1m", "latency-10k", + "connections-5m", + "connections-1m-tls", + "connections-1m", "pipelined", "limited-conn", "json-comp", diff --git a/scripts/benchmark.sh b/scripts/benchmark.sh index 375af5b444..3ce4b91ce5 100755 --- a/scripts/benchmark.sh +++ b/scripts/benchmark.sh @@ -183,7 +183,7 @@ done # and any combination thereof. _has_isolated_test=false for t in baseline pipelined limited-conn json-comp json-tls upload \ - static-tls async-db async latency-1m latency-10k \ + static-tls async-db async latency-1m latency-10k connections-5m connections-1m-tls connections-1m \ baseline-h2 static-h2 baseline-h2c json-h2c \ baseline-h3 static-h3 \ unary-grpc unary-grpc-tls \ @@ -214,14 +214,49 @@ if { framework_subscribes_to "latency-1m" || framework_subscribes_to "latency-10 info "zrk: docker mode ($ZRK_IMAGE)" fi +# connections-1m runs its own zrk (ZRK_CONN1M_VERSION, tools/zrk.sh): the +# same Dockerfile at another version, so the pinned image above is untouched. +# A failed build is not fatal here: the fan-out asks the image for --version +# and reports the profile as not run, and the other profiles go ahead. +if framework_subscribes_to "connections-1m" \ + && [[ " ${profiles_to_run[*]} " == *" connections-1m "* ]] \ + && [ -z "${ZRK_CONN1M_CMD:-}" ]; then + if _zrk_at_least "$ZRK" "$ZRK_CONN1M_VERSION"; then + ZRK_CONN1M_CMD="$ZRK" + else + if ! docker image inspect "$ZRK_CONN1M_IMAGE" >/dev/null 2>&1; then + info "building $ZRK_CONN1M_IMAGE (zrk $ZRK_CONN1M_VERSION) for connections-1m" + docker build -t "$ZRK_CONN1M_IMAGE" \ + --build-arg ZRK_VERSION="$ZRK_CONN1M_VERSION" \ + --build-arg ZRK_SHA256="$ZRK_CONN1M_SHA256" \ + -f "$ROOT_DIR/docker/zrk.Dockerfile" "$ROOT_DIR/docker" \ + || warn "$ZRK_CONN1M_IMAGE build failed - connections-1m will not run" + fi + ZRK_CONN1M_CMD="docker run --rm --network host --cpuset-cpus=$GCANNON_CPUS --security-opt seccomp=unconfined --ulimit memlock=-1:-1 --ulimit nofile=1048576:1048576 $ZRK_CONN1M_IMAGE" + fi + info "zrk for connections-1m: $ZRK_CONN1M_CMD" +fi + # ── System tuning — NOW, after all image builds are complete ─────────────── if [ "${SKIP_TUNE:-}" != "true" ]; then system_tune + # Only when this run will hold a million connections; see system.sh. + _held=false + for _p in "${profiles_to_run[@]}"; do + if held_conn_profile "$_p" && framework_subscribes_to "$_p"; then _held=true; break; fi + done + if $_held; then + system_tune_held_connections + fi else info "skipping system tuning as requested (SKIP_TUNE=true)" fi +# The socket count a held-connection run waits to get back to (system.sh, +# held_conn_drain): taken now, with nothing of ours running. +held_conn_baseline + # Start the postgres sidecar if any subscribed test needs it. need_pg=false for t in async-db gateway-64 gateway-h3 production-stack fortunes; do @@ -321,7 +356,7 @@ run_one() { # three runs, which is not known until all three have happened. Every run is # recorded here and the choice is made below. local _mdir="" - case "$endpoint" in latency-1m|latency-10k|8gbit) _mdir=$(mktemp -d) ;; esac + case "$endpoint" in latency-1m|latency-10k|8gbit|connections-5m|connections-1m-tls|connections-1m) _mdir=$(mktemp -d) ;; esac BEST_M=() local run @@ -329,6 +364,28 @@ run_one() { for run in $(seq 1 "$RUNS"); do echo ""; echo "[run $run/$RUNS]" + # The held-connection profiles give every run a fresh server. One that + # has just held five million connections keeps what it grew to after + # they close (a GC heap, allocator arenas: genhttp-ioxide still held + # ~71 GiB a minute after its 5M run), so the next run would start from + # the last one's peak - in its memory check and in its Mem column. + # The previous run's server was stopped once its fleet was closed + # (below). + if [ "$run" -gt 1 ] && held_conn_profile "$endpoint" && ! $is_gateway; then + info "starting a fresh $FRAMEWORK for run $run" + framework_start "$endpoint" "$PROF_CPU" + if ! framework_wait_ready "$endpoint"; then + warn "$FRAMEWORK did not come back up for run $run; keeping the runs so far" + dump_container_logs "$CONTAINER_NAME" "$FRAMEWORK" + break + fi + fi + # ...and connects only once the host has finished closing whatever came + # before it: the last run's fleet, or the last profile's. + if held_conn_profile "$endpoint" && ! $is_gateway; then + held_conn_drain "before run $run" + fi + if $is_gateway; then # shellcheck disable=SC2086 stats_start $GATEWAY_CONTAINERS @@ -368,6 +425,14 @@ run_one() { [[ "$line" == *=* ]] && m["${line%%=*}"]="${line#*=}" done <<< "$metrics" + # connections-5m(-tls) reports the server's CPU over gcannon's measured + # window only (scripts/conn_hold.py), connections-1m over the fan- + # out's (scripts/zrk_fanout.py). The reading above spans the whole run, + # a million connects and closes included, so the window replaces it. + if [ -n "${m[cpu_usec_window]:-}" ]; then + CPU_ACCT_USEC="${m[cpu_usec_window]}" + fi + local rps_int=${m[rps]:-0} # Best-of-N keeps the fastest run — except on a fixed-rate profile, @@ -414,7 +479,19 @@ run_one() { # for. tcp_tw_reuse lets those be recycled, but at 48K of a 64.5K-port # range the connect path starts scanning and the ramp lands inside the # measured window. Two seconds is plenty below that. - if [ "$CONNS" -ge 32768 ]; then sleep 15; else sleep 2; fi + # A held-connection run waits for its fleet to be closed instead of + # sleeping (system.sh, held_conn_drain): seconds when gcannon closes it + # itself (>= 0.8.3), over a minute at 5M when the kernel does. The + # server stays up meanwhile, so it closes its side as the client's go + # rather than being killed holding millions; then it is stopped for a + # fresh one. After the last run it is left for the profile's cleanup. + if held_conn_profile "$endpoint" && ! $is_gateway; then + held_conn_drain "after run $run" + if [ "$run" -lt "$RUNS" ]; then + framework_stop + fi + elif [ "$CONNS" -ge 32768 ]; then sleep 15 + else sleep 2; fi done if [ "$best_rps" -lt 0 ]; then @@ -463,7 +540,7 @@ run_one() { echo ""; echo "=== Best: ${best_rps} req/s (CPU: $best_cpu, Mem: $best_mem) ===" # The fixed-rate profiles' headline number, and the check that it counts. - if [ "$endpoint" = "latency-1m" ] || [ "$endpoint" = "latency-10k" ] || [ "$endpoint" = "8gbit" ]; then + if [ "$endpoint" = "latency-1m" ] || [ "$endpoint" = "latency-10k" ] || [ "$endpoint" = "8gbit" ] || held_conn_profile "$endpoint"; then # Two different failures that used to print the same line. "No CPU # reading" is a cgroup problem; "no requests" is a generator or server # problem, and saying the former when it is the latter sent the first @@ -498,6 +575,23 @@ run_one() { fi fi + # The held-connection profiles: whether the fleet was actually held. The + # rate alone cannot say it - a connection that never opened sends nothing, + # which reads as a rate shortfall - so gcannon reports the connections + # still open at the end of its window, and zrk's fan-out counts the + # server's established sockets after it. + if held_conn_profile "$endpoint"; then + if [ -n "${BEST_M[hold_error]:-}" ]; then + warn "$endpoint did not run: ${BEST_M[hold_error]}" + else + echo "=== Connections: ${BEST_M[connections_open]:-n/a} open of $CONNS | connect errors in the window ${BEST_M[connect_errors]:-n/a} ===" + if [ -n "${BEST_M[connections_open]:-}" ] \ + && [ "${BEST_M[connections_open]}" -lt $(( CONNS * 99 / 100 )) ] 2>/dev/null; then + warn "held ${BEST_M[connections_open]} of $CONNS connections through the window" + fi + fi + fi + # 8gbit's generator reports only the bytes it read back, so that figure # is the download half of the echo; the request body is a fixed size # (ZRK_ECHO_BODY_BYTES in scripts/lib/tools/zrk.sh - keep the two in step), @@ -590,7 +684,7 @@ save_result() { # not the load, so the reason ships with the row rather than being inferred # from an rps that looks merely slow. local eff_extra="" - if [ "$profile" = "latency-1m" ] || [ "$profile" = "latency-10k" ] || [ "$profile" = "8gbit" ]; then + if [ "$profile" = "latency-1m" ] || [ "$profile" = "latency-10k" ] || [ "$profile" = "8gbit" ] || held_conn_profile "$profile"; then local _eff_reqs=${BEST_M[status_2xx]:-0} local _eff_per_req="null" if [ -n "$best_cpu_usec" ] && [ "$_eff_reqs" -gt 0 ] 2>/dev/null; then @@ -602,6 +696,14 @@ save_result() { \"target_rate\": ${BEST_M[target_rate]:-0}, \"rate_ratio\": ${best_rate_ratio:-0}, \"p99_9_latency\": \"${BEST_M[p999_lat]:-}\"" + # How much of the fleet was held, next to what it cost to hold it, and + # the median the held-connection score weighs with the p99. + if held_conn_profile "$profile"; then + eff_extra="$eff_extra, + \"p50_latency\": \"${BEST_M[p50_lat]:-}\", + \"connections_open\": ${BEST_M[connections_open]:-null}, + \"window_connect_errors\": ${BEST_M[connect_errors]:-null}" + fi fi local cpu_extra="" @@ -670,6 +772,10 @@ for profile in "${profiles_to_run[@]}"; do warn "unknown profile: $profile" continue fi + if [ "$profile" = "connections-5m" ] && echo ",$FRAMEWORK_TESTS," | grep -qF ",connections-5m," && ! conn5m_allowed; then + info "skip: $FRAMEWORK subscribes to connections-5m but is not on scripts/connections-5m-allowlist.json" + continue + fi framework_subscribes_to "$profile" || { info "skip: $FRAMEWORK does not subscribe to $profile"; continue; } parse_profile "${PROFILES[$profile]}" diff --git a/scripts/conn_hold.py b/scripts/conn_hold.py new file mode 100644 index 0000000000..e0cdf5d43e --- /dev/null +++ b/scripts/conn_hold.py @@ -0,0 +1,321 @@ +#!/usr/bin/env python3 +"""Run gcannon --rate for a held-connection profile; report a fixed-rate summary. + +connections-5m holds five million keep-alive connections and paces requests +across them, connections-1m-tls a million over TLS 1.3. gcannon does the load +itself (gcannon >= 0.8.2: --rate, --addr-span, --connect-limit, --settle, +--warmup-max) in one process: ~3.3 KiB a connection, against the ~303 KiB that +sank the first million-connection attempt with zrk 2.3.0. (connections-1m +runs a million on zrk 3.0.2, ~41 KiB a connection, through +scripts/zrk_fanout.py.) What this wrapper adds is what gcannon cannot know +about the server or the host: + + - a listener on every address. The fleet is spread over 127.0.0.1-.160 + (.32 for the million over TLS; one source address holds ~64.5K + connections to one destination), so a + server bound to 127.0.0.1 or localhost refuses most of it. Probed first, + and reported as an error rather than millions of connect failures. + - memory. The run is refused when the client, the kernel's share and what + the server may still grow into do not fit in MemAvailable: the first + million-connection run took the bench host down. + - open files. Five million sockets need RLIMIT_NOFILE above five million, + usually past the hard limit the runner was started with; it is raised + with `sudo -n prlimit` when it has to be (fs.nr_open, the ceiling, is + raised by system_tune_held_connections). + - the server's CPU over exactly the measured window. gcannon prints + "gcannon: warmup done" when its window opens and "gcannon: measurement + done" when it closes, while every connection is still up; the server + cgroup's usage_usec is read at each, so neither the connects nor the + million closes afterwards are in the figure. + +stdout is one JSON object in the shape scripts/lib/tools/gcannon.sh's +held-connection parser reads (rps, latency, status classes, rate_ratio, the +window CPU, connections still open). Usage: + + conn_hold.py --profile connections-5m --conns N --rate R --port P + --probe 127.0.0.2,127.0.0.160 [--span 127.0.0.1-127.0.0.160] + [--cpu-stat FILE] [--server-mem 128g] [--kib-per-conn 4] + [--kernel-kib-per-conn 8] + -- --args-- +""" + +from __future__ import annotations + +import argparse +import json +import os +import resource +import socket +import subprocess +import sys +import threading + +# 0.8.0 has --rate, but scheduled each thread's connections inside one 1/T +# slice of the interval, so one thread at a time sent the whole fleet's rate: +# at a million connections every send ran ~150 ms late and that is what the +# latency figures measured (MDA2AV/gcannon#30). 0.8.2 adds --settle, the +# steady-state pause between the connect phase and the window (gcannon#31). +MIN_VERSION = (0, 8, 2) +# Not required, but 0.8.3 closes its own connections before it exits (gcannon#32). +# Earlier ones leave the fleet for the kernel to close, one socket at a time, +# and the harness waits that out between runs (system.sh, held_conn_drain). +CLOSES_ITSELF = (0, 8, 3) +# Over https://, 0.8.4 counts a connection against --connect-limit until its +# handshake is done (gcannon#33). Before, it let the handshakes pile up at the +# server past its handshake timeout, which closed them mid-handshake: a fleet +# that never finished connecting. +MIN_VERSION_TLS = (0, 8, 4) + + +def log(msg: str) -> None: + print(f"[conn-hold] {msg}", file=sys.stderr, flush=True) + + +def _mem_available_kib() -> int | None: + try: + with open("/proc/meminfo") as f: + for line in f: + if line.startswith("MemAvailable:"): + return int(line.split()[1]) + except (OSError, ValueError, IndexError): + pass + return None + + +def _size_kib(s: str | None) -> int: + if not s: + return 0 + s = s.strip().lower() + mult = {"k": 1, "m": 1024, "g": 1024 ** 2, "t": 1024 ** 3} + try: + return int(float(s[:-1]) * mult[s[-1]]) if s[-1] in mult else int(s) // 1024 + except ValueError: + return 0 + + +def _cgroup_mem_kib(cpu_stat: str | None) -> int: + """The server cgroup's memory now, in KiB: memory.current, which sits next + to the cpu.stat the caller passes. 0 when it cannot be read.""" + if not cpu_stat: + return 0 + try: + with open(os.path.join(os.path.dirname(cpu_stat), "memory.current")) as f: + return int(f.read().strip()) // 1024 + except (OSError, ValueError): + return 0 + + +def _cpu_usec(path: str | None) -> int | None: + if not path: + return None + try: + with open(path) as f: + for line in f: + if line.startswith("usage_usec"): + return int(line.split()[1]) + except (OSError, ValueError, IndexError): + pass + return None + + +def _probe(addr: str, port: int) -> str | None: + try: + with socket.create_connection((addr, port), timeout=3): + return None + except OSError as e: + return f"{type(e).__name__}: {e}" + + +def _version(prefix: list[str]) -> tuple[int, ...] | None: + try: + out = subprocess.run(prefix + ["--version"], capture_output=True, text=True, + timeout=60).stdout + except (OSError, subprocess.TimeoutExpired): + return None + for tok in out.split(): + parts = tok.lstrip("v").split(".") + if len(parts) == 3 and all(p.isdigit() for p in parts): + return tuple(int(p) for p in parts) + return None # an old gcannon has no --version and prints usage instead + + +def _raise_nofile(want: int) -> str | None: + """Give this process (and so gcannon, which inherits it) `want` open files. + + Raising the soft limit up to the hard one needs no privilege. Past the + hard limit - five million sockets are usually past whatever the runner was + started with - only root can raise it, and setrlimit has no sudo, so + prlimit(1) raises it for this pid from outside. fs.nr_open caps both. + Returns why it could not, or None.""" + soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE) + if soft >= want: + return None + if hard < want: + try: + subprocess.run(["sudo", "-n", "prlimit", "--pid", str(os.getpid()), + f"--nofile={want}:{want}"], capture_output=True, timeout=30) + except (OSError, subprocess.TimeoutExpired): + pass + soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE) + try: + resource.setrlimit(resource.RLIMIT_NOFILE, (min(want, hard), hard)) + except (ValueError, OSError): + pass + soft = resource.getrlimit(resource.RLIMIT_NOFILE)[0] + if soft >= want: + return None + try: + nr_open = int(open("/proc/sys/fs/nr_open").read()) + except (OSError, ValueError): + nr_open = 0 + return (f"the open-file limit is {soft} (hard {hard}, fs.nr_open {nr_open}), below the " + f"{want} these connections need; `sudo -n prlimit` could not raise it. Raise the " + "runner's hard limit (LimitNOFILE= in its systemd unit, or limits.conf) and " + "fs.nr_open") + + +def _error(args, msg: str) -> dict: + log(msg) + return {"hold_error": msg, "connections": args.conns, "target_rate": args.rate, + "rps": 0, "rate_ratio": 0, "duration_s": 0, "latency_us": {}, + "status_codes": {}, "errors": {}, "connections_open": None, + "server_cpu_usec": None} + + +def run(args, prefix: list[str], gargs: list[str]) -> dict: + ver = _version(prefix) + tls = bool(gargs) and gargs[0].startswith("https://") + need = MIN_VERSION_TLS if tls else MIN_VERSION + if ver is None or ver < need: + # prefix[-1] is the image or the binary: which gcannon was asked + why = ("--connect-limit held through the TLS handshake" if tls else + "--settle, and --rate with every thread spread over the whole interval") + return _error(args, "%s needs gcannon >= %s (%s); %s %s" + % (args.profile, ".".join(map(str, need)), why, prefix[-1], + "is " + ".".join(map(str, ver)) if ver else + "did not answer --version (an older gcannon, or an image that did not build)")) + + if ver < CLOSES_ITSELF: + log(f"gcannon {'.'.join(map(str, ver))} leaves its {args.conns} connections for the " + "kernel to close after it exits, one at a time; the next run waits for that. " + f"{'.'.join(map(str, CLOSES_ITSELF))} closes them itself") + + for addr in [a for a in args.probe.split(",") if a]: + err = _probe(addr, args.port) + if err: + return _error(args, f"no listener reachable on {addr}:{args.port} ({err}): " + f"{args.profile} spreads its connections over {args.span}, " + "so the server must listen on 0.0.0.0 or [::], not 127.0.0.1 or " + "localhost alone") + + avail = _mem_available_kib() + server_kib = _size_kib(args.server_mem) + # What the server already holds is missing from MemAvailable and inside its + # cap both, so only what it may still grow by is counted; otherwise a + # server still warm from an earlier run is counted twice. + server_now = _cgroup_mem_kib(args.cpu_stat) + need = (args.conns * (args.kib_per_conn + args.kernel_kib_per_conn) + + max(server_kib - server_now, 0)) + gib = 1024 ** 2 + budget = (f"the client ~{args.conns * args.kib_per_conn / gib:.1f} GiB, the kernel " + f"~{args.conns * args.kernel_kib_per_conn / gib:.1f} GiB, and the server, at " + f"{server_now / gib:.1f} GiB now, may grow to {server_kib / gib:.0f} GiB") + if avail is not None and need > avail * 0.9: + return _error(args, f"not enough memory to hold {args.conns} connections: {budget}, " + f"against {avail / gib:.0f} GiB available") + if avail is not None: + log(f"memory: {budget}; {avail / gib:.0f} GiB available") + + native = not any(os.path.basename(p) == "docker" for p in prefix) + if native: + want = args.conns + 4096 + err = _raise_nofile(want) + if err: + return _error(args, err) + + cpu = {} + proc = subprocess.Popen(prefix + gargs, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + stdin=subprocess.DEVNULL, text=True) + + def watch_stderr(): + assert proc.stderr is not None + for line in proc.stderr: + sys.stderr.write(line) + if line.startswith("gcannon: warmup done"): + cpu["start"] = _cpu_usec(args.cpu_stat) + elif line.startswith("gcannon: measurement done"): + cpu["end"] = _cpu_usec(args.cpu_stat) + sys.stderr.flush() + + t = threading.Thread(target=watch_stderr, daemon=True) + t.start() + # Not communicate(): it reads stderr too, and would race the thread for + # the markers (the "measurement done" line went missing that way). + assert proc.stdout is not None + out = proc.stdout.read() + proc.wait() + t.join(timeout=10) + + start, end = out.find("{"), out.rfind("}") + try: + g = json.loads(out[start:end + 1]) + except ValueError: + return _error(args, f"gcannon exited {proc.returncode} without a JSON summary: " + f"{out.strip()[:300] or ''}") + + el = g.get("elapsed_sec") or 0 + st = g.get("status") or {} + ok = st.get("2xx") or 0 + rps = ok / el if el else 0 + lat = g.get("latency_us") or {} + rate = g.get("rate") or {} + cpu_win = (cpu["end"] - cpu["start"]) if cpu.get("start") is not None \ + and cpu.get("end") is not None and cpu["end"] >= cpu["start"] else None + if g.get("connections_active") is not None: + log(f"{g['connections_active']} of {args.conns} connections open at the end of the window") + return { + "connections": args.conns, + "connections_open": g.get("connections_active"), + "target_rate": args.rate, + "rps": round(rps, 2), + "rate_ratio": round(rps / args.rate, 4) if args.rate else 0, + "duration_s": el, + "bytes_per_sec": g.get("bandwidth_bps") or 0, + "max_schedule_lag_us": rate.get("max_lag_us") or 0, + "latency_us": {"mean": lat.get("avg"), "p50": lat.get("p50"), "p90": lat.get("p90"), + "p99": lat.get("p99"), "p99_9": lat.get("p999")}, + "status_codes": {k: st.get(k) or 0 for k in ("2xx", "3xx", "4xx", "5xx")}, + "errors": g.get("errors") or {}, + "reconnects": g.get("reconnects") or 0, + "server_cpu_usec": cpu_win, + "gcannon": g, + } + + +def main(argv: list[str]) -> int: + if "--" not in argv or "--args--" not in argv: + print(__doc__, file=sys.stderr) + return 2 + i, j = argv.index("--"), argv.index("--args--") + ap = argparse.ArgumentParser() + ap.add_argument("--conns", type=int, required=True) + ap.add_argument("--rate", type=int, required=True) + ap.add_argument("--port", type=int, required=True) + ap.add_argument("--probe", default="") + ap.add_argument("--cpu-stat", dest="cpu_stat") + ap.add_argument("--server-mem", dest="server_mem") + ap.add_argument("--kib-per-conn", dest="kib_per_conn", type=int, default=4, + help="gcannon's memory per connection in KiB (~3.3 measured)") + ap.add_argument("--kernel-kib-per-conn", dest="kernel_kib_per_conn", type=int, default=8, + help="kernel memory per connection: both sockets and a conntrack " + "entry, plus kernel TLS state over TLS") + ap.add_argument("--profile", default="connections-5m", help="for messages") + ap.add_argument("--span", default="127.0.0.1-127.0.0.160", + help="the addresses the fleet is spread over, for messages") + args = ap.parse_args(argv[:i]) + print(json.dumps(run(args, argv[i + 1:j], argv[j + 1:]), indent=1)) + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/scripts/connections-5m-allowlist.json b/scripts/connections-5m-allowlist.json new file mode 100644 index 0000000000..c66cd5fdee --- /dev/null +++ b/scripts/connections-5m-allowlist.json @@ -0,0 +1,6 @@ +{ + "description": "connections-5m (CON-5M) runs only for the frameworks listed here. Holding five million connections, a server may grow to 128 GiB, so the field is chosen rather than open: subscribing to connections-5m in meta.json is not enough on its own. scripts/lib/framework.sh reads this file.", + "frameworks": [ + "genhttp-ioxide" + ] +} diff --git a/scripts/gen_leaderboard_data.py b/scripts/gen_leaderboard_data.py index 5f39d2d631..6e8d416f91 100644 --- a/scripts/gen_leaderboard_data.py +++ b/scripts/gen_leaderboard_data.py @@ -60,6 +60,27 @@ # application handler to await in. ("async", "Async Delay", "A 10ms wait named in the route, at 32K held connections.", [32000], [32000], True,True,False), + # The held-connection profiles: a fleet of keep-alive connections held + # open, with the baseline GET paced across it at one request per + # connection every four seconds. They sit here because what they vary is + # how many connections are open, which is this group's question. Paced, + # so they carry a fixed-rate score (latency_score.HELD): what holding the + # fleet costs - CPU per request, memory, p50 and p99 - against the best + # in the field, times the share of the rate delivered. + # + # CON-1M: a million at 250K req/s on zrk 3.0.2, one process per loopback + # address (scripts/zrk_fanout.py). CON-1M-TLS: a million TLS 1.3 sessions + # at 250K req/s on gcannon. Both scored for frameworks and engines, not + # infrastructure, like the other fixed-rate profiles. + ("connections-1m", "CON-1M", "Score out of 100: CPU per request, memory, p50 and p99 latency with one million held connections at 250K req/s.", + [1000000], [1000000], True,True,False), + ("connections-1m-tls", "CON-1M-TLS", "Score out of 100: CPU per request, memory, p50 and p99 latency with one million TLS 1.3 sessions held at 250K req/s.", + [1000000], [1000000], True,True,False), + # CON-5M: five million at 1.25M req/s on gcannon. Reference-only, and it + # runs only for the entries on scripts/connections-5m-allowlist.json: the + # server may grow to 128 GiB, so the field is chosen rather than open. + ("connections-5m", "CON-5M", "Score out of 100 (reference): CPU per request, memory, p50 and p99 latency with five million held connections at 1.25M req/s.", + [5000000], [5000000], False,False,False), ]), ("Efficiency", [ # Scored, on the same terms as latency-1m below: the rate is pinned, so @@ -146,7 +167,7 @@ # Efficiency-only. Emitted like TPL_FIELDS - only where present - so the # other ~2,300 rows in data.js do not each grow four nulls. EFF_FIELDS = ("cpu_usec", "cpu_per_req_us", "rate_ratio", "target_rate", - "p99_9_latency") + "p99_9_latency", "connections_open", "p50_latency") # Map each benchmark profile to its Knowledge Base "Implementation Guidelines" # page (docs ids differ from profile ids; TLS gRPC variants share one page). @@ -161,6 +182,9 @@ "async": "test-profiles/h1/async/implementation", "latency-1m": "test-profiles/h1/latency-1m/implementation", "latency-10k": "test-profiles/h1/latency-10k/implementation", + "connections-1m": "test-profiles/h1/connections/implementation", + "connections-1m-tls": "test-profiles/h1/connections/implementation", + "connections-5m": "test-profiles/h1/connections/implementation", # The database profiles rank on their own board but keep their docs under # h1/: those pages are linked from outside, so their URLs stay. "async-db": "test-profiles/h1/async-database/implementation", @@ -1253,12 +1277,18 @@ def badge_aggregate(profiles, results): def lat_scores(pid): if pid in _LAT_CACHE: return _LAT_CACHE[pid] + # The exact profile's keys: "connections-1m-" also starts every + # "connections-1m-tls-" key. p50 and mem are read by the + # held-connection profiles' score only (latency_score.HELD). rows = [{"fw": r.get("framework") or r.get("fw"), "rps": r.get("rps") or 0, "cpu": r.get("cpu_per_req_us"), "p99": _lat.to_us(r.get("p99_latency")), - "mean": _lat.to_us(r.get("avg_latency"))} - for key, rs in RESULTS.items() if key.startswith(pid + "-") + "mean": _lat.to_us(r.get("avg_latency")), + "p50": _lat.to_us(r.get("p50_latency")), + "mem": _lat.to_mib(r.get("memory"))} + for key, rs in RESULTS.items() + if key.startswith(pid + "-") and key[len(pid) + 1:].isdigit() for r in rs] out: dict = {} if rows: diff --git a/scripts/latency_score.py b/scripts/latency_score.py index 484a13d384..04da0a7bc0 100755 --- a/scripts/latency_score.py +++ b/scripts/latency_score.py @@ -1,5 +1,7 @@ #!/usr/bin/env python3 -"""Scoring for the fixed-rate profiles: `latency-1m`, `latency-10k` and `8gbit`. +"""Scoring for the fixed-rate profiles: `latency-1m`, `latency-10k`, `8gbit`, and +the held-connection profiles `connections-1m`, `connections-1m-tls` and +`connections-5m` (CON-1M, CON-1M-TLS, CON-5M). Every other profile here ranks on one number, requests per second. This one cannot: the rate is pinned, so every entry that finishes serves the same load @@ -41,6 +43,26 @@ entry scores in the low-to-mid 90s because no single entry is simultaneously best on cost and on both tails, and that gap is information. +The held-connection profiles score what holding the fleet costs instead: + + rateFactor = min(1, achieved_rps / FULL_RATE[profile]) + quality = 0.25*cpuScore + 0.25*memScore + 0.25*p50Score + 0.25*p99Score + score = 100 * rateFactor * quality + + cpuScore = bestCpu / cpu (linear, CPU per request) + memScore = bestMem / mem (linear, the server's peak memory) + p50Score = 1 - log10(p50 / bestP50) / 3 (clamped to 0..1) + p99Score = 1 - log10(p99 / bestP99) / 3 (clamped to 0..1) + +A million connections held at one request every four seconds is mostly +waiting, so what separates servers is what the waiting costs: the memory each +connection keeps, the CPU a request carries while the rest of the fleet sits +in the poll set, and how long a request takes when it finally comes - typically +(p50) and in the tail (p99). Memory and CPU spread over a few times, so they +are plain ratios; both latencies get the three-decade scale the p99 has above. +The rate factor still applies: a connection that never opened sends nothing, so +a fleet only partly held shows up as a shortfall in the rate. + Two modes: latency_score.py --pick [--profile P] best of N runs (benchmark.sh) @@ -65,12 +87,28 @@ # Keep in step with LAT_FULL in site/leaderboard/index.html - check_badge_parity.js # compares the two and fails the deploy when they disagree. "8gbit": 47_500.0, + # Five million held connections at 1.25M req/s, measured on the window + # after the fleet is connected: 95% of the target, like the others. A + # connection that never opened sends nothing, so a fleet only partly held + # lands here as a rate shortfall. + "connections-5m": 1_187_500.0, + # A million held connections at 250K req/s, over TLS or on zrk, scored the + # same way. + "connections-1m-tls": 237_500.0, + "connections-1m": 237_500.0, } DEFAULT_PROFILE = "latency-1m" W_CPU, W_P99, W_MEAN = 0.50, 0.25, 0.25 DECADES = 3.0 # p99: a third of the term per decade above the best MEAN_DECADES = 1.0 # mean: ten times the best is zero +# The held-connection profiles: four equal terms. Keep in step with LAT_HELD +# and latBuild() in site/leaderboard/index.html - check_badge_parity.js runs the +# board's scoring against this one and fails the deploy when ranks disagree. +HELD = frozenset({"connections-1m", "connections-1m-tls", "connections-5m"}) +H_CPU, H_MEM, H_P50, H_P99 = 0.25, 0.25, 0.25, 0.25 +HELD_DECADES = 3.0 # p50 and p99: a third of the term per decade above the best + def to_us(value) -> float | None: """'173.0us' / '1.5ms' / '2s' -> microseconds. None when unparseable.""" @@ -85,6 +123,20 @@ def to_us(value) -> float | None: return v * {"us": 1.0, "ms": 1e3, "s": 1e6, None: 1.0}[m.group(2)] +def to_mib(value) -> float | None: + """'336MiB' / '71.2GiB' / '512KiB' -> MiB, the way mem() in index.html reads + the memory column. None when unparseable.""" + if value is None: + return None + if isinstance(value, (int, float)): + return float(value) + m = re.search(r"([\d.]+)\s*([KMG]i?B)", str(value), re.IGNORECASE) + if not m: + return None + v, u = float(m.group(1)), m.group(2).upper()[0] + return v * 1024 if u == "G" else v if u == "M" else v / 1024 + + def _clamp(v: float) -> float: return 0.0 if v < 0 else 1.0 if v > 1 else v @@ -108,7 +160,8 @@ def linear_score(value: float | None, best: float | None) -> float: def score_rows(rows: list[dict], profile: str = DEFAULT_PROFILE) -> list[dict]: - """Annotate rows with their score. Each row needs rps, cpu, p99, mean. + """Annotate rows with their score. Each row needs rps, cpu, p99, mean - and + mem and p50 on the held-connection profiles. Bests are taken over the rows given, so a caller scoring one framework's three runs gets them normalised against each other, and a caller scoring the @@ -118,6 +171,21 @@ def best_of(key): vals = [r[key] for r in rows if r.get(key)] return min(vals) if vals else None + if profile in HELD: + b_cpu, b_mem = best_of("cpu"), best_of("mem") + b_p50, b_p99 = best_of("p50"), best_of("p99") + for r in rows: + rf = rate_factor(r.get("rps") or 0, FULL_RATE[profile]) + cpu_s = linear_score(r.get("cpu"), b_cpu) + mem_s = linear_score(r.get("mem"), b_mem) + p50_s = decade_score(r.get("p50"), b_p50, HELD_DECADES) + p99_s = decade_score(r.get("p99"), b_p99, HELD_DECADES) + r["rateFactor"] = rf + r["cpuScore"], r["memScore"] = cpu_s, mem_s + r["p50Score"], r["p99Score"] = p50_s, p99_s + r["score"] = 100.0 * rf * (H_CPU * cpu_s + H_MEM * mem_s + H_P50 * p50_s + H_P99 * p99_s) + return rows + b_cpu, b_p99, b_mean = best_of("cpu"), best_of("p99"), best_of("mean") for r in rows: rf = rate_factor(r.get("rps") or 0, FULL_RATE[profile]) @@ -163,6 +231,10 @@ def pick(dirpath: str, profile: str = DEFAULT_PROFILE) -> int | None: "cpu": (cpu_usec / reqs) if (reqs > 0 and cpu_usec > 0) else None, "p99": to_us(kv.get("p99_lat")), "mean": to_us(kv.get("avg_lat")), + # The held-connection profiles also weigh the typical request and + # the run's peak memory (benchmark.sh writes stats_mem per run). + "p50": to_us(kv.get("p50_lat")), + "mem": to_mib(meta.get("stats_mem")), }) if not rows: return None @@ -178,7 +250,9 @@ def table(results_dir: Path, profile: str = DEFAULT_PROFILE) -> None: except Exception: continue for key, r in (d.get("results") or {}).items(): - if not key.startswith(profile + "-"): + # The exact profile: "connections-1m-" also starts every + # "connections-1m-tls-..." key. + if not (key.startswith(profile + "-") and key[len(profile) + 1:].isdigit()): continue rows.append({ "fw": d.get("framework", f.stem), @@ -186,12 +260,25 @@ def table(results_dir: Path, profile: str = DEFAULT_PROFILE) -> None: "cpu": r.get("cpu_per_req_us"), "p99": to_us(r.get("p99_latency")), "mean": to_us(r.get("avg_latency")), + "p50": to_us(r.get("p50_latency")), + "mem": to_mib(r.get("memory")), }) if not rows: print(f"no {profile} results found", file=sys.stderr) return score_rows(rows, profile) rows.sort(key=lambda r: -r["score"]) + if profile in HELD: + print("%-24s %7s %7s %9s %10s %11s %11s" % + ("framework", "score", "rate", "us/req", "mem MiB", "p50", "p99")) + for r in rows: + print("%-24s %7.1f %7.3f %9s %10s %11s %11s" % ( + r["fw"], r["score"], r["rateFactor"], + "-" if r["cpu"] is None else f"{r['cpu']:.1f}", + "-" if r["mem"] is None else f"{r['mem']:.0f}", + "-" if r["p50"] is None else f"{r['p50']:.0f}", + "-" if r["p99"] is None else f"{r['p99']:.0f}")) + return print("%-24s %7s %7s %9s %11s %11s" % ("framework", "score", "rate", "us/req", "mean", "p99")) for r in rows: diff --git a/scripts/lib/common.sh b/scripts/lib/common.sh index 2bda2a7d4a..4808750d07 100644 --- a/scripts/lib/common.sh +++ b/scripts/lib/common.sh @@ -76,6 +76,42 @@ HARD_NOFILE=$(ulimit -Hn 2>/dev/null || echo 1048576) [[ "$HARD_NOFILE" =~ ^[0-9]+$ ]] || HARD_NOFILE=1048576 ulimit -n "$HARD_NOFILE" 2>/dev/null || true +# The held-connection profiles' server container. HARD_NOFILE is whatever the +# shell running the harness was given, which can be below the fleet; these +# profiles need a socket per connection plus the server's own, so the container +# gets these instead (capped at fs.nr_open, which system_tune_held_connections +# raises). The memory cap keeps an entry from taking the host down with it: it +# is OOM-killed and the run reports what it held. +# +# The 5M caps are what the 251 GiB bench host has left after the fleet itself: +# ~4 KiB of gcannon and ~8 KiB of kernel (both sockets and a conntrack entry) +# per connection is ~57 GiB at five million; a server spending ~25 KiB per +# connection fits in 128g. The million-connection profiles (connections-1m-tls, +# connections-1m) get the 1M caps. Over TLS the kernel adds ~4 KiB of TLS +# state per socket on each side that uses it, so the fleet costs ~20 KiB a +# connection, ~19 GiB at a million, besides the server. +CONN1M_NOFILE="${CONN1M_NOFILE:-2097152}" +CONN1M_MEM_LIMIT="${CONN1M_MEM_LIMIT:-96g}" +CONN5M_NOFILE="${CONN5M_NOFILE:-8388608}" +CONN5M_MEM_LIMIT="${CONN5M_MEM_LIMIT:-128g}" + +# Between held-connection runs the harness waits for the host's TCP socket +# count to come back down (system.sh, held_conn_drain) instead of sleeping: to +# within HELD_CONN_DRAIN_SLACK of what it held before the first profile, giving +# up after HELD_CONN_DRAIN_STALL seconds without progress or +# HELD_CONN_DRAIN_TIMEOUT seconds in all. +HELD_CONN_DRAIN_SLACK="${HELD_CONN_DRAIN_SLACK:-50000}" +HELD_CONN_DRAIN_STALL="${HELD_CONN_DRAIN_STALL:-30}" +HELD_CONN_DRAIN_TIMEOUT="${HELD_CONN_DRAIN_TIMEOUT:-600}" + +# " " for a held-connection profile's server container. +held_conn_limits() { + case "$1" in + connections-5m) echo "$CONN5M_NOFILE $CONN5M_MEM_LIMIT" ;; + *) echo "$CONN1M_NOFILE $CONN1M_MEM_LIMIT" ;; + esac +} + # Postgres sidecar. PG_CONTAINER="httparena-postgres" DATABASE_URL="postgres://bench:bench@localhost:5432/benchmark" diff --git a/scripts/lib/framework.sh b/scripts/lib/framework.sh index 839ad24ea6..382d4937af 100644 --- a/scripts/lib/framework.sh +++ b/scripts/lib/framework.sh @@ -52,8 +52,20 @@ framework_validate_tests() { known profiles: $(printf '%s\n' "${!PROFILES[@]}" | sort | tr '\n' ' ')" } +# connections-5m runs only for the entries on scripts/connections-5m-allowlist.json. +# Holding five million connections a server may grow to 128 GiB, so the field is +# chosen rather than open: subscribing in meta.json is not enough on its own. +CONN5M_ALLOWLIST="${CONN5M_ALLOWLIST:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)/connections-5m-allowlist.json}" +conn5m_allowed() { + python3 -c 'import json, sys +sys.exit(0 if sys.argv[2] in (json.load(open(sys.argv[1])).get("frameworks") or []) else 1)' \ + "$CONN5M_ALLOWLIST" "$FRAMEWORK" 2>/dev/null +} + framework_subscribes_to() { local profile="$1" + # Not on the allowlist: not subscribed, whatever meta.json says. + if [ "$profile" = "connections-5m" ] && ! conn5m_allowed; then return 1; fi [ -z "$FRAMEWORK_TESTS" ] && return 0 echo ",$FRAMEWORK_TESTS," | grep -qF ",$profile," } @@ -82,11 +94,24 @@ framework_start() { docker stop -t 5 "$CONTAINER_NAME" 2>/dev/null || true docker rm -f "$CONTAINER_NAME" 2>/dev/null || true + # The held-connection profiles hold millions of sockets, more than + # HARD_NOFILE may allow; their own limit is capped at fs.nr_open, the + # ceiling the kernel enforces (common.sh held_conn_limits). + local nofile="$HARD_NOFILE" mem_limit="${FRAMEWORK_MEM_LIMIT:-}" + if held_conn_profile "$endpoint"; then + local nr_open held_nofile held_mem + nr_open=$(cat /proc/sys/fs/nr_open 2>/dev/null || echo "$HARD_NOFILE") + read -r held_nofile held_mem <<< "$(held_conn_limits "$endpoint")" + nofile="$held_nofile" + [ "$nofile" -gt "$nr_open" ] 2>/dev/null && nofile="$nr_open" + [ -n "$mem_limit" ] || mem_limit="$held_mem" + fi + local args=( -d --name "$CONTAINER_NAME" --network host --security-opt seccomp=unconfined --ulimit memlock=-1:-1 - --ulimit nofile="$HARD_NOFILE:$HARD_NOFILE" + --ulimit nofile="$nofile:$nofile" -v "$DATA_DIR/dataset.json:/data/dataset.json:ro" -v "$DATA_DIR/static:/data/static:ro" -v "$CERTS_DIR:/certs:ro" @@ -97,9 +122,10 @@ framework_start() { # Empty is the default and leaves every other caller (benchmark, validate, # spec) exactly as before. --memory-swap equal to --memory disables swap, so # an over-limit server is OOM-killed deterministically instead of silently - # swapping and merely getting slow. - if [ -n "${FRAMEWORK_MEM_LIMIT:-}" ]; then - args+=(--memory="$FRAMEWORK_MEM_LIMIT" --memory-swap="$FRAMEWORK_MEM_LIMIT") + # swapping and merely getting slow. The held-connection profiles set one + # of their own (held_conn_limits) when the caller did not. + if [ -n "$mem_limit" ]; then + args+=(--memory="$mem_limit" --memory-swap="$mem_limit") fi # Profiles that exercise the database get DATABASE_URL + per-profile conn cap. diff --git a/scripts/lib/profiles.sh b/scripts/lib/profiles.sh index 539e38146d..0f9ae70dc3 100644 --- a/scripts/lib/profiles.sh +++ b/scripts/lib/profiles.sh @@ -77,6 +77,44 @@ declare -A PROFILES=( # poll loops, timers, background GC, wakeups. A busy box amortises those # away; this one does not. [latency-10k]="1|0|0-31,64-95|1024|latency-10k" + # Connections-5M: five million keep-alive connections held at once, with + # the baseline GET paced at 1.25M req/s across them (GCANNON_RATE_CONNECTIONS_5M) + # - one request per connection every four seconds. At that rate the work + # per request is a fraction of what a fast server carries on this cpuset, + # so what separates entries is what holding the rest of the fleet costs: + # memory per connection, the CPU a request carries while the others wait, + # and the tail once a heap, a timer wheel or a poll set is that large. + # Measured on gcannon's window after the whole fleet is connected. + # + # One source address can open about 64.5K connections to one destination + # (the async comment above), so gcannon spreads the fleet over the + # loopback addresses 127.0.0.1 .. 127.0.0.160 (--addr-span), 31,250 on + # each - the density the million-connection runs proved. An entry must + # listen on 0.0.0.0 or [::] to subscribe; validate.sh checks it, and + # scripts/conn_hold.py probes it before the run. Needs gcannon >= 0.8.2. + # Opt-in and reference-only while the first field is measured. + # + # Not zrk: even 3.0.2 keeps ~41 KiB per connection, ~200 GiB for five + # million. gcannon holds one in ~3.3 KiB. + [connections-5m]="1|0|0-31,64-95|5000000|connections-5m" + # connections-5m over TLS 1.3 on the h1 TLS port (8081), at a million + # connections and 250K req/s - still one request per connection every four + # seconds - over 127.0.0.1-.32: every connection handshakes once, then + # carries its requests encrypted. gcannon hands each session to kernel TLS + # after the handshake, so its side costs what a plaintext connection does + # plus the kernel's record state; what the server keeps per TLS session is + # the point. A million for now: five million over TLS was still connecting + # 7.7 min into its first run. Needs gcannon >= 0.8.4, which paces the + # handshakes to the server (MDA2AV/gcannon#33). + [connections-1m-tls]="1|0|0-31,64-95|1000000|connections-1m-tls" + # CON-1M: a million connections at 250K req/s with zrk 3.0.2 as the generator + # (run next to gcannon, it found gcannon 0.8.0's --rate bursts, MDA2AV/gcannon#30). + # Scored, like CON-1M-TLS (latency_score.HELD); CON-5M is reference-only and + # runs only for the entries on scripts/connections-5m-allowlist.json. + # zrk takes one URL, so tools/zrk.sh runs one process per loopback address + # (scripts/zrk_fanout.py) and merges their histograms. It stays at a + # million: zrk's ~41 KiB per connection rules out five. + [connections-1m]="1|0|0-31,64-95|1000000|connections-1m" [json-comp]="1|0|0-31,64-95|4096,16384|json-compressed" [json-tls]="1|0|0-31,64-95|4096|json-tls" # 8Gbit: 100 KB up and the same 100 KB back, over TLS. The only profile @@ -131,8 +169,23 @@ PROFILE_ORDER=( # TIME_WAIT for the kernel's fixed ~60s, so anything scheduled after it # starts against a nearly full port table. async + # After even that, for the same reason a hundred times over: millions of + # sockets closing at once, and millions of conntrack entries ageing out. + connections-5m + connections-1m-tls + connections-1m ) +# The held-connection profiles. Everything the harness does around their load +# (host limits, the server's fd and memory caps, the window CPU, the held +# count) is the same for all three; only the generator and the scale differ. +held_conn_profile() { + case "$1" in + connections-5m|connections-1m-tls|connections-1m) return 0 ;; + esac + return 1 +} + # ── Parsing + validation ──────────────────────────────────────────────────── # Parse a profile spec string into global fields. Exits on malformed input. @@ -163,7 +216,7 @@ endpoint_tool() { # wrk (lua script rotation) static-tls|json-tls) echo "wrk" ;; # zrk — the only paced generator; holds a fixed offered rate - latency-1m|latency-10k|8gbit) echo "zrk" ;; + latency-1m|latency-10k|8gbit|connections-1m) echo "zrk" ;; # h2load for all HTTP/2 variants (TLS via ALPN + h2c prior-knowledge) h2|static-h2|h2c|json-h2c|gateway-64|grpc|grpc-tls|production-stack) echo "h2load" ;; # h2load built with ngtcp2 for HTTP/3 diff --git a/scripts/lib/spec.sh b/scripts/lib/spec.sh index f8556c9c4f..448761499c 100644 --- a/scripts/lib/spec.sh +++ b/scripts/lib/spec.sh @@ -14,7 +14,7 @@ SPEC_SUITES="" # listener, ws the /ws echo. spec_profiles_for() { case "$1" in - h1) echo "baseline pipelined limited-conn json-comp async async-db fortunes latency-1m latency-10k latency-500k-8cpu" ;; + h1) echo "baseline pipelined limited-conn json-comp async async-db fortunes latency-1m latency-10k connections-1m connections-1m-tls connections-5m" ;; h2) echo "baseline-h2 static-h2 baseline-h2c json-h2c" ;; h3) echo "baseline-h3 static-h3" ;; ws) echo "echo-ws echo-ws-pipeline echo-ws-limited" ;; diff --git a/scripts/lib/system.sh b/scripts/lib/system.sh index fb97b9a5da..4cbf748a9b 100644 --- a/scripts/lib/system.sh +++ b/scripts/lib/system.sh @@ -90,6 +90,112 @@ system_tune() { sync } +# Raise a sysctl to at least `want`; never lowers one that is already higher. +_raise_sysctl() { + local key="$1" want="$2" have + have=$(sysctl -n "$key" 2>/dev/null) || { warn "sysctl $key is not available"; return 0; } + [ "$have" -ge "$want" ] 2>/dev/null && return 0 + sudo sysctl -w "$key=$want" >/dev/null 2>&1 || warn "could not raise $key ($have < $want)" +} + +# The limits millions of held connections run into, raised only when the run +# includes a held-connection profile (connections-5m, connections-1m-tls, +# connections-1m). Each one is a ceiling rather than a setting, so a host +# left with them raised measures every other profile exactly as before; like +# the governor, they are not put back. +# +# fs.nr_open the most fds a process may be given, and the +# ceiling on RLIMIT_NOFILE. Five million sockets +# in one server, and five million more in one +# gcannon, need 8M (CONN5M_NOFILE) to be allowed +# vm.max_map_count zrk (connections-1m) maps a stack plus a +# guard per coroutine: ~4 maps a connection, +# ~125K for one process's 31,250, against a +# 65,530 default +# net.netfilter.nf_conntrack_max +# docker's rules switch conntrack on for the +# host, loopback included, and a full table drops +# SYNs. Five million live entries plus the last +# run's five million in TIME_WAIT (120s) need +# room for both +# nf_conntrack hashsize so those entries are not chained deep in a +# table sized for a quarter of a million +system_tune_held_connections() { + info "raising host limits for the held-connection profiles" + _raise_sysctl fs.nr_open 16777216 + _raise_sysctl vm.max_map_count 4194304 + if [ -e /proc/sys/net/netfilter/nf_conntrack_max ]; then + _raise_sysctl net.netfilter.nf_conntrack_max 16777216 + local hs=/sys/module/nf_conntrack/parameters/hashsize + if [ -r "$hs" ] && [ "$(cat "$hs" 2>/dev/null || echo 0)" -lt 4194304 ] 2>/dev/null; then + sudo sh -c "echo 4194304 > $hs" 2>/dev/null || warn "could not raise the conntrack hash size" + fi + fi +} + +# ── Held connections: wait out the last fleet ─────────────────────────────── +# +# A held-connection run ends with millions of sockets to close, and a process +# exiting does not close them by itself: gcannon before 0.8.3 leaves its whole +# fleet to one kernel worker after it exits, and a server stopped while still +# holding its side hands that to the kernel the same way. On the bench host a +# 60 s cool-down was shorter than that: runs 2 and 3 of connections-5m +# connected in 178 s and 300 s against run 1's 63 s, with 28-31 GiB less memory +# available, and measured p50 6.0 / 7.5 ms against 0.35 ms. So the harness +# waits for the socket count to come back down rather than for a fixed time. + +# TCP sockets the kernel holds in any state but TIME_WAIT (kept apart, capped by +# tcp_max_tw_buckets): "alloc" in /proc/net/sockstat. A socket counts until it +# is freed, so a fleet still being closed after its process exited counts too. +host_tcp_sockets() { + awk '$1 == "TCP:" { for (i = 2; i < NF; i += 2) if ($i == "alloc") { print $(i + 1); exit } }' \ + /proc/net/sockstat 2>/dev/null || true +} + +# What a drain waits to get under: the host's count with nothing of ours +# running, plus HELD_CONN_DRAIN_SLACK. Taken once, before the first profile; a +# host still closing someone else's fleet counts as holding 20,000 at most. +HELD_CONN_DRAIN_TARGET="" +held_conn_baseline() { + local base + base=$(host_tcp_sockets) + [ -n "$base" ] || return 0 + if [ "$base" -gt 20000 ]; then + warn "the host already holds $base TCP sockets; held-connection runs wait for it to get under $((20000 + HELD_CONN_DRAIN_SLACK))" + base=20000 + fi + HELD_CONN_DRAIN_TARGET=$((base + HELD_CONN_DRAIN_SLACK)) +} + +# held_conn_drain : wait until the host is back under +# HELD_CONN_DRAIN_TARGET. Gives up, and says so, when the count has not fallen +# by a thousand in HELD_CONN_DRAIN_STALL seconds (a server that never closes its +# side: stopping it hands the rest to the kernel, and the next drain waits for +# that) or after HELD_CONN_DRAIN_TIMEOUT seconds in all. +held_conn_drain() { + local when="$1" cur + [ -n "$HELD_CONN_DRAIN_TARGET" ] || return 0 + cur=$(host_tcp_sockets) + [ -n "$cur" ] || return 0 + [ "$cur" -le "$HELD_CONN_DRAIN_TARGET" ] && return 0 + local from=$cur start=$SECONDS best=$cur best_at=$SECONDS + while [ "$cur" -gt "$HELD_CONN_DRAIN_TARGET" ]; do + if [ $((SECONDS - start)) -ge "$HELD_CONN_DRAIN_TIMEOUT" ]; then + warn "teardown $when: $cur TCP sockets still open after ${HELD_CONN_DRAIN_TIMEOUT}s (from $from); going on" + return 0 + fi + if [ $((SECONDS - best_at)) -ge "$HELD_CONN_DRAIN_STALL" ]; then + warn "teardown $when: stuck at $cur TCP sockets for ${HELD_CONN_DRAIN_STALL}s (from $from); going on" + return 0 + fi + sleep 1 + cur=$(host_tcp_sockets) + [ -n "$cur" ] || return 0 + if [ "$cur" -lt $((best - 1000)) ]; then best=$cur; best_at=$SECONDS; fi + done + info "teardown $when: $from -> $cur TCP sockets in $((SECONDS - start))s" +} + # Revert everything we touched. Call from EXIT trap. system_restore() { info "restoring loopback MTU to 65536" diff --git a/scripts/lib/tools/gcannon.sh b/scripts/lib/tools/gcannon.sh index a133c7dd90..4cfefd8d0b 100644 --- a/scripts/lib/tools/gcannon.sh +++ b/scripts/lib/tools/gcannon.sh @@ -4,6 +4,40 @@ # and gRPC plaintext (indirectly via -H and -d, though we use h2load for # that in practice). This file owns the gcannon ↔ driver interface. +# connections-5m: five million keep-alive connections +# with 1.25M req/s paced over them, one request per connection every four +# seconds, so what is left to measure is what holding the rest of the fleet +# costs. Four seconds stays inside the 5s keep-alive default of Node, uvicorn +# and actix: at five (1M req/s) actix's timeouts raced every request, 51,410 +# reconnects at 16,000 connections against none at four. Needs gcannon >= 0.8.2 +# (--rate with every thread spread over the interval, --addr-span, +# --connect-limit, --warmup-max, --settle); scripts/conn_hold.py checks. +# +# One source address holds ~64.5K connections to one destination, so the +# fleet spans 127.0.0.1-127.0.0.CONN5M_ADDRS (31,250 on each of 160, the +# density the million-connection runs held). First connects are capped per +# thread so five million SYNs never land at once, and the warmup waits for all +# of them to open: up to CONN5M_WARMUP_MAX. The load then runs CONN5M_SETTLE +# more seconds before the 20s window opens: genhttp-ioxide's first 5M run, +# measured from the moment the last connection opened, answered 670K more +# requests in the window than were sent in it (p50 10 ms, p90 390 ms) - the +# connect phase's backlog, not the steady state. +GCANNON_RATE_CONNECTIONS_5M="${GCANNON_RATE_CONNECTIONS_5M:-1250000}" +CONN5M_ADDRS="${CONN5M_ADDRS:-160}" +CONN5M_CONNECT_LIMIT="${CONN5M_CONNECT_LIMIT:-64}" +CONN5M_WARMUP_MAX="${CONN5M_WARMUP_MAX:-300}" +CONN5M_SETTLE="${CONN5M_SETTLE:-30}" + +# connections-1m-tls: the same over TLS 1.3, at a million connections and +# 250K req/s - the same four-second interval - over 127.0.0.1-.32, the same +# 31,250 per address. The warmup may take longer, since every connection also +# handshakes; gcannon >= 0.8.4 holds each --connect-limit slot until the +# handshake is done, so the server never has more than 64 per client thread +# waiting (MDA2AV/gcannon#33). It shares CONN5M_CONNECT_LIMIT and CONN5M_SETTLE. +GCANNON_RATE_CONNECTIONS_1M_TLS="${GCANNON_RATE_CONNECTIONS_1M_TLS:-250000}" +CONN1M_TLS_ADDRS="${CONN1M_TLS_ADDRS:-32}" +CONN1M_TLS_WARMUP_MAX="${CONN1M_TLS_WARMUP_MAX:-900}" + # ── Build arguments ───────────────────────────────────────────────────────── # Usage: gcannon_build_args [req_per_conn] @@ -80,6 +114,28 @@ gcannon_build_args() { # redoes the HTTP/1.1 upgrade, which is what that profile measures. [ "$req_per_conn" -gt 0 ] 2>/dev/null && args+=(-r "$req_per_conn") ;; + connections-5m|connections-1m-tls) + # The baseline GET: what varies here is how many connections are + # held, so the request stays the one subscribers are already + # validated on - plaintext on PORT, or TLS 1.3 on H1TLS_PORT + # (https:// makes gcannon handshake, then hand the session to + # kernel TLS). gcannon_run hands the --args-- part to + # scripts/conn_hold.py, which owns everything around the load. + local url="http://127.0.0.1:$PORT/baseline11?a=1&b=2" + local hport="$PORT" warm="$CONN5M_WARMUP_MAX" + local rate="$GCANNON_RATE_CONNECTIONS_5M" addrs="$CONN5M_ADDRS" + if [ "$endpoint" = "connections-1m-tls" ]; then + url="https://127.0.0.1:$H1TLS_PORT/baseline11?a=1&b=2" + hport="$H1TLS_PORT" warm="$CONN1M_TLS_WARMUP_MAX" + rate="$GCANNON_RATE_CONNECTIONS_1M_TLS" addrs="$CONN1M_TLS_ADDRS" + fi + args=(--hold-- "$endpoint" "$conns" "$rate" "$hport" "$warm" "$addrs" + --args-- "$url" + -c "$conns" -t "$THREADS" -d 20s + --rate "$rate" --addr-span "$addrs" + --connect-limit "$CONN5M_CONNECT_LIMIT" + --warmup-max "${warm}s" --settle "${CONN5M_SETTLE}s" --json) + ;; *) fail "gcannon_build_args: unknown endpoint '$endpoint'" ;; @@ -93,6 +149,10 @@ gcannon_build_args() { # Run gcannon with the given args, return output on stdout. # Honors GCANNON_MODE=native|docker. gcannon_run() { + if [ "${1:-}" = "--hold--" ]; then + _gcannon_hold_run "${@:2}" + return 0 + fi local -a args=("$@") if [ "$GCANNON_MODE" = "native" ]; then timeout 45 taskset -c "$GCANNON_CPUS" \ @@ -107,13 +167,96 @@ gcannon_run() { fi } +# connections-5m / connections-1m-tls: gcannon under scripts/conn_hold.py, +# which probes the listener, refuses a run the host cannot hold, raises the +# open-file limit for the fleet, and reads the server cgroup's CPU at +# gcannon's window markers. stdout is the wrapper's JSON summary; stderr +# (gcannon's own lines) goes straight to the log. +_gcannon_hold_run() { + local profile="$1" conns="$2" rate="$3" hport="$4" warm="$5" addrs="$6" + shift 6 + [ "${1:-}" = "--args--" ] && shift + local nofile mem + read -r nofile mem <<< "$(held_conn_limits "$profile")" + local -a prefix + if [ "$GCANNON_MODE" = "native" ]; then + prefix=(taskset -c "$GCANNON_CPUS" env LD_LIBRARY_PATH=/usr/lib "$GCANNON") + else + prefix=(docker run --rm --network host --cpuset-cpus="$GCANNON_CPUS" + --security-opt seccomp=unconfined + --ulimit memlock=-1:-1 --ulimit nofile="$nofile:$nofile" + -v "$REQUESTS_DIR:$REQUESTS_DIR:ro" "$GCANNON_IMAGE") + fi + local cpu_stat="" + if [ -n "${CONTAINER_NAME:-}" ]; then + cpu_stat=$(_cgroup_cpu_path "$CONTAINER_NAME" 2>/dev/null) || cpu_stat="" + fi + # Kernel memory per connection: both sockets and a conntrack entry, and + # over TLS a kernel TLS context on each side that uses one (gcannon's + # always, the server's when it offloads too). + local kernel_kib=8 + [ "$profile" = "connections-1m-tls" ] && kernel_kib=16 + timeout $(( warm + CONN5M_SETTLE + 20 + 300 )) python3 "$SCRIPT_DIR/conn_hold.py" \ + --profile "$profile" --conns "$conns" --rate "$rate" --port "$hport" \ + --probe "127.0.0.2,127.0.0.$addrs" --span "127.0.0.1-127.0.0.$addrs" \ + ${cpu_stat:+--cpu-stat "$cpu_stat"} --server-mem "${FRAMEWORK_MEM_LIMIT:-$mem}" \ + --kib-per-conn 4 --kernel-kib-per-conn "$kernel_kib" \ + -- "${prefix[@]}" --args-- "$@" || true +} + # ── Parse output ──────────────────────────────────────────────────────────── +# connections-5m / connections-1m-tls: the fixed-rate keys benchmark.sh reads (the same ones +# zrk_parse emits for the latency profiles), from conn_hold.py's summary. +_gcannon_hold_parse() { + python3 - "$1" <<'PY' +import json, sys +raw = sys.argv[1] +s, e = raw.find("{"), raw.rfind("}") +try: + d = json.loads(raw[s:e + 1]) if s >= 0 and e > s else {} +except ValueError: + d = {} +if not d: + sys.stderr.write("[gcannon] no held-connection summary in the output:\n%s\n" % (raw[:2000] or "")) +lat = d.get("latency_us") or {} +codes = d.get("status_codes") or {} +print("rps=%d" % round(d.get("rps") or 0)) +print("avg_lat=%.1fus" % (lat.get("mean") or 0)) +# The median, which the held-connection score weighs (latency_score.HELD). +print("p50_lat=%.1fus" % (lat.get("p50") or 0)) +print("p99_lat=%.1fus" % (lat.get("p99") or 0)) +print("p999_lat=%.1fus" % (lat.get("p99_9") or 0)) +print("reconnects=%d" % (d.get("reconnects") or 0)) +print("bandwidth=%.2fMB/s" % ((d.get("bytes_per_sec") or 0) / 1e6)) +for k in ("2xx", "3xx", "4xx", "5xx"): + print("status_%s=%d" % (k, codes.get(k) or 0)) +print("rate_ratio=%.4f" % (d.get("rate_ratio") or 0)) +print("duration=%.0fs" % (d.get("duration_s") or 0)) +print("target_rate=%d" % (d.get("target_rate") or 0)) +print("max_schedule_lag_us=%d" % (d.get("max_schedule_lag_us") or 0)) +if d.get("connections_open") is not None: + print("connections_open=%d" % d["connections_open"]) +print("connect_errors=%d" % ((d.get("errors") or {}).get("connect") or 0)) +if d.get("server_cpu_usec") is not None: + print("cpu_usec_window=%d" % d["server_cpu_usec"]) +if d.get("hold_error"): + print("hold_error=%s" % " ".join(str(d["hold_error"]).split())) +PY +} + # Usage: gcannon_parse # Echoes KEY=VALUE lines. Caller reads into an assoc array. gcannon_parse() { local endpoint="$1" output="$2" + case "$endpoint" in + connections-5m|connections-1m-tls) + _gcannon_hold_parse "$output" + return 0 + ;; + esac + # rps — compute from 2xx (or 3xx for caching, or WS frames for ws-echo) # divided by the actual measured duration. # diff --git a/scripts/lib/tools/zrk.sh b/scripts/lib/tools/zrk.sh index 8a26f95dff..78f0665b3b 100644 --- a/scripts/lib/tools/zrk.sh +++ b/scripts/lib/tools/zrk.sh @@ -48,6 +48,63 @@ ZRK_RATE_LATENCY_1M="${ZRK_RATE_LATENCY_1M:-1000000}" ZRK_RATE_LATENCY_10K="${ZRK_RATE_LATENCY_10K:-10000}" ZRK_RATE_8GBIT="${ZRK_RATE_8GBIT:-50000}" +# connections-1m: a million held connections at 250K req/s, one request per +# connection every four seconds, with zrk as the load generator. Run next to +# gcannon at the same scale (tools/gcannon.sh), it caught gcannon 0.8.0's +# --rate bursts (MDA2AV/gcannon#30). +# +# Its own zrk, 3.0.2, while the profiles above stay on the pinned 2.3.0 (a bump +# re-baselines them). 2.3.0 kept ~303 KiB per connection and took the bench +# host down at a million; 3.0.2 keeps ~41 KiB (measured at 4K and 16K). The +# image is docker/zrk.Dockerfile built with this version and checksum. +ZRK_RATE_CONNECTIONS_1M="${ZRK_RATE_CONNECTIONS_1M:-250000}" +ZRK_CONN1M_VERSION="${ZRK_CONN1M_VERSION:-3.0.2}" +ZRK_CONN1M_SHA256="${ZRK_CONN1M_SHA256:-339ade3ba435f14ea3c15ab8e97a880d931e14604857cde01aea1797e7430cbf}" +ZRK_CONN1M_IMAGE="${ZRK_CONN1M_IMAGE:-zrk:$ZRK_CONN1M_VERSION}" +: "${ZRK_CONN1M_CMD:=}" + +# How the fleet is spread (scripts/zrk_fanout.py has the why). zrk takes one +# URL, so one process per loopback address 127.0.0.1..127.0.0.ZRK_FANOUT_ADDRS, +# 31,250 connections and 2 threads each (64 in all, like gcannon's -t). Each +# opens all of its connections the moment it starts, so processes start +# STAGGER seconds apart, SETTLE seconds after the last start are discarded, +# WINDOW seconds are measured, and TAIL seconds keep the fleet up while the +# open connections are counted (ss walking a million sockets; a count that +# outlasts the tail would see zrk's own closes). +ZRK_FANOUT_ADDRS="${ZRK_FANOUT_ADDRS:-32}" +ZRK_FANOUT_STAGGER="${ZRK_FANOUT_STAGGER:-1}" +ZRK_FANOUT_SETTLE="${ZRK_FANOUT_SETTLE:-10}" +ZRK_FANOUT_WINDOW="${ZRK_FANOUT_WINDOW:-20}" +ZRK_FANOUT_TAIL="${ZRK_FANOUT_TAIL:-20}" +# The fan-out refuses a run the host cannot hold at this much per connection +# and caps each zrk container at half again over it, so an overrun is +# OOM-killed in its own cgroup instead of taking the bench host down. +ZRK_KIB_PER_CONN="${ZRK_KIB_PER_CONN:-48}" + +# The zrk connections-1m runs: ZRK_CONN1M_CMD when set (benchmark.sh sets +# it at startup), else a zrk on PATH if it is new enough. Printed one word per +# line; the fan-out asks it for --version and refuses anything older. +_zrk_conn1m_cmd() { + if [ -n "$ZRK_CONN1M_CMD" ]; then + printf '%s\n' $ZRK_CONN1M_CMD + elif _zrk_at_least "$ZRK" "$ZRK_CONN1M_VERSION"; then + printf '%s\n' "$ZRK" + else + printf '%s\n' docker run --rm --network host \ + --cpuset-cpus="$GCANNON_CPUS" --security-opt seccomp=unconfined \ + --ulimit memlock=-1:-1 --ulimit nofile=1048576:1048576 "$ZRK_CONN1M_IMAGE" + fi +} + +# True when binary $1 is on PATH and reports a version >= $2. +_zrk_at_least() { + command -v "$1" >/dev/null 2>&1 || return 1 + local have + have=$("$1" --version 2>/dev/null | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1) + [ -n "$have" ] || return 1 + [ "$(printf '%s\n%s\n' "$2" "$have" | sort -V | head -1)" = "$2" ] +} + # The body zrk posts to /echo. zrk takes a single body (-b @FILE), so unlike the # wrk script this profile used to run there is no eight-way rotation making a # canned response wrong seven times out of eight. The anti-cheat therefore rests @@ -78,6 +135,18 @@ sys.stdout.buffer.write((unit * (n // len(unit) + 1))[:n]) zrk_build_args() { local endpoint="$1" conns="$2" pipeline="$3" duration="$4" local -a cmd + + # The baseline GET over plaintext, as on connections-5m. One zrk cannot + # hold a million connections to one address, so zrk_run fans this out; + # the sentinel carries what it needs ahead of the zrk command itself. + # Handled before _zrk_cmd: this profile runs 3.0.2, not the pinned zrk. + if [ "$endpoint" = "connections-1m" ]; then + mapfile -t cmd < <(_zrk_conn1m_cmd) + printf '%s\n' --fanout-- "$conns" "$ZRK_RATE_CONNECTIONS_1M" "/baseline11?a=1&b=2" \ + -- "${cmd[@]}" + return 0 + fi + mapfile -t cmd < <(_zrk_cmd) case "$endpoint" in @@ -125,6 +194,10 @@ zrk_build_args() { # dashboard out of the log -- but --format json already suppresses the # dashboard, so all that redirect ever hid was the reason a run failed. zrk_run() { + if [ "${1:-}" = "--fanout--" ]; then + _zrk_fanout_run "${@:2}" + return 0 + fi if [ -n "$ZRK_CMD" ]; then timeout 60 "$@" || true else @@ -132,6 +205,39 @@ zrk_run() { fi } +# connections-1m: one zrk per loopback address, merged into one summary +# shaped like zrk's own (scripts/zrk_fanout.py). Its stdout is that summary, so +# the caller captures and parses it exactly as it would a single zrk's. +# +# The server cgroup's CPU is read by the fan-out at the edges of the measured +# window and reported as server_cpu_usec; benchmark.sh's own reading spans the +# whole run, a million connects included, so the window figure replaces it. +_zrk_fanout_run() { + local conns="$1" rate="$2" path="$3" + shift 3 + [ "${1:-}" = "--" ] && shift + local -a prefix=("$@") + # docker pins through --cpuset-cpus; a native zrk needs taskset. + [ "$(basename "${prefix[0]}")" = "docker" ] || prefix=(taskset -c "$GCANNON_CPUS" "${prefix[@]}") + local cpu_stat="" + if [ -n "${CONTAINER_NAME:-}" ]; then + cpu_stat=$(_cgroup_cpu_path "$CONTAINER_NAME" 2>/dev/null) || cpu_stat="" + fi + local addrs="$ZRK_FANOUT_ADDRS" nofile mem + read -r nofile mem <<< "$(held_conn_limits connections-1m)" + local total=$(( (addrs - 1) * ZRK_FANOUT_STAGGER + ZRK_FANOUT_SETTLE \ + + ZRK_FANOUT_WINDOW + ZRK_FANOUT_TAIL )) + timeout $(( total + 300 )) python3 "$SCRIPT_DIR/zrk_fanout.py" \ + --conns "$conns" --rate "$rate" --addrs "$addrs" \ + --port "$PORT" --path "$path" --threads "$THREADS" \ + --stagger "$ZRK_FANOUT_STAGGER" --settle "$ZRK_FANOUT_SETTLE" \ + --window "$ZRK_FANOUT_WINDOW" --tail "$ZRK_FANOUT_TAIL" \ + ${cpu_stat:+--cpu-stat "$cpu_stat"} --ss-cpus "$GCANNON_CPUS" \ + --kib-per-conn "$ZRK_KIB_PER_CONN" --server-mem "${FRAMEWORK_MEM_LIMIT:-$mem}" \ + --min-version "$ZRK_CONN1M_VERSION" \ + -- "${prefix[@]}" || true +} + # ── Parse output ──────────────────────────────────────────────────────────── # zrk writes the JSON summary to stdout under --format json. stderr carries the @@ -165,6 +271,8 @@ codes = d.get("status_codes") or {} print("rps=%d" % round(d.get("achieved_rate") or 0)) # lat() on the board reads us/ms/s, so hand it microseconds unconverted. print("avg_lat=%.1fus" % (lat.get("mean") or 0)) +# The median, which the held-connection profiles score (latency_score.HELD). +print("p50_lat=%.1fus" % (lat.get("p50") or 0)) print("p99_lat=%.1fus" % (lat.get("p99") or 0)) # p99.9 is not a field any other adapter produces, and the fixed-rate # score weights it, so it has to survive into the result row rather than @@ -190,5 +298,18 @@ print("rate_ratio=%.4f" % (d.get("rate_ratio") or 0)) print("duration=%.0fs" % (d.get("duration_s") or 0)) print("target_rate=%d" % (d.get("target_rate") or 0)) print("max_schedule_lag_us=%d" % (d.get("max_schedule_lag_us") or 0)) + +# connections-1m's fan-out adds these (scripts/zrk_fanout.py), under the +# keys gcannon's held-connection parser emits, so benchmark.sh reads both the +# same way. A single zrk summary has none of them. +if "fanout" in d or d.get("hold_error"): + for k in ("launched", "connections_open", "ramp_connect_errors"): + if d.get(k) is not None: + print("%s=%d" % (k, d[k])) + print("connect_errors=%d" % ((d.get("errors") or {}).get("connect") or 0)) +if d.get("server_cpu_usec") is not None: + print("cpu_usec_window=%d" % d["server_cpu_usec"]) +if d.get("hold_error"): + print("hold_error=%s" % " ".join(str(d["hold_error"]).split())) PY } diff --git a/scripts/validate.sh b/scripts/validate.sh index bcb9fb307c..752ceca2ea 100755 --- a/scripts/validate.sh +++ b/scripts/validate.sh @@ -209,7 +209,7 @@ if has_test "baseline-h2" || has_test "static-h2" || has_test "baseline-h3" || h fi needs_h1tls=false -if has_test "json-tls" || has_test "static-tls" || has_test "8gbit"; then +if has_test "json-tls" || has_test "static-tls" || has_test "8gbit" || has_test "connections-1m-tls"; then needs_h1tls=true fi @@ -1251,7 +1251,7 @@ wait_h2() { # The fixed-rate profiles drive GET /baseline11, so they need the same # handler to be correct and gets its coverage from this section rather than # one of its own -- there is nothing about it a request-shaped check can see. -if has_test "baseline" || has_test "limited-conn" || has_test "latency-1m" || has_test "latency-10k" || has_test "latency-500k-8cpu"; then +if has_test "baseline" || has_test "limited-conn" || has_test "latency-1m" || has_test "latency-10k" || has_test "connections-5m" || has_test "connections-1m-tls" || has_test "connections-1m"; then BASELINE_DOCS="$DOCS_BASE/h1/baseline/validation" echo "[test] baseline endpoints" check "GET /baseline11?a=13&b=42" "55" "$BASELINE_DOCS" \ @@ -1352,6 +1352,33 @@ if has_test "baseline" || has_test "limited-conn" || has_test "latency-1m" || ha fi fi +# ───── Held connections: a listener on every loopback address ───── + +# connections-5m spreads its five million connections over 127.0.0.1- +# 127.0.0.160 (connections-1m its million over .1-.32), because one source +# address holds at most ~64K connections to one destination. A server bound to +# 127.0.0.1 or "localhost" passes every check above and refuses all of these +# but the first, so the profiles ask for a listener on 0.0.0.0 or [::] and this +# is where an entry finds out. Both ends of the widest range. +HELD_DOCS="$DOCS_BASE/h1/connections/validation" +if has_test "connections-5m" || has_test "connections-1m"; then + echo "[test] held connections: listener on every address" + check "GET /baseline11 on 127.0.0.2" "55" "$HELD_DOCS" \ + "http://127.0.0.2:$PORT/baseline11?a=13&b=42" + check "GET /baseline11 on 127.0.0.160" "55" "$HELD_DOCS" \ + "http://127.0.0.160:$PORT/baseline11?a=13&b=42" +fi +# connections-1m-tls: a million over TLS on the h1 TLS port (127.0.0.1-.32), +# where the baseline GET has to answer too, and over TLS 1.3 - the only +# version gcannon offers - or every handshake of the run fails. +if has_test "connections-1m-tls"; then + echo "[test] held connections over TLS: listener on every address, TLS 1.3" + check "GET /baseline11 over TLS 1.3 on 127.0.0.2" "55" "$HELD_DOCS" \ + -k --tlsv1.3 --http1.1 "https://127.0.0.2:$H1TLS_PORT/baseline11?a=13&b=42" + check "GET /baseline11 over TLS 1.3 on 127.0.0.32" "55" "$HELD_DOCS" \ + -k --tlsv1.3 --http1.1 "https://127.0.0.32:$H1TLS_PORT/baseline11?a=13&b=42" +fi + # ───── Pipelined (GET /pipeline) ───── if has_test "pipelined"; then diff --git a/scripts/zrk_fanout.py b/scripts/zrk_fanout.py new file mode 100755 index 0000000000..9a796380b5 --- /dev/null +++ b/scripts/zrk_fanout.py @@ -0,0 +1,661 @@ +#!/usr/bin/env python3 +"""Fan one zrk run out over many loopback addresses and merge the results. + +connections-1m is connections-1m (a million keep-alive connections, 250K +req/s paced across them) with zrk as the load generator instead of gcannon, +so the two generators can be compared on the same load. It needs zrk >= 3.0.2: +2.3.0 kept a 272 KiB latency histogram per connection, ~303 KiB resident in +all, and the first million-connection run with it took the bench host down. +3.0.2 shares one histogram per thread; measured at 4K and 16K connections it +keeps ~41 KiB a connection (buffers and coroutine stacks), ~40 GiB for the +million. + +The kernel tells TCP connections apart by source address and port plus +destination address and port, so one source address can hold at most one +connection per local port to a given destination: about 64K on the bench host +(ip_local_port_range 1024-65535, less the reserved ports). That is the ceiling +the async profile's comment in scripts/lib/profiles.sh runs into. + +Every 127.x.y.z address is local on Linux, so the fleet is spread over +127.0.0.1 .. 127.0.0.K instead: one zrk process per address, each holding +conns/K connections at rate/K, and each destination address brings its own +64K ports. The server has to accept on all of them, which a listener on +0.0.0.0 or [::] does. One bound to 127.0.0.1 alone refuses the rest, and the +probe below says so before anything is launched. + +Measuring the steady state only. zrk opens all of its connections the moment +it starts, so the processes are launched `stagger` seconds apart, and the +`settle` seconds after the last launch are discarded too. What is reported is +the `window` that follows, with the whole fleet connected. Each process streams +one NDJSON row per second (--timeseries) carrying that second's full latency +histogram (--timeseries-histogram). The rows inside the window are merged +exactly, bucket by bucket, and the percentiles are read off the merged +histogram: averaging per-process percentiles would not be a percentile of +anything. + +Output: one JSON object on stdout with the keys of zrk's own --format json +summary that zrk_parse reads (achieved_rate, latency_us, status_codes, errors, +rate_ratio, duration_s, target_rate, max_schedule_lag_us, bytes_per_sec), and: + + connections offered connection count + launched connections the zrk processes report launching + connections_open server-side ESTABLISHED sockets on the port, counted + with ss(8) right after the window + server_cpu_usec the server cgroup's CPU over the window, or null + ramp_connect_errors connect failures outside the window (the ramp) + fanout how the run was split and timed, per process + hold_error set, with every count zero, when the run could not + start (the key scripts/conn_hold.py uses too) + +status_codes 2xx counts the window, like every other figure here. 4xx and 5xx +count the whole run, ramp included: a non-2xx anywhere is worth seeing. + +Usage (scripts/lib/tools/zrk.sh calls it): + + zrk_fanout.py --conns N --rate R --addrs K --port P --path /x --threads T + [--stagger S] [--settle Z] [--window W] [--tail E] + [--cpu-stat FILE] [--ss-cpus LIST] [--min-version 3.0.2] + -- +""" + +from __future__ import annotations + +import argparse +import base64 +import json +import math +import os +import shutil +import socket +import struct +import subprocess +import sys +import tempfile +import time +import zlib + +# ── HdrHistogram V2, as zrk writes it (src/hdr.zig) ───────────────────────── +# +# zrk records microseconds at 3 significant figures between 1us and 60s. The +# functions below mirror its index arithmetic and its reporting conventions +# exactly -- a percentile is the median-equivalent value of the bucket holding +# the rank round(p/100 * total), the mean weights each bucket's median- +# equivalent value, max is the highest-equivalent value of the top bucket -- so +# the merged figures are the ones zrk would print had one process seen +# everything. tests: decoding a summary's own latency_histogram reproduces the +# latency_us block printed next to it. + +_COMPRESSED_BASE = 0x1C849304 +_ENCODING_BASE = 0x1C849303 +_COOKIE_MASK = 0xFFFFFF0F # zrk masks the word-size nibble: ~0xf0 as a u32 + + +class Layout: + def __init__(self, lowest: int, highest: int, sig_figs: int): + self.key = (lowest, highest, sig_figs) + largest_single_unit = 2 * 10 ** sig_figs + sub_bucket_count_magnitude = (largest_single_unit - 1).bit_length() # ceil(log2) + self.half_mag = max(sub_bucket_count_magnitude - 1, 0) + self.unit_mag = lowest.bit_length() - 1 # floor(log2) + sub_bucket_count = 1 << (self.half_mag + 1) + self.half_count = sub_bucket_count // 2 + self.mask = (sub_bucket_count - 1) << self.unit_mag + + def value_from_index(self, i: int) -> int: + bucket = (i >> self.half_mag) - 1 + sub = (i & (self.half_count - 1)) + self.half_count + if bucket < 0: + sub -= self.half_count + bucket = 0 + return sub << (bucket + self.unit_mag) + + def _bucket(self, v: int) -> int: + return (v | self.mask).bit_length() - self.unit_mag - (self.half_mag + 1) + + def _lowest_equiv(self, v: int) -> int: + b = self._bucket(v) + return (v >> (b + self.unit_mag)) << (b + self.unit_mag) + + def _size(self, v: int) -> int: + return 1 << (self._bucket(v) + self.unit_mag) + + def median_equiv(self, v: int) -> int: + return self._lowest_equiv(v) + (self._size(v) >> 1) + + def highest_equiv(self, v: int) -> int: + return self._lowest_equiv(v) + self._size(v) - 1 + + +def _read_zigzag(buf: bytes, pos: int) -> tuple[int, int]: + value = shift = 0 + for i in range(9): + b = buf[pos] + pos += 1 + if i == 8: # the 9th byte carries the top 8 bits whole + value |= b << 56 + break + value |= (b & 0x7F) << shift + if not b & 0x80: + break + shift += 7 + return (value >> 1) ^ -(value & 1), pos + + +def decode_histogram(b64: str) -> tuple[Layout, list[int]]: + raw = base64.b64decode(b64) + cookie, zlen = struct.unpack(">II", raw[:8]) + if cookie & _COOKIE_MASK != _COMPRESSED_BASE: + raise ValueError("not an HdrHistogram V2 compressed histogram") + enc = zlib.decompress(raw[8:8 + zlen]) + cookie, plen, _offset, sig, lowest, highest, _ratio = struct.unpack(">IIIIQQd", enc[:40]) + if cookie & _COOKIE_MASK != _ENCODING_BASE: + raise ValueError("bad HdrHistogram V2 encoding cookie") + payload = enc[40:40 + plen] + counts: list[int] = [] + pos = 0 + while pos < len(payload): + v, pos = _read_zigzag(payload, pos) + if v < 0: + counts.extend([0] * -v) # a run of zeros + else: + counts.append(v) + return Layout(lowest, highest, sig), counts + + +class Merged: + """Counts summed bucket by bucket across any number of decoded histograms.""" + + def __init__(self): + self.layout: Layout | None = None + self.counts: list[int] = [] + + def add(self, b64: str | None) -> None: + if not b64: + return + layout, counts = decode_histogram(b64) + if self.layout is None: + self.layout = layout + elif layout.key != self.layout.key: + raise ValueError(f"histogram layouts differ: {layout.key} vs {self.layout.key}") + if len(counts) > len(self.counts): + self.counts.extend([0] * (len(counts) - len(self.counts))) + for i, c in enumerate(counts): + if c: + self.counts[i] += c + + @property + def total(self) -> int: + return sum(self.counts) + + def percentile(self, p: float) -> int: + total = self.total + if not total or self.layout is None: + return 0 + wanted = int(math.floor((p / 100.0) * total + 0.5)) # Zig @round: half away from zero + wanted = max(wanted, 1) + running = 0 + for i, c in enumerate(self.counts): + running += c + if running >= wanted: + return self.layout.median_equiv(self.layout.value_from_index(i)) + return self.max() + + def mean(self) -> float: + total = self.total + if not total or self.layout is None: + return 0.0 + acc = 0.0 + for i, c in enumerate(self.counts): + if c: + acc += float(self.layout.median_equiv(self.layout.value_from_index(i))) * c + return acc / total + + def max(self) -> int: + if self.layout is None: + return 0 + for i in range(len(self.counts) - 1, -1, -1): + if self.counts[i]: + return self.layout.highest_equiv(self.layout.value_from_index(i)) + return 0 + + def min(self) -> int: + if self.layout is None: + return 0 + for i, c in enumerate(self.counts): + if c: + return self.layout.value_from_index(i) + return 0 + + def latency_block(self) -> dict: + return { + "min": self.min(), "mean": round(self.mean(), 1), "max": self.max(), + "p50": self.percentile(50), "p75": self.percentile(75), + "p90": self.percentile(90), "p99": self.percentile(99), + "p99_9": self.percentile(99.9), "p99_99": self.percentile(99.99), + } + + +# ── Helpers ───────────────────────────────────────────────────────────────── + +def _summary(text: str) -> dict | None: + """zrk's final report, from a stream that may carry other output around it.""" + start, end = text.find("{"), text.rfind("}") + if start < 0 or end <= start: + return None + try: + return json.loads(text[start:end + 1]) + except json.JSONDecodeError: + return None + + +def _rows(path: str) -> list[dict]: + out = [] + try: + with open(path, errors="replace") as f: + for line in f: + line = line.strip() + if line.startswith("{"): + try: + out.append(json.loads(line)) + except json.JSONDecodeError: + pass + except OSError: + pass + return out + + +def _cgroup_mem_kib(cpu_stat: str | None) -> int: + """The server cgroup's memory now, in KiB: memory.current, which sits next + to the cpu.stat the caller passes. 0 when it cannot be read.""" + if not cpu_stat: + return 0 + try: + with open(os.path.join(os.path.dirname(cpu_stat), "memory.current")) as f: + return int(f.read().strip()) // 1024 + except (OSError, ValueError): + return 0 + + +def _cpu_usec(path: str | None) -> int | None: + if not path: + return None + try: + with open(path) as f: + for line in f: + if line.startswith("usage_usec"): + return int(line.split()[1]) + except (OSError, ValueError, IndexError): + pass + return None + + +def _count_established(port: int, cpus: str | None) -> int | None: + """Server-side ESTABLISHED sockets on `port`, counted without buffering 1M lines.""" + if not shutil.which("ss"): + return None + cmd = ["ss", "-H", "-t", "-n", "state", "established", f"( sport = :{port} )"] + if cpus and shutil.which("taskset"): + cmd = ["taskset", "-c", cpus] + cmd + try: + p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) + except OSError: + return None + n = 0 + deadline = time.monotonic() + 30 + assert p.stdout is not None + while True: + chunk = p.stdout.read(1 << 20) + if not chunk: + break + n += chunk.count(b"\n") + if time.monotonic() > deadline: + p.kill() + return None + p.wait() + return n if p.returncode == 0 else None + + +def _probe(addr: str, port: int) -> str | None: + try: + with socket.create_connection((addr, port), timeout=3): + return None + except OSError as e: + return f"{type(e).__name__}: {e}" + + +def _split(total: int, parts: int) -> list[int]: + base, extra = divmod(total, parts) + return [base + (1 if i < extra else 0) for i in range(parts)] + + +def _name_containers(prefix: list[str], k: int, mem_mib: int = 0) -> list[str]: + """Name each zrk container so the harness's cleanup sweeps it (httparena-*), + and cap its memory so a client that outgrows its estimate is OOM-killed in + its own cgroup instead of taking the host down with it.""" + for i in range(len(prefix) - 1): + if os.path.basename(prefix[i]) == "docker" and prefix[i + 1] == "run": + extra = ["--name", f"httparena-zrk-{k}"] + if mem_mib > 0: + extra += [f"--memory={mem_mib}m", f"--memory-swap={mem_mib}m"] + return prefix[:i + 2] + extra + prefix[i + 2:] + return prefix + + +def _version(prefix: list[str]) -> tuple[int, ...] | None: + """What `zrk --version` says ("zrk 3.0.2"), through the same prefix the run + uses, so a docker image is asked rather than whatever is on PATH.""" + try: + out = subprocess.run(prefix + ["--version"], capture_output=True, text=True, + timeout=120).stdout + except (OSError, subprocess.TimeoutExpired): + return None + for tok in out.split(): + parts = tok.lstrip("v").split(".") + if len(parts) == 3 and all(p.isdigit() for p in parts): + return tuple(int(p) for p in parts) + return None + + +def _empty(args, error: str) -> dict: + return { + "hold_error": error, "connections": args.conns, "launched": 0, + "connections_open": None, "requests": 0, "achieved_rate": 0, + "target_rate": args.rate, "rate_ratio": 0, "duration_s": 0, + "bytes_per_sec": 0, "max_schedule_lag_us": 0, "server_cpu_usec": None, + "latency_us": {}, "status_codes": {"1xx": 0, "2xx": 0, "3xx": 0, "4xx": 0, "5xx": 0}, + "errors": {"connect": 0}, "ramp_connect_errors": 0, + } + + +def _mem_available_kib() -> int | None: + try: + with open("/proc/meminfo") as f: + for line in f: + if line.startswith("MemAvailable:"): + return int(line.split()[1]) + except (OSError, ValueError, IndexError): + pass + return None + + +def _size_kib(s: str | None) -> int: + """'96g' / '512m' / '1048576k' / bytes -> KiB; 0 when unset or unparseable.""" + if not s: + return 0 + s = s.strip().lower() + mult = {"k": 1, "m": 1024, "g": 1024 ** 2, "t": 1024 ** 3} + try: + if s[-1] in mult: + return int(float(s[:-1]) * mult[s[-1]]) + return int(s) // 1024 + except ValueError: + return 0 + + +# Kernel memory per connection, both ends of it: two sockets with their file, +# dentry and epoll entries (~3.5 KiB each), plus a conntrack entry. +_KERNEL_KIB_PER_CONN = 8 + + +def _sleep_until(t: float) -> None: + d = t - time.monotonic() + if d > 0: + time.sleep(d) + + +def log(msg: str) -> None: + print(f"[zrk-fanout] {msg}", file=sys.stderr, flush=True) + + +# ── The run ───────────────────────────────────────────────────────────────── + +def run(args, prefix: list[str]) -> dict: + K = args.addrs + if not 1 <= K <= 254: + return _empty(args, f"--addrs must be 1..254, got {K}") + addrs = [f"127.0.0.{k + 1}" for k in range(K)] + + # 2.3.0, the version the other zrk profiles pin, would need ~290 GiB here. + want = tuple(int(p) for p in args.min_version.split(".")) + ver = _version(prefix) + if ver is None or ver < want: + msg = ("connections-1m needs zrk >= %s (per-thread latency histograms); " + "%s %s" % (args.min_version, prefix[-1], + "is " + ".".join(map(str, ver)) if ver else + "did not answer --version (not installed, or an image that did not build)")) + log(msg) + return _empty(args, msg) + + # A listener bound to 127.0.0.1 or "localhost" passes everything else in the + # harness and refuses every address here but the first. Say that, rather + # than launching a million connect errors that read like a broken server. + for probe_addr in (addrs[1], addrs[-1]) if K > 1 else (addrs[0],): + err = _probe(probe_addr, args.port) + if err: + msg = (f"no listener reachable on {probe_addr}:{args.port} ({err}). " + "connections-1m spreads its connections over 127.0.0.1-" + f"{addrs[-1]}, so the server must listen on 0.0.0.0 or [::], " + "not on 127.0.0.1 or localhost alone") + log(msg) + return _empty(args, msg) + + # Refuse what the host cannot hold. The first million-connection run on the + # bench host took it down: zrk 2.3.0 keeps ~303 KiB resident per connection + # (measured flat from 1K to 8K connections), so a million needed ~290 GiB + # of a 251 GiB machine, with nothing capping it. 3.0.2 keeps ~41 KiB. + # Count the client, the kernel's share and everything the server is still + # allowed to grow into. + avail = _mem_available_kib() + server_kib = _size_kib(args.server_mem) + # What the server already holds is out of MemAvailable and inside its cap + # both: count only what it may still grow by. + server_now = _cgroup_mem_kib(args.cpu_stat) + need = (args.conns * (args.kib_per_conn + _KERNEL_KIB_PER_CONN) + + max(server_kib - server_now, 0)) + if avail is not None and need > avail * 0.9: + gib = 1024 ** 2 + msg = (f"not enough memory to hold {args.conns} connections: the load generator " + f"needs ~{args.conns * args.kib_per_conn / gib:.0f} GiB at {args.kib_per_conn} KiB " + f"per connection, the kernel ~{args.conns * _KERNEL_KIB_PER_CONN / gib:.0f} GiB, " + f"and the server, at {server_now / gib:.1f} GiB now, may grow to " + f"{server_kib / gib:.0f} GiB, against {avail / gib:.0f} GiB available. " + "Refusing rather than running the host out of memory") + log(msg) + return _empty(args, msg) + + conns = _split(args.conns, K) + rates = _split(args.rate, K) + threads = max(1, args.threads // K) + # Per-process cap: half again over the estimate, plus a fixed allowance. + mem_cap_mib = int(conns[0] * args.kib_per_conn * 1.5 / 1024) + 512 if args.kib_per_conn else 0 + stagger, settle, window, tail = args.stagger, args.settle, args.window, args.tail + w0 = (K - 1) * stagger + settle # window start, seconds after the first launch + total = w0 + window + tail + log(f"{args.conns} connections at {args.rate} req/s over {K} addresses " + f"({addrs[0]}-{addrs[-1]}): {conns[0]} conns, {rates[0]} req/s, {threads} threads each; " + f"launches {stagger}s apart, window {w0}-{w0 + window}s, run {total}s") + + work = tempfile.mkdtemp(prefix="zrk-fanout-") + procs: list[subprocess.Popen | None] = [None] * K + launch = [0.0] * K + ended = [None] * K + files = [] + if any(os.path.basename(x) == "docker" for x in prefix): + for k in range(K): # a name left over from a crashed run would refuse the start + subprocess.run(["docker", "rm", "-f", f"httparena-zrk-{k}"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + t0 = time.monotonic() + try: + for k in range(K): + _sleep_until(t0 + k * stagger) + cmd = _name_containers(prefix, k, mem_cap_mib) + [ + "-t", str(threads), "-c", str(conns[k]), "-d", f"{total - k * stagger}s", + "-R", str(rates[k]), "--interval", "1s", + "--timeseries", "-", "--timeseries-histogram", "--format", "json", + f"http://{addrs[k]}:{args.port}{args.path}", + ] + ts = open(os.path.join(work, f"ts{k}.ndjson"), "wb") + rep = open(os.path.join(work, f"rep{k}.txt"), "wb") + files += [ts, rep] + launch[k] = time.monotonic() - t0 + try: + procs[k] = subprocess.Popen(cmd, stdout=ts, stderr=rep, stdin=subprocess.DEVNULL) + except OSError as e: + log(f"process {k} ({addrs[k]}) did not start: {e}") + + _sleep_until(t0 + w0) + cpu_a = _cpu_usec(args.cpu_stat) + _sleep_until(t0 + w0 + window) + cpu_b = _cpu_usec(args.cpu_stat) + # Counted after the window rather than inside it: walking a million + # sockets is kernel work the measurement should not carry. + conns_open = _count_established(args.port, args.ss_cpus) + + deadline = t0 + total + 90 + while any(p is not None and ended[k] is None for k, p in enumerate(procs)): + for k, p in enumerate(procs): + if p is not None and ended[k] is None and p.poll() is not None: + ended[k] = time.monotonic() - t0 + if time.monotonic() > deadline: + for k, p in enumerate(procs): + if p is not None and ended[k] is None: + log(f"process {k} ({addrs[k]}) overran; terminating") + p.terminate() + try: + p.wait(10) + except subprocess.TimeoutExpired: + p.kill() + ended[k] = time.monotonic() - t0 + break + time.sleep(0.05) + finally: + for f in files: + f.close() + + # ── Merge ─────────────────────────────────────────────────────────────── + hist = Merged() + window_reqs = window_bytes = 0 + rate_sum = bps_sum = 0.0 + covered = [] + errs = {"connect": 0, "read": 0, "write": 0, "timeout": 0, "deadline": 0, "non_2xx_3xx": 0} + run_connect = run_4xx = run_5xx = launched = 0 + lag = 0 + per = [] + for k in range(K): + rep_text = open(os.path.join(work, f"rep{k}.txt"), errors="replace").read() + summ = _summary(rep_text) + rows = _rows(os.path.join(work, f"ts{k}.ndjson")) + info = {"addr": addrs[k], "connections": conns[k], "rate": rates[k], + "launched": None, "window_requests": 0, "window_s": 0.0} + if summ is None: + log(f"process {k} ({addrs[k]}) left no summary: {rep_text.strip()[:300] or ''}") + else: + info["launched"] = (summ.get("config") or {}).get("launched") + launched += info["launched"] or 0 + run_connect += (summ.get("errors") or {}).get("connect") or 0 + codes = summ.get("status_codes") or {} + run_4xx += codes.get("4xx") or 0 + run_5xx += codes.get("5xx") or 0 + # This process's clock started when zrk did, which is its launch plus + # however long `docker run` took to get there. Its own elapsed time, + # taken back from when it ended, places that start better than the + # launch time alone; the slack either way is well inside settle/tail. + start = launch[k] + if summ and summ.get("duration_s") and ended[k] is not None: + start = max(launch[k], ended[k] - float(summ["duration_s"])) + lo, hi = w0 - start, w0 + window - start + prev = 0.0 + cov = 0.0 + reqs = byts = 0 + for r in rows: + t = float(r.get("t") or 0) + interval = t - prev + prev = t + if t - interval < lo - 0.5 or t > hi + 0.5: + continue + cov += interval + reqs += r.get("requests") or 0 + byts += r.get("bytes") or 0 + for kind, n in (r.get("errors_by_kind") or {}).items(): + if kind in errs: + errs[kind] += n or 0 + lag = max(lag, r.get("max_schedule_lag_us") or 0) + hist.add(r.get("latency_histogram")) + info["window_requests"], info["window_s"] = reqs, round(cov, 3) + window_reqs += reqs + window_bytes += byts + if cov > 0: + rate_sum += reqs / cov + bps_sum += byts / cov + covered.append(cov) + per.append(info) + + shutil.rmtree(work, ignore_errors=True) + + if launched and launched < args.conns: + log(f"only {launched} of {args.conns} connections were launched - " + "zrk could not spawn the rest (vm.max_map_count, memory, or fds)") + if conns_open is not None: + log(f"{conns_open} established on :{args.port} after the window " + f"({100.0 * conns_open / args.conns:.1f}% of {args.conns})") + + return { + "fanout": {"processes": K, "addresses": f"{addrs[0]}-{addrs[-1]}", + "stagger_s": stagger, "settle_s": settle, "window_s": window, + "tail_s": tail, "threads_per_process": threads, "per_process": per}, + "connections": args.conns, + "launched": launched, + "connections_open": conns_open, + "duration_s": round(sum(covered) / len(covered), 3) if covered else 0, + "requests": window_reqs, + "bytes": window_bytes, + "achieved_rate": round(rate_sum, 2), + "target_rate": args.rate, + "rate_ratio": round(rate_sum / args.rate, 4) if args.rate else 0, + "bytes_per_sec": round(bps_sum, 2), + "max_schedule_lag_us": lag, + "server_cpu_usec": (cpu_b - cpu_a) if cpu_a is not None and cpu_b is not None and cpu_b >= cpu_a else None, + "latency_us": hist.latency_block(), + "status_codes": {"1xx": 0, "2xx": max(window_reqs - errs["non_2xx_3xx"], 0), "3xx": 0, + "4xx": run_4xx, "5xx": run_5xx}, + "errors": errs, + "ramp_connect_errors": max(run_connect - errs["connect"], 0), + } + + +def main(argv: list[str]) -> int: + if "--" not in argv: + print("usage: zrk_fanout.py [options] -- ", file=sys.stderr) + return 2 + i = argv.index("--") + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("--conns", type=int, required=True) + ap.add_argument("--rate", type=int, required=True) + ap.add_argument("--addrs", type=int, required=True) + ap.add_argument("--port", type=int, required=True) + ap.add_argument("--path", required=True) + ap.add_argument("--threads", type=int, default=64) + ap.add_argument("--stagger", type=int, default=1) + ap.add_argument("--settle", type=int, default=10) + ap.add_argument("--window", type=int, default=20) + ap.add_argument("--tail", type=int, default=20) + ap.add_argument("--cpu-stat", dest="cpu_stat") + ap.add_argument("--ss-cpus", dest="ss_cpus") + ap.add_argument("--kib-per-conn", dest="kib_per_conn", type=int, default=48, + help="client memory per connection in KiB (zrk 3.0.2: ~41 measured, " + "2.3.0: ~303)") + ap.add_argument("--min-version", dest="min_version", default="3.0.2", + help="the oldest zrk the run accepts") + ap.add_argument("--server-mem", dest="server_mem", + help="the server container's memory cap (e.g. 96g), counted as headroom") + args = ap.parse_args(argv[:i]) + prefix = argv[i + 1:] + if not prefix: + print("zrk_fanout.py: no zrk command after --", file=sys.stderr) + return 2 + print(json.dumps(run(args, prefix), indent=1)) + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/site/content/docs/add-framework/meta-json.md b/site/content/docs/add-framework/meta-json.md index 31274409c2..19460646de 100644 --- a/site/content/docs/add-framework/meta-json.md +++ b/site/content/docs/add-framework/meta-json.md @@ -51,6 +51,9 @@ Create a `meta.json` file in your framework directory: | `async` | HTTP/1.1 | `/delay/{ms}` | | `latency-1m` | HTTP/1.1 | `/baseline11` (fixed 1M req/s) | | `latency-10k` | HTTP/1.1 | `/baseline11` (fixed 10K req/s) | +| `connections-1m` | HTTP/1.1 | `/baseline11` (CON-1M: 1M held connections at a fixed 250K req/s; needs a listener on `0.0.0.0` or `[::]` and an idle timeout of 5 s or more) | +| `connections-1m-tls` | HTTP/1.1 + TLS | `/baseline11` on port 8081 over TLS 1.3 (CON-1M-TLS: 1M held connections at 250K req/s; same requirements) | +| `connections-5m` | HTTP/1.1 | `/baseline11` (CON-5M: 5M held connections at 1.25M req/s; same requirements, and runs only if the entry is on `scripts/connections-5m-allowlist.json`) | | `json-comp` | HTTP/1.1 | `/json/{count}?m=N` (must honor `Accept-Encoding: gzip, br`) | | `json-tls` | HTTP/1.1 + TLS | `/json/{count}?m=N` (port 8081, ALPN `http/1.1`) | | `8gbit` | HTTP/1.1 + TLS | `POST /echo` on port 8081 (10 KB echoed verbatim) | diff --git a/site/content/docs/load-generators/h1/gcannon.md b/site/content/docs/load-generators/h1/gcannon.md index faa7de2034..9f7668098f 100644 --- a/site/content/docs/load-generators/h1/gcannon.md +++ b/site/content/docs/load-generators/h1/gcannon.md @@ -83,6 +83,17 @@ Latency is measured per-request from the moment the send SQE is prepared (not wh For pipelined requests, each request in the batch gets its own send timestamp, and latencies are matched FIFO to response completions. +## Fixed-rate mode (`--rate`, gcannon ≥ 0.8.1) + +Everywhere else gcannon sends the next request the moment the last response arrives. With `--rate N` it holds a fixed total rate instead, which is how [CON-5M and CON-1M-TLS](/docs/test-profiles/h1/connections/implementation/) run, plaintext and over TLS: + +- every connection has its own schedule, one request per (connections / rate) seconds, the first offset by its share of the interval so the fleet sends evenly rather than in waves. Each thread spreads its connections over the whole interval, interleaved with the other threads. 0.8.0 gave each thread one contiguous slice instead, so one thread at a time sent the whole rate, and above what one thread can send its latency figures measured gcannon (p50 ~150 ms at a million connections); 0.8.1 fixes it; +- latency counts from each request's scheduled time (coordinated-omission correction), so a stall is charged to every request scheduled during it, not only to those already on the wire; +- the event loop sleeps exactly until the next send is due, with 1 ns timer slack, so sends leave within tens of microseconds of their slot; at the same paced load it reads the same p50-p99 as [zrk](../zrk/); +- one process holds five million connections in ~16 GiB (~3.3 KiB each), where zrk 2.3.0 needs ~303 KiB per connection and 3.0.2 ~41 KiB ([CON-1M](/docs/test-profiles/h1/connections/implementation/#con-1m-a-million-on-zrk) runs a million on it). Over TLS (`https://`), each connection handshakes TLS 1.3 with OpenSSL and is then handed to kernel TLS, and gcannon frees its own TLS state, so a held TLS connection costs it about what a plaintext one does. + +Three options make a fleet that large possible: `--addr-span 160` spreads it over `127.0.0.1`-`127.0.0.160` (one source address holds ~64.5K connections to one destination), `--connect-limit` caps first connects in flight per thread so five million SYNs never land at once, and `--warmup-max` lets the warmup wait long enough for all of them to open. `--settle` (gcannon ≥ 0.8.2) then keeps the load running before the window opens, so the server has worked off the connect phase by the time measuring starts; CON-5M settles for 30s. On stderr it marks the window's start and end (`gcannon: warmup done ...`, `gcannon: measurement done`), which `scripts/conn_hold.py` uses to read the server's CPU over exactly that window. + ## Command-line reference ``` @@ -99,3 +110,7 @@ Usage: gcannon -c -t -d | `-p` | Pipeline depth | 1 | | `-r` | Requests per connection (0 = unlimited) | 0 | | `--raw` | Comma-separated raw request template files | -- | +| `--rate` | Fixed total request rate (req/s), paced per connection; needs `-p 1`, no `-r` | closed loop | +| `--addr-span` | Spread connections over N consecutive IPv4 addresses from the target's | 1 | +| `--connect-limit` | First connects in flight per thread | all at once | +| `--warmup-max` | Longest the warmup waits for connections to open | 10s | diff --git a/site/content/docs/load-generators/h1/zrk.md b/site/content/docs/load-generators/h1/zrk.md index ed025927ba..5a2fe2a9a0 100644 --- a/site/content/docs/load-generators/h1/zrk.md +++ b/site/content/docs/load-generators/h1/zrk.md @@ -36,6 +36,8 @@ The image pins an exact version and verifies its checksum, unlike gcannon which zrk has no distro package. `benchmark.sh` builds the `zrk:local` image from `docker/zrk.Dockerfile` automatically when a framework subscribes to one of these profiles and no `zrk` binary is on the `PATH`. +`connections-1m` (CON-1M) is the exception: it runs zrk **3.0.2** from its own `zrk:3.0.2` image, the same Dockerfile built with that version and checksum, while the profiles above stay on 2.3.0. A million held connections need 3.0.2's per-thread latency histograms: 2.3.0 keeps ~303 KiB resident per connection, 3.0.2 ~41 KiB. It holds [a million connections](/docs/test-profiles/h1/connections/implementation/#con-1m-a-million-on-zrk) at 250K req/s, the cross-check that caught gcannon 0.8.0's `--rate` bursts; gcannon's own test has since moved to five million. + ## Parameters | Profile | Request | Offered rate | Connections | Duration | @@ -43,5 +45,6 @@ zrk has no distro package. `benchmark.sh` builds the `zrk:local` image from `doc | `latency-1m` | `GET /baseline11?a=1&b=2` | 1,000,000 req/s | 1,024 | 20s | | `latency-10k` | `GET /baseline11?a=1&b=2` | 10,000 req/s | 1,024 | 20s | | `8gbit` | `POST /echo` with a 10 KB body, over TLS on port 8081 | 50,000 req/s | 512 | 5s | +| `connections-1m` | `GET /baseline11?a=1&b=2`, over 127.0.0.1-.32 | 250,000 req/s | 1,000,000 (32 processes) | 20s window | All of them run with 64 threads and 3 runs, keeping the run with the best score. diff --git a/site/content/docs/running-locally/prerequisites.md b/site/content/docs/running-locally/prerequisites.md index 8c030f6f10..5b38b2569e 100644 --- a/site/content/docs/running-locally/prerequisites.md +++ b/site/content/docs/running-locally/prerequisites.md @@ -51,7 +51,7 @@ The one exception is `zrk`, which drives `8gbit`: `benchmark-lite.sh` does not b For the default (native) mode, install each tool the host binary. If anything is missing, set `LOADGEN_DOCKER=true` and the script falls back to the same docker images `benchmark-lite.sh` uses. -- **gcannon** - io_uring HTTP/1.1, WebSocket, and `--raw` multi-template generator. Requires Linux kernel ≥ 6.1 with `io_uring` enabled. +- **gcannon** - io_uring HTTP/1.1, WebSocket, and `--raw` multi-template generator. Requires Linux kernel ≥ 6.1 with `io_uring` enabled. `connections-5m` needs gcannon ≥ 0.8.2 (`--rate`, `--addr-span`), and `connections-1m-tls` ≥ 0.8.4 (`--connect-limit` held through the TLS handshake); `gcannon --version` prints it, and an older build has no `--version` at all. ```bash git clone --branch liburing-2.9 https://github.com/axboe/liburing.git diff --git a/site/content/docs/running-locally/scripts/benchmark.md b/site/content/docs/running-locally/scripts/benchmark.md index 67ffa0aba1..1cbccad8d0 100644 --- a/site/content/docs/running-locally/scripts/benchmark.md +++ b/site/content/docs/running-locally/scripts/benchmark.md @@ -136,6 +136,9 @@ pipeline | req_per_conn | cpu_limit | connections | endpoint | `async` | 1 | ∞ | `0-31,64-95` | 32000 | gcannon | `GET /delay/10`, 10s runs | | `latency-1m` | 1 | ∞ | `0-31,64-95` | 1024 | zrk | `/baseline11` paced at 1M req/s, 20s runs | | `latency-10k` | 1 | ∞ | `0-31,64-95` | 1024 | zrk | `/baseline11` paced at 10K req/s, 20s runs | +| `connections-5m` | 1 | ∞ | `0-31,64-95` | 5000000 | gcannon `--rate` (≥ 0.8.2) | `/baseline11` paced at 1.25M req/s over 5M held connections on 127.0.0.1-.160, 20s window | +| `connections-1m-tls` | 1 | ∞ | `0-31,64-95` | 1000000 | gcannon `--rate` (≥ 0.8.4) | `/baseline11` over TLS 1.3 on `H1TLS_PORT`, paced at 250K req/s over 1M held connections on 127.0.0.1-.32 | +| `connections-1m` | 1 | ∞ | `0-31,64-95` | 1000000 | zrk 3.0.2, one per address | `/baseline11` paced at 250K req/s over 1M held connections on 127.0.0.1-.32 | | `json-comp` | 1 | ∞ | `0-31,64-95` | 4096, 16384 | gcannon | `/json/{count}` + `Accept-Encoding: gzip, br` | | `json-tls` | 1 | ∞ | `0-31,64-95` | 4096 | wrk | `/json/{count}` over TLS on `H1TLS_PORT` | | `8gbit` | 1 | ∞ | `0-31,64-95` | 512 | zrk | `POST /echo` on TLS `:8081` - 10 KB echoed, paced at 50k req/s | diff --git a/site/content/docs/scoring/composite-score.md b/site/content/docs/scoring/composite-score.md index e11ed40e3a..03f114387b 100644 --- a/site/content/docs/scoring/composite-score.md +++ b/site/content/docs/scoring/composite-score.md @@ -78,6 +78,9 @@ The tables below show whether a profile counts for framework entries. Engines an | Async Delay | Yes | `GET /delay/10` over 32,000 held connections - what the framework does while a request waits | | Latency-10K | Yes | Fixed 10K req/s; scored on CPU cost and latency (0-100 score, see above) | | Latency-1M | Yes | Fixed 1M req/s; scored on CPU cost and latency (0-100 score, see above) | +| CON-1M | Yes | One million held connections at a fixed 250K req/s; scored on CPU per request, memory, p50 and p99 ([held-connection score](/docs/test-profiles/h1/connections/implementation/#scoring)) | +| CON-1M-TLS | Yes | The same over TLS 1.3 | +| CON-5M | No (*) | Five million held connections at 1.25M req/s. Reference-only, and run only for the entries on the allowlist | | JSON Compressed | Yes | JSON with `Accept-Encoding: gzip, br` and multiplier `?m=N` | | JSON TLS | Yes | JSON workload over HTTP/1.1 + TLS on port 8081 | | 8Gbit | Yes | 10 KB echoed over TLS at a fixed 50K req/s; scored on CPU cost and latency (0-100 score, see above) | diff --git a/site/content/docs/test-profiles/h1/_index.md b/site/content/docs/test-profiles/h1/_index.md index fb637ed439..c932515b1d 100644 --- a/site/content/docs/test-profiles/h1/_index.md +++ b/site/content/docs/test-profiles/h1/_index.md @@ -16,6 +16,7 @@ Every HTTP/1.1 profile measures one thing at a time, so a number can be attribut {{< card link="async" title="Async Delay" subtitle="A 10ms wait named in the route, at 32K held connections - measures what the framework does while a request waits." icon="clock" >}} {{< card link="latency-10k" title="Latency-10K" subtitle="Latency-1M's setup at a near-idle 10K req/s; the metric is the CPU and latency of a server with almost nothing to do." icon="chip" >}} {{< card link="latency-1m" title="Latency-1M" subtitle="One million req/s offered at a fixed rate; the metric is the CPU each framework spends to serve it, read exactly from its cgroup." icon="chip" >}} + {{< card link="connections" title="Connections (CON-1M, CON-1M-TLS, CON-5M)" subtitle="A million keep-alive connections held at once, a million over TLS 1.3, or five million (by allowlist), with requests paced across them - scored on CPU per request, memory, p50 and p99." icon="globe" >}} {{< card link="async-database" title="Async Database (Postgres)" subtitle="Async Postgres range query over 100K rows, connection pooling, and JSON serialization. Ranked on the Database board, with its own CPU split." icon="database" >}} {{< card link="static-tls" title="Static Files over TLS" subtitle="20 static files served over HTTP/1.1 + TLS on port 8081. Reference-only for frameworks and engines, scored for infrastructure." icon="lock-closed" >}} {{< card link="pipelined" title="Pipelined (16x) *" subtitle="16 requests sent back-to-back per connection, testing raw I/O and pipeline batching. Reference-only - not part of the composite score." icon="fast-forward" >}} diff --git a/site/content/docs/test-profiles/h1/connections/_index.md b/site/content/docs/test-profiles/h1/connections/_index.md new file mode 100644 index 0000000000..3cddd83a10 --- /dev/null +++ b/site/content/docs/test-profiles/h1/connections/_index.md @@ -0,0 +1,18 @@ +--- +title: Connections +seo_title: "Held Connections: CON-1M, CON-1M-TLS and CON-5M" +description: "Holds a million keep-alive connections, a million TLS 1.3 sessions or five million connections open at once, with requests paced across them, and scores what carrying them costs the server: CPU per request, memory, p50 and p99 latency." +--- + +Three profiles hold a fleet of keep-alive connections open at once, every connection sending one request every four seconds. Every other profile keeps a few thousand connections busy; these keep a million, or five million, mostly idle, the way a chat, push or IoT gateway does, so what separates entries is what the waiting costs: the memory each connection keeps, the CPU a request carries while the rest of the fleet sits in the poll set, and how long a request takes when it comes. + +| Profile | On the board | Fleet | Rate | Load generator | Scored | +|---|---|---|---|---|---| +| `connections-1m` | CON-1M | 1,000,000 | 250,000 req/s | zrk 3.0.2, one process per address | Yes | +| `connections-1m-tls` | CON-1M-TLS | 1,000,000 over TLS 1.3 | 250,000 req/s | gcannon ≥ 0.8.4 | Yes | +| `connections-5m` | CON-5M | 5,000,000 | 1,250,000 req/s | gcannon ≥ 0.8.2 | No - and by allowlist only | + +{{< cards >}} + {{< card link="implementation" title="Implementation Guidelines" subtitle="Endpoint, listener requirements, how the load is run, what is measured, and how it is scored." icon="code" >}} + {{< card link="validation" title="Validation" subtitle="All checks executed by the validation script for these test profiles." icon="check-circle" >}} +{{< /cards >}} diff --git a/site/content/docs/test-profiles/h1/connections/implementation.md b/site/content/docs/test-profiles/h1/connections/implementation.md new file mode 100644 index 0000000000..5c2d025ca9 --- /dev/null +++ b/site/content/docs/test-profiles/h1/connections/implementation.md @@ -0,0 +1,115 @@ +--- +title: Implementation Guidelines +seo_title: "Held-Connection Benchmarks (CON-1M, CON-1M-TLS, CON-5M): Implementation Guide" +description: "What to implement, what the listener must allow, how the load is run, what is measured, and how the held-connection profiles CON-1M, CON-1M-TLS and CON-5M are scored." +--- +{{< type-rules standard="Nothing new to implement - the profiles drive `GET /baseline11`, which the baseline profile already specifies and validates. What they ask of you is a server that can hold the whole fleet - a million connections, five million on CON-5M: it must listen on every loopback address (0.0.0.0 or [::], not 127.0.0.1 or localhost), must not cap connections below the fleet, and must not close an idle keep-alive connection in under five seconds. Over TLS it also needs TLS 1.3 on the h1 TLS port, serving the same route. Memory is a quarter of the score, so buffers and TLS state kept per connection count directly against it." tuned="May size buffers, pools and accept loops for the fleet, raise connection caps and idle timeouts, and set the runtime's heap and GC options. All of it is charged: memory is read from the container, which is capped at 128 GiB (96 GiB on the million-connection profiles)." engine="Same as above. An engine with a fixed-size connection table, or one that preallocates a full read buffer per connection, finds out here." >}} + + +A fleet of keep-alive connections is opened against the server and held for the whole run, and `GET /baseline11?a=1&b=2` is paced across it: **one request per connection every four seconds**. At that rate the work per request is a fraction of what a fast server carries on this cpuset, so what is left to measure is what holding the rest of the fleet costs. + +| | CON-1M | CON-1M-TLS | CON-5M | +|---|---|---|---| +| Profile | `connections-1m` | `connections-1m-tls` | `connections-5m` | +| Connections | 1,000,000 | 1,000,000 over TLS 1.3 | 5,000,000 | +| Rate | 250,000 req/s | 250,000 req/s | 1,250,000 req/s | +| Addresses | 127.0.0.1-.32 | 127.0.0.1-.32, port 8081 | 127.0.0.1-.160 | +| Load generator | 32 zrk 3.0.2, [one per address](#con-1m-a-million-on-zrk) | gcannon ≥ 0.8.4, [below](#con-1m-tls-a-million-over-tls) | gcannon ≥ 0.8.2 | +| Scored | yes | yes | no, and [by allowlist only](#con-5m-by-allowlist) | + +**Endpoint:** `GET /baseline11?a=1&b=2` · **CPU:** cpuset `0-31,64-95` · **Window:** 20s, after the fleet is connected + +## What your server must allow + +The request is the baseline one, so there is no code to write. Five things about the listener decide whether an entry can run here at all (the numbers are CON-5M's; CON-1M and CON-1M-TLS hold a fifth of it): + +- **Listen on every address.** A connection is identified by its source and destination address and port, so one client address can hold at most about 64.5K connections to one server address and port. The five million are therefore spread over 160 loopback addresses, `127.0.0.1` to `127.0.0.160`, 31,250 connections each. A listener on `0.0.0.0` or `[::]` accepts on all of them; one bound to `127.0.0.1` or `localhost` refuses 159 of the 160. [Validation](../validation) checks this, and the run refuses to start without it. +- **No connection cap below the fleet.** Some servers ship with a per-worker or global limit: actix's is 25,600 per worker, about 1.64 million across 64 workers, so the actix entry raises it to 100,000. Raise anything lower. +- **An idle timeout of five seconds or more.** Each connection is idle for four seconds between requests, and for up to four seconds between connecting and its first request. Node's, uvicorn's and actix's default keep-alive timeouts are five seconds, which is enough; anything shorter closes the fleet between requests and shows up as reconnects and errors. (At 1M req/s the interval would be five seconds, and those defaults raced every request.) +- **File descriptors.** The container is started with `--ulimit nofile=8388608` (capped at the host's `fs.nr_open`), so five million sockets fit. A server that sets a lower limit of its own, or spends a descriptor per connection on something besides the socket, has to leave room for them. +- **TLS 1.3, for CON-1M-TLS.** The TLS listener on port 8081 (the one JSON TLS uses) must serve `/baseline11` too, listen on every address, and speak TLS 1.3, the only version the load generator offers. + +## How the load is run + +On CON-5M, one [gcannon](/docs/load-generators/h1/gcannon/) process holds the whole fleet: `--rate 1250000` gives each connection its own schedule, one request every four seconds, with every client thread's connections spread over the whole interval so the five million do not fire in waves, and latency counted from each request's scheduled time. `--addr-span 160` spreads the connections over `127.0.0.1`-`127.0.0.160`, 31,250 on each, and `--connect-limit 64` keeps at most 64 first connects in flight per thread, so they never arrive as one burst of SYNs. + +gcannon's warmup waits until every connection has opened (up to 300s), then keeps the load running 30 seconds more (`--settle 30s`) so the server can work off the connect phase, and **what is reported is the 20 seconds after that**. [`scripts/conn_hold.py`](https://github.com/MDA2AV/HttpArena/blob/main/scripts/conn_hold.py) reads the server's cgroup CPU when gcannon marks the window's start and end, so neither the five million connects (or handshakes) nor the five million closes are in the CPU figure. It also probes the listener, refuses a run the host cannot hold in memory, and raises the open-file limit gcannon needs for five million sockets. + +Every run gets a fresh server, and connects only once the last run's connections are gone. After the window, the harness waits, with the server still up so it closes its own side, until the host's TCP socket count (`alloc` in `/proc/net/sockstat`) is back to within 50,000 of what it was before the first profile; then it stops the server and starts the next. gcannon 0.8.3 and later close their connections themselves before exiting, in seconds. Earlier versions leave them for the kernel to close one at a time after exit, which on the bench host took longer than the minute the harness used to sleep, so runs 2 and 3 connected and measured on a host still closing the last fleet. + +The load generator is gcannon rather than [zrk](/docs/load-generators/h1/zrk/), the other paced generator here, because of memory: zrk 2.3.0 keeps ~303 KiB resident per connection and even 3.0.2 ~41 KiB, ~200 GiB for five million. gcannon holds a connection in ~3.3 KiB. + +## CON-1M-TLS: a million over TLS + +`connections-1m-tls` is the gcannon run over TLS 1.3 at a million connections: 250,000 req/s, still one request per connection every four seconds, over `127.0.0.1`-`127.0.0.32` (31,250 on each), against the TLS listener on port 8081. Every connection handshakes once, then carries its requests encrypted, so what it adds is the TLS session the server keeps for each connection. + +- **A million, for now.** Five million over TLS was still connecting 7.7 minutes into its first run. +- **Handshakes are paced to the server.** gcannon ≥ 0.8.4 counts a connection against `--connect-limit` until its handshake is done, so at most 64 per client thread wait at the server, and a new connection starts only when one of them finishes ([MDA2AV/gcannon#33](https://github.com/MDA2AV/gcannon/pull/33)). Earlier versions released the slot at the TCP connect, which the kernel completes on its own, and the handshakes piled up past the server's handshake timeout (10 s on ioxide and Kestrel, 3 s on actix), which closed them mid-handshake. The run refuses an older gcannon. +- **gcannon's side.** It handshakes each connection with OpenSSL (TLS 1.3, no certificate verification: the bench certificate is self-signed), then hands the session to kernel TLS and frees its own TLS state. A TLS connection costs the client what a plaintext one does plus the kernel's record state, so what the profile adds to the server's figures is its own TLS sessions. +- **Limits.** The warmup waits up to 900s for the handshakes, and the server gets the million-connection caps: `nofile` 2,097,152 and 96 GiB. + +## CON-1M: a million on zrk + +`connections-1m` holds one million connections at 250,000 req/s with zrk 3.0.2 as the load generator, on the same cpusets, 64 client threads and 20s window. Run next to gcannon at the same scale, it is also how gcannon 0.8.0's `--rate` was caught sending each thread's connections in one burst ([MDA2AV/gcannon#30](https://github.com/MDA2AV/gcannon/pull/30)). + +- **zrk 3.0.2, not the pinned 2.3.0.** 3.0.2 shares one latency histogram per thread instead of keeping one per connection, which takes a connection from ~303 KiB to ~41 KiB (measured flat at 4K and 16K connections), ~40 GiB for the million. The other zrk profiles stay on 2.3.0; this one builds its own `zrk:3.0.2` image from the same Dockerfile, and refuses an older zrk. +- **One process per address.** zrk takes one URL, so [`scripts/zrk_fanout.py`](https://github.com/MDA2AV/HttpArena/blob/main/scripts/zrk_fanout.py) runs 32 of them, one per address from `127.0.0.1` to `127.0.0.32`, each holding 31,250 connections at 7,812 req/s on 2 threads. +- **Staggered starts instead of a connect limit.** Each zrk opens all of its connections the moment it starts, so the 32 start one second apart, the 10s after the last start are discarded, and the 20s that follow are measured. +- **Merged histograms.** Each process writes its full latency histogram every second; the rows inside the window are summed bucket by bucket and the percentiles read off the sum, never averaged across processes. +- **Held** is counted from the server's side: its established sockets on :8080, read with `ss` after the window. + +## CON-5M: by allowlist + +Holding five million connections, a server may grow to its 128 GiB cap, so CON-5M is not open to every entry: it runs only for the frameworks listed in [`scripts/connections-5m-allowlist.json`](https://github.com/MDA2AV/HttpArena/blob/main/scripts/connections-5m-allowlist.json). Subscribing to `connections-5m` in `meta.json` is not enough on its own: an entry that subscribes but is not on the list is skipped, and the run says why. To be added, ask in your pull request. + +## What is measured + +| field | meaning | +|---|---| +| `connections_open` | connections still open when the window closed, counted by gcannon ("Held" on the board); on `connections-1m`, the server's established sockets after the window | +| `memory` | the container's peak memory across the run, the whole fleet included - a quarter of the score. Divided by the fleet it is the cost of a connection, to within the server's baseline | +| `cpu_usec` | server CPU microseconds over the window only, read from cgroup v2 `cpu.stat`, so the connects and handshakes are not in it | +| `cpu_per_req_us` | the same divided by requests served in the window | +| `p50_latency`, `p99_latency` | the median and the 99th percentile, coordinated-omission-corrected, over the window: both are in the score | +| `avg_latency`, `p99_9_latency` | coordinated-omission-corrected, over the window, shown but not scored | +| `rate_ratio` | achieved over offered in the window. A connection that never opened sends nothing, so a fleet only partly held lands here too | +| `window_connect_errors` | connect failures inside the window: connections the server dropped and refused again | + +## Parameters + +| Parameter | Value | +|-----------|-------| +| Endpoint | `GET /baseline11?a=1&b=2` (GET only, no body); over TLS 1.3 on port 8081 for `connections-1m-tls` | +| Connections | 1,000,000 over 127.0.0.1-127.0.0.32 (CON-1M, CON-1M-TLS); 5,000,000 over 127.0.0.1-127.0.0.160 (CON-5M); 31,250 per address | +| Offered rate | 250,000 req/s (CON-1M, CON-1M-TLS), 1,250,000 req/s (CON-5M), paced: one request per connection every 4s | +| CPU | cpuset `0-31,64-95` (32 cores, both threads) | +| Memory cap | 128 GiB (`CONN5M_MEM_LIMIT`), 96 GiB on the million-connection profiles (`CONN1M_MEM_LIMIT`); a server above it is OOM-killed | +| Ramp | at most 64 first connects in flight per thread (over TLS, until the handshake is done); the warmup waits up to 300s (900s on `connections-1m-tls`) for all of them | +| Settle | 30s at the full rate after the fleet is up, before the window (`--settle`) | +| Window | 20s | +| Runs | 3, and the highest-scoring one is kept | +| Load generator | [gcannon](/docs/load-generators/h1/gcannon/) ≥ 0.8.2 with `--rate` and `--settle` (≥ 0.8.4 on `connections-1m-tls`), under `scripts/conn_hold.py`; on `connections-1m`, 32 [zrk](/docs/load-generators/h1/zrk/) 3.0.2 processes under `scripts/zrk_fanout.py` | +| Host limits | `fs.nr_open`, `vm.max_map_count` (zrk maps ~4 regions per connection) and the conntrack table are raised for these profiles only (`system_tune_held_connections`) | + +## Scoring + +What holding the fleet costs, against the best in the field, times the share of the rate delivered: + +``` +rateFactor = min(1, achieved_rps / full_rate) +quality = 0.25 x cpuScore + 0.25 x memScore + 0.25 x p50Score + 0.25 x p99Score +score = 100 x rateFactor x quality +``` + +| term | measured as | scale | +|---|---|---| +| cpuScore | CPU microseconds per request, over the window | best / yours | +| memScore | the server's peak memory with the fleet held | best / yours | +| p50Score | median latency | 1 - log10(yours / best) / 3: ten times the best costs a third of the term | +| p99Score | 99th-percentile latency | the same three-decade scale | + +Memory and CPU spread over a few times across the field, so they are plain ratios; latency spans orders of magnitude, where a ratio would leave everyone but the leader near zero, so both percentiles get the three-decade scale [Latency-1M](../latency-1m/implementation/#scoring) uses for its p99. The rate earns full credit at 95% of what is offered: 237,500 req/s on CON-1M and CON-1M-TLS, 1,187,500 on CON-5M. A connection that never opened sends nothing, so a fleet only partly held falls short in the rate factor as well as in Held. Computed by [`scripts/latency_score.py`](https://github.com/MDA2AV/HttpArena/blob/main/scripts/latency_score.py); the board computes the same. + +**CON-1M and CON-1M-TLS are scored.** Each is worth up to 1,000 in the HTTP/1.1 composite, normalised against the field's leader like the other fixed-rate profiles, for frameworks and engines (not infrastructure). **CON-5M is reference-only:** measured and shown, part of no composite. + +Subscribe by adding `connections-1m` and `connections-1m-tls` to `tests` in your `meta.json`. `connections-5m` also needs the entry on the [allowlist](#con-5m-by-allowlist). diff --git a/site/content/docs/test-profiles/h1/connections/validation.md b/site/content/docs/test-profiles/h1/connections/validation.md new file mode 100644 index 0000000000..3e4bc758c4 --- /dev/null +++ b/site/content/docs/test-profiles/h1/connections/validation.md @@ -0,0 +1,33 @@ +--- +title: Validation +seo_title: "Held-Connection Benchmarks (CON-1M, CON-1M-TLS, CON-5M): Validation Checks" +description: "How correctness is established for the held-connection profiles CON-1M, CON-1M-TLS and CON-5M, and the listener checks that are specific to them." +--- + +The profiles drive `GET /baseline11?a=1&b=2`, the baseline endpoint unchanged, so an entry subscribed to `connections-5m`, `connections-1m-tls` or `connections-1m` is run through the full [baseline validation suite](../baseline/validation): the arithmetic, the `Content-Type`, the randomized-input anti-cheat, the TCP fragmentation checks, and the exhaustive per-byte fragmentation sweep. + +## A listener on every address + +One check is specific to these profiles. CON-5M spreads its five million connections over `127.0.0.1` to `127.0.0.160`, CON-1M its million over `127.0.0.1` to `127.0.0.32`, because one client address can hold only about 64.5K connections to one server address and port. A server bound to `127.0.0.1` or `localhost` passes every baseline check and refuses all but one of those addresses, so validation sends the baseline request to both ends of the range: + +| check | request | expected | +|---|---|---| +| GET /baseline11 on 127.0.0.2 | `GET http://127.0.0.2:8080/baseline11?a=13&b=42` | `55` | +| GET /baseline11 on 127.0.0.160 | `GET http://127.0.0.160:8080/baseline11?a=13&b=42` | `55` | + +To pass, listen on `0.0.0.0` or `[::]` (an IPv6 wildcard listener accepts IPv4 connections too, unless it sets `IPV6_V6ONLY`). The benchmark repeats the probe before it launches anything, and a server that fails it gets an empty row with the reason rather than millions of connect errors. + +## Over TLS + +CON-1M-TLS (`connections-1m-tls`) spreads its million over `127.0.0.1` to `127.0.0.32` on the h1 TLS port, so both ends of that range are asked there, over TLS 1.3: the load generator offers no other version, and a server without it would fail every handshake of the run. + +| check | request | expected | +|---|---|---| +| GET /baseline11 over TLS 1.3 on 127.0.0.2 | `GET https://127.0.0.2:8081/baseline11?a=13&b=42` (TLS 1.3, HTTP/1.1) | `55` | +| GET /baseline11 over TLS 1.3 on 127.0.0.32 | `GET https://127.0.0.32:8081/baseline11?a=13&b=42` (TLS 1.3, HTTP/1.1) | `55` | + +## What the run checks + +- **Held, not just offered.** gcannon counts the connections still open at the end of the window; on CON-1M (`connections-1m`) the harness counts the server's established sockets on :8080 from the kernel's socket table after it. Either way a server that dropped connections, or never accepted them, shows its real count in the Held column. +- **`rate_ratio`.** Achieved over offered in the window, published with the row. A connection that never opened sends nothing, so a fleet only partly held falls short here as well as in Held, and the score falls proportionally. +- **CPU from outside.** As on the other fixed-rate profiles, CPU is read by the harness from the container's cgroup rather than reported from inside it, over the window only. diff --git a/site/leaderboard/index.html b/site/leaderboard/index.html index 1ee0ab24f4..175b002998 100644 --- a/site/leaderboard/index.html +++ b/site/leaderboard/index.html @@ -1929,7 +1929,7 @@

setupTopScroll(); setupFloatHead(); } - function val(r,k){ if(k==='rps')return r.rps||0; if(k==='bw')return bw(r.bandwidth); if(k==='bwreq'){var b=bw(r.bandwidth),q=r.rps||0;return q>0?b/q:0;} if(k==='inbw')return bw(r.input_bw); if(k==='avg')return lat(r.avg_latency); if(k==='p99')return lat(r.p99_latency); if(k==='l1mscore')return latScore(state.profile,r.fw); if(k==='p999')return lat(r.p99_9_latency); if(k==='cpureq')return (r.cpu_per_req_us!=null)?+r.cpu_per_req_us:Infinity; if(k==='cputot'){var t=cpuTotPct(r); return t==null?Infinity:t;} if(k==='cpu')return cpu(r.cpu); if(k==='mem')return mem(r.memory); if(k==='fw')return (r.fw||'').toLowerCase(); return 0; } + function val(r,k){ if(k==='rps')return r.rps||0; if(k==='held')return r.connections_open!=null?+r.connections_open:0; if(k==='bw')return bw(r.bandwidth); if(k==='bwreq'){var b=bw(r.bandwidth),q=r.rps||0;return q>0?b/q:0;} if(k==='inbw')return bw(r.input_bw); if(k==='avg')return lat(r.avg_latency); if(k==='p99')return lat(r.p99_latency); if(k==='p50')return lat(r.p50_latency); if(k==='l1mscore')return latScore(state.profile,r.fw); if(k==='p999')return lat(r.p99_9_latency); if(k==='cpureq')return (r.cpu_per_req_us!=null)?+r.cpu_per_req_us:Infinity; if(k==='cputot'){var t=cpuTotPct(r); return t==null?Infinity:t;} if(k==='cpu')return cpu(r.cpu); if(k==='mem')return mem(r.memory); if(k==='fw')return (r.fw||'').toLowerCase(); return 0; } function fmtBytes(n){ if(n>=1048576)return (n/1048576).toFixed(2)+' MB'; if(n>=1024)return (n/1024).toFixed(1)+' KB'; return Math.round(n)+' B'; } // Explorer columns - profile-specific (json-comp adds BW/req, upload adds In BW); // low-priority columns drop out below width breakpoints so the grid never overflows. @@ -1941,11 +1941,11 @@

// Offered rate that earns the whole rate factor, per profile. 95% of target: // the generator never quite reaches its own number, so the threshold has to // sit below it. Mirrors FULL_RATE in scripts/latency_score.py. - var LAT_FULL={'latency-1m':950000, 'latency-10k':9500, '8gbit':47500}; + var LAT_FULL={'latency-1m':950000, 'latency-10k':9500, '8gbit':47500, 'connections-5m':1187500, 'connections-1m-tls':237500, 'connections-1m':237500}; // Logical CPUs each fixed-rate profile is pinned to, per scripts/lib/profiles.sh: // cpuset 0-31,64-95 is 32 cores with both threads, so 64. Used to turn CPU-per-request // into "how much of the machine it was allowed did this take". - var LAT_CPUS={'latency-1m':64, 'latency-10k':64, '8gbit':64}; + var LAT_CPUS={'latency-1m':64, 'latency-10k':64, '8gbit':64, 'connections-5m':64, 'connections-1m-tls':64, 'connections-1m':64}; // CPU microseconds per second / 1e6 = cores in use; over the allowance = 0-100%. function cpuTotPct(r,pid){ if(r==null||r.cpu_per_req_us==null) return null; @@ -1953,6 +1953,11 @@

return (+r.cpu_per_req_us)*q/1e6/(LAT_CPUS[pid]||64)*100; } var LAT_W_CPU=0.50, LAT_W_P99=0.25, LAT_W_MEAN=0.25, LAT_DEC=3, LAT_MEAN_DEC=1; + // The held-connection profiles (CON-1M, CON-1M-TLS, CON-5M) score what holding the + // fleet costs, on four equal terms: CPU per request and peak memory as plain + // ratios, p50 and p99 on the three-decade scale. Mirrors HELD in scripts/latency_score.py. + var LAT_HELD={'connections-1m':1, 'connections-1m-tls':1, 'connections-5m':1}; + var HELD_W_CPU=0.25, HELD_W_MEM=0.25, HELD_W_P50=0.25, HELD_W_P99=0.25; var _latScores={}; function isLatProfile(pid){ return Object.prototype.hasOwnProperty.call(LAT_FULL,pid); } function clamp01(v){ return v<0?0:v>1?1:v; } @@ -1975,6 +1980,24 @@

} function latBuild(pid, rows){ var out={}; _latScores[pid]=out; + if(LAT_HELD[pid]){ + var hc=Infinity,hm=Infinity,h5=Infinity,h9=Infinity, hfull=LAT_FULL[pid]||1; + rows.forEach(function(r){ + var c=+r.cpu_per_req_us, m=mem(r.memory), p5=lat(r.p50_latency), p9=lat(r.p99_latency); + if(c>0) hc=Math.min(hc,c); + if(m>0) hm=Math.min(hm,m); + if(p5>0&&isFinite(p5)) h5=Math.min(h5,p5); + if(p9>0&&isFinite(p9)) h9=Math.min(h9,p9); + }); + rows.forEach(function(r){ + var rf=clamp01((r.rps||0)/hfull); + out[r.fw]=100*rf*(HELD_W_CPU*latLinear(+r.cpu_per_req_us,hc) + +HELD_W_MEM*latLinear(mem(r.memory),hm) + +HELD_W_P50*latDecade(lat(r.p50_latency),h5,LAT_DEC) + +HELD_W_P99*latDecade(lat(r.p99_latency),h9,LAT_DEC)); + }); + return; + } var bc=Infinity,bp=Infinity,bm=Infinity, full=LAT_FULL[pid]||1; rows.forEach(function(r){ var c=+r.cpu_per_req_us, p=lat(r.p99_latency), m=lat(r.avg_latency); @@ -2014,6 +2037,18 @@

// exact one. Avg latency stays: it replaced p99.9 in the score and is the // queueing signal this view has to show. Dropping the other two buys the // name back ~200px and loses no information. + if(LAT_HELD[state.profile]){ + c.push({k:'l1mscore', label:'Score', num:true, w:'92px', min:0, tip:'0-100. rateFactor \u00d7 (0.25\u00d7CPU per request + 0.25\u00d7memory + 0.25\u00d7p50 + 0.25\u00d7p99), each measured against the best in the field. rateFactor is 1 at 95% of the offered rate and falls proportionally below it. Higher is better.'}); + c.push({k:'rps', label:'Requests / sec', num:true, w:'minmax(150px,1fr)', min:0, tip:TIP.rps}); + // How much of the fleet was actually held: the rate cannot say it alone, since a connection that never opened sends nothing. + c.push({k:'held', label:'Held', num:true, w:'104px', min:0, tip:'Connections still open at the end of the measured window: 1,000,000 is the whole fleet on CON-1M and CON-1M-TLS, 5,000,000 on CON-5M.'}); + c.push({k:'cpureq', label:'CPU / req', num:true, w:'110px', min:0, tip:'CPU microseconds the server spent per request, read exactly out of its cgroup rather than sampled. A quarter of the score - lower is better.'}); + c.push({k:'mem', label:'Mem', num:true, w:'92px', min:0, tip:'The server container\u2019s peak memory while it held the fleet. A quarter of the score - lower is better.'}); + c.push({k:'p50', label:'p50', num:true, w:'92px', min:0, tip:'Median latency, coordinated-omission corrected. A quarter of the score, on a three-decade scale against the best.'}); + c.push({k:'p99', label:'p99', num:true, w:'92px', min:0, tip:'99th-percentile latency, coordinated-omission corrected. A quarter of the score, on a three-decade scale against the best.'}); + c.push({k:'cputot', label:'CPU used', num:true, w:'100px', min:640, tip:'The same CPU cost read as a share of the 64 logical CPUs the profile pins: CPU-per-request \u00d7 the rate delivered. 100% would mean the entry saturated everything it was given.'}); + return c.filter(function(x){ return W>=x.min; }); + } if(isLatProfile(state.profile)){ c.push({k:'l1mscore', label:'Score', num:true, w:'92px', min:0, tip:'0-100. rateFactor \u00d7 (0.50\u00d7CPU + 0.25\u00d7p99 + 0.25\u00d7mean), each measured against the best in the field. rateFactor is 1 at 95% of the offered rate and falls proportionally below it. Higher is better.'}); c.push({k:'rps', label:'Requests / sec', num:true, w:'minmax(150px,1fr)', min:0, tip:TIP.rps}); @@ -2045,8 +2080,10 @@

if(k==='p999') return '
'+esc(r.p99_9_latency||'-')+'
'; if(k==='cpureq') return '
'+(r.cpu_per_req_us!=null?esc((+r.cpu_per_req_us).toFixed(2))+' \u00b5s':'-')+'
'; if(k==='cputot'){ var t=cpuTotPct(r,state.profile); return '
'+(t==null?'-':esc(t.toFixed(1))+'%')+'
'; } + if(k==='held') return '
'+(r.connections_open!=null?fmt(+r.connections_open):'-')+'
'; if(k==='avg') return '
'+esc(r.avg_latency||'-')+'
'; if(k==='p99') return '
'+esc(r.p99_latency||'-')+'
'; + if(k==='p50') return '
'+esc(r.p50_latency||'-')+'
'; if(k==='cpu') return '
'+esc(r.cpu||'-')+'
'; if(k==='mem') return '
'+esc(r.memory||'-')+'
'; return '
'; @@ -2228,6 +2265,7 @@

if(k==='cputot'){ var t=cpuTotPct(r,state.profile); return t==null?'-':t.toFixed(1)+'%'; } if(k==='avg') return r.avg_latency||'-'; if(k==='p99') return r.p99_latency||'-'; + if(k==='p50') return r.p50_latency||'-'; if(k==='cpu') return r.cpu||'-'; if(k==='mem') return r.memory||'-'; return '';