diff --git a/.github/workflows/benchmark-e2e.yml b/.github/workflows/benchmark-e2e.yml new file mode 100644 index 0000000..89ea145 --- /dev/null +++ b/.github/workflows/benchmark-e2e.yml @@ -0,0 +1,81 @@ +name: Pinned proxy benchmark +on: + push: + branches: [bench/http2-e2e] + paths: [benchmarks/e2e/**, .github/workflows/benchmark-e2e.yml] + workflow_dispatch: +permissions: + contents: read +concurrency: + group: pinned-proxy-benchmark + cancel-in-progress: true +jobs: + benchmark: + runs-on: ubuntu-24.04 + timeout-minutes: 25 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: actions/checkout@v4 + with: + repository: Ray0907/tinyproxy-rust + ref: d500d2510475daafa8269e09caea6d2043c26aa5 + path: tested-source + persist-credentials: false + - uses: dtolnay/rust-toolchain@stable + with: + components: clippy,rustfmt + - uses: actions/setup-go@v5 + with: + go-version: stable + cache: false + - name: Build pinned implementations and independent Go driver + shell: bash + run: | + set -euo pipefail + mkdir -p benchmark-results + (cd tested-source && cargo build --release --locked) >benchmark-results/rust-build.log 2>&1 || { tail -80 benchmark-results/rust-build.log; exit 1; } + cp tested-source/target/release/tinyproxy-rust ./rust-baseline + curl --fail --location --retry 3 https://github.com/tinyproxy/tinyproxy/releases/download/1.11.3/tinyproxy-1.11.3.tar.gz -o /tmp/tinyproxy.tar.gz + echo '9bcf46db1a2375ff3e3d27a41982f1efec4706cce8899ff9f33323a8218f7592 /tmp/tinyproxy.tar.gz' | sha256sum -c - + mkdir -p c-source + tar xzf /tmp/tinyproxy.tar.gz -C c-source --strip-components=1 + (cd c-source && ./configure --disable-manpage-support CFLAGS='-O3 -DNDEBUG' && make -j2) >benchmark-results/c-build.log 2>&1 || { tail -80 benchmark-results/c-build.log; exit 1; } + (cd benchmarks/e2e && go mod tidy && gofmt -w main.go && go build -trimpath -o ../../bench-driver .) >benchmark-results/go-build.log 2>&1 || { cat benchmark-results/go-build.log; exit 1; } + cp benchmarks/e2e/go.mod benchmarks/e2e/go.sum benchmark-results/ + cp tested-source/Cargo.lock benchmark-results/ + git rev-parse HEAD > benchmark-results/harness-commit.txt + git -C tested-source rev-parse HEAD > benchmark-results/tested-commit.txt + sha256sum rust-baseline c-source/src/tinyproxy bench-driver > benchmark-results/binary-sha256.txt + - name: Re-run unchanged baseline regressions and real curl interoperability + shell: bash + run: | + set -euo pipefail + (cd tested-source && cargo test --all-targets --locked) >benchmark-results/tests.log 2>&1 || { tail -100 benchmark-results/tests.log; exit 1; } + grep -E '^running [0-9]+ tests|^test result:' benchmark-results/tests.log + python3 tested-source/scripts/test_curl_proxy.py --binary ./rust-baseline --curl /usr/bin/curl | tee benchmark-results/curl.log + - name: Build and validate separately labeled TCP_NODELAY experiment + shell: bash + run: | + set -euo pipefail + python3 benchmarks/e2e/nodelay_experiment.py tested-source + (cd tested-source && cargo fmt --all && cargo test --all-targets --locked && cargo clippy --all-targets --locked -- -D warnings && cargo build --release --locked) >benchmark-results/nodelay-build-test.log 2>&1 || { tail -100 benchmark-results/nodelay-build-test.log; exit 1; } + cp tested-source/target/release/tinyproxy-rust ./rust-nodelay + git -C tested-source diff -- src/connection.rs src/transport.rs > benchmark-results/nodelay.patch + sha256sum rust-nodelay >> benchmark-results/binary-sha256.txt + grep -E '^running [0-9]+ tests|^test result:|Finished' benchmark-results/nodelay-build-test.log + python3 tested-source/scripts/test_curl_proxy.py --binary ./rust-nodelay --curl /usr/bin/curl | tee benchmark-results/nodelay-curl.log + - name: Run interleaved baselines and experimental cases, then held tunnels + shell: bash + run: | + set -euo pipefail + ulimit -n 32768 + python3 benchmarks/e2e/run.py --rust ./rust-baseline --rust-nodelay ./rust-nodelay --c-proxy c-source/src/tinyproxy --driver ./bench-driver --output benchmark-results --rounds 3 --seconds 4 | tee benchmark-results/run.log + - name: Retain results even when a case fails + if: always() + uses: actions/upload-artifact@v4 + with: + name: pinned-proxy-benchmark-${{ github.run_id }} + path: benchmark-results/ + retention-days: 30 diff --git a/benchmarks/e2e/go.mod b/benchmarks/e2e/go.mod new file mode 100644 index 0000000..cc2cbb7 --- /dev/null +++ b/benchmarks/e2e/go.mod @@ -0,0 +1,5 @@ +module tinyproxy-benchmark + +go 1.23.0 + +require golang.org/x/net v0.43.0 diff --git a/benchmarks/e2e/main.go b/benchmarks/e2e/main.go new file mode 100644 index 0000000..50825c9 --- /dev/null +++ b/benchmarks/e2e/main.go @@ -0,0 +1,234 @@ +// End-to-end loopback load generator. It is test tooling, not proxy runtime code. +package main + +import ( + "bufio" + "bytes" + "context" + "crypto/tls" + "crypto/x509" + "encoding/json" + "flag" + "fmt" + "io" + "net" + "net/http" + "net/url" + "os" + "sort" + "strconv" + "sync" + "sync/atomic" + "time" + + "golang.org/x/net/http2" +) + +var ( + mode = flag.String("mode", "load", "origin or load") + kind = flag.String("kind", "http", "http, tunnel, or idle") + protocol = flag.String("protocol", "h1", "h1, h1tls, h2c, h2tls") + proxy = flag.String("proxy", "", "proxy host:port; empty means direct") + target = flag.String("target", "127.0.0.1:18080", "origin or echo host:port") + ca = flag.String("ca", "", "trusted test CA PEM") + concurrency = flag.Int("c", 32, "parallel workers / held tunnels") + connections = flag.Int("connections", 1, "exact HTTP/2 connections") + size = flag.Int("size", 1024, "response / echo bytes") + method = flag.String("method", "GET", "HTTP method") + fresh = flag.Bool("fresh", false, "disable HTTP/1 connection reuse") + duration = flag.Duration("duration", 5*time.Second, "measurement admission window") + warmup = flag.Duration("warmup", time.Second, "unmeasured warmup") + hold = flag.Duration("hold", 6*time.Second, "idle tunnel hold time") +) + +func emit(v any) { if err := json.NewEncoder(os.Stdout).Encode(v); err != nil { panic(err) } } +func fail(err error) { fmt.Fprintln(os.Stderr, err); os.Exit(1) } +func main() { + flag.Parse() + if *mode == "origin" { if err := serveOrigin(); err != nil { fail(err) }; return } + if *concurrency < 1 || *concurrency > 2048 || *size < 1 || *size > 8<<20 || *connections < 1 { fail(fmt.Errorf("invalid bounds")) } + if err := run(); err != nil { fail(err) } +} + +func serveOrigin() error { + echo, err := net.Listen("tcp", "127.0.0.1:18081"); if err != nil { return err } + go func() { for { c, e := echo.Accept(); if e != nil { return }; go func() { defer c.Close(); _, _ = io.Copy(c, c) }() } }() + payload := bytes.Repeat([]byte("x"), 8<<20) + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + n, e := strconv.Atoi(r.URL.Query().Get("size")); if e != nil || n < 1 || n > len(payload) { http.Error(w,"size",400); return } + if r.Header.Get("Proxy-Authorization") != "" { http.Error(w,"credential leak",500); return } + if r.Method == "POST" { + b, e := io.ReadAll(io.LimitReader(r.Body, int64(n)+1)); _ = r.Body.Close() + if e != nil || !bytes.Equal(b, payload[:n]) { http.Error(w,"bad upload",400); return } + } + w.Header().Set("Content-Type", "application/octet-stream") + w.Header().Set("Content-Length", strconv.Itoa(n)) + _, _ = w.Write(payload[:n]) + }) + server := &http.Server{Addr:"127.0.0.1:18080", Handler:handler, ReadHeaderTimeout:5*time.Second, IdleTimeout:30*time.Second} + emit(map[string]any{"ready":true, "http":server.Addr, "echo":"127.0.0.1:18081"}) + return server.ListenAndServe() +} + +type clients struct { + h1 *http.Transport + h2 []*http2.ClientConn + tlsConfig *tls.Config + dials atomic.Int64 +} +func newClients() (*clients, error) { + c := &clients{} + if *protocol == "h1tls" || *protocol == "h2tls" { + cert, err := os.ReadFile(*ca); if err != nil { return nil, err } + roots := x509.NewCertPool(); if !roots.AppendCertsFromPEM(cert) { return nil, fmt.Errorf("invalid test CA") } + alpn := "http/1.1"; if *protocol == "h2tls" { alpn = "h2" } + c.tlsConfig = &tls.Config{RootCAs:roots, ServerName:"localhost", NextProtos:[]string{alpn}, MinVersion:tls.VersionTLS12} + } + if *protocol == "h2c" || *protocol == "h2tls" { + if *proxy == "" { return nil, fmt.Errorf("h2 requires proxy address") } + tr := &http2.Transport{AllowHTTP:true} + for i:=0; i<*connections; i++ { + conn, err := c.dial(); if err != nil { c.close(); return nil, err } + cc, err := tr.NewClientConn(conn); if err != nil { conn.Close(); c.close(); return nil, err } + c.h2 = append(c.h2, cc) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + err = cc.Ping(ctx); cancel(); if err != nil { c.close(); return nil, err } + } + } else { + dialer := &net.Dialer{Timeout:5*time.Second, KeepAlive:30*time.Second} + c.h1 = &http.Transport{ + Proxy:nil, DisableKeepAlives:*fresh, DisableCompression:true, + MaxIdleConns:*concurrency, MaxIdleConnsPerHost:*concurrency, MaxConnsPerHost:*concurrency, + IdleConnTimeout:15*time.Second, TLSHandshakeTimeout:5*time.Second, ResponseHeaderTimeout:10*time.Second, + ForceAttemptHTTP2:false, TLSNextProto:make(map[string]func(string,*tls.Conn) http.RoundTripper), TLSClientConfig:c.tlsConfig, + DialContext:func(ctx context.Context, network, addr string)(net.Conn,error) { + conn, err := dialer.DialContext(ctx, network, addr); if err == nil { c.dials.Add(1) }; return conn,err + }, + } + if *proxy != "" { + scheme := "http"; if *protocol == "h1tls" { scheme = "https" } + u, err := url.Parse(scheme+"://"+*proxy); if err != nil { return nil, err }; c.h1.Proxy = http.ProxyURL(u) + } + } + return c, nil +} +func (c *clients) dial() (net.Conn,error) { + addr := *proxy; if addr == "" { addr = *target } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second); defer cancel() + conn, err := (&net.Dialer{}).DialContext(ctx,"tcp",addr); if err != nil { return nil,err } + c.dials.Add(1) + if c.tlsConfig != nil { + secure := tls.Client(conn,c.tlsConfig) + if err = secure.HandshakeContext(ctx); err != nil { conn.Close(); return nil,err } + if *protocol == "h2tls" && secure.ConnectionState().NegotiatedProtocol != "h2" { secure.Close(); return nil,fmt.Errorf("h2 ALPN not negotiated") } + return secure,nil + } + return conn,nil +} +func (c *clients) close() { if c.h1 != nil { c.h1.CloseIdleConnections() }; for _, cc := range c.h2 { _ = cc.Close() } } +func (c *clients) request(worker int, payload, received []byte) (int,error) { + ctx,cancel := context.WithTimeout(context.Background(),10*time.Second); defer cancel() + var body io.Reader + if *method == "POST" { body = bytes.NewReader(payload) } + req,err := http.NewRequestWithContext(ctx,*method,"http://"+*target+"/data?size="+strconv.Itoa(*size),body) + if err != nil { return 0,err } + var resp *http.Response + if c.h1 != nil { resp,err=c.h1.RoundTrip(req) } else { resp,err=c.h2[worker%len(c.h2)].RoundTrip(req) } + if err != nil { return 0,err }; defer resp.Body.Close() + if resp.StatusCode != 200 { return resp.ProtoMajor, fmt.Errorf("HTTP status %d",resp.StatusCode) } + if len(c.h2)>0 && resp.ProtoMajor != 2 { return resp.ProtoMajor,fmt.Errorf("expected HTTP/2, got %s",resp.Proto) } + if _,err=io.ReadFull(resp.Body, received); err != nil { return resp.ProtoMajor,err } + var extra [1]byte + n,err:=resp.Body.Read(extra[:]); if n!=0 || err!=io.EOF { return resp.ProtoMajor,fmt.Errorf("unexpected body end: n=%d err=%v",n,err) } + if !bytes.Equal(payload,received) { return resp.ProtoMajor,fmt.Errorf("body mismatch") } + return resp.ProtoMajor,nil +} + +type tunnel struct { r io.Reader; w io.Writer; closeFn func(); once sync.Once } +func (t *tunnel) close() { t.once.Do(t.closeFn) } +func (c *clients) openTunnel(worker int) (*tunnel,error) { + if len(c.h2)>0 { + pr,pw := io.Pipe() + ctx,cancel:=context.WithCancel(context.Background()) + req:=(&http.Request{Method:"CONNECT",URL:&url.URL{Scheme:"http",Host:*target},Host:*target,Header:make(http.Header),Body:pr,ContentLength:-1}).WithContext(ctx) + timer:=time.AfterFunc(10*time.Second,cancel) + resp,err:=c.h2[worker%len(c.h2)].RoundTrip(req); timer.Stop() + if err!=nil { cancel();pr.Close();pw.Close();return nil,err } + if resp.StatusCode!=200 { cancel();resp.Body.Close();pr.Close();pw.Close();return nil,fmt.Errorf("CONNECT status %d",resp.StatusCode) } + return &tunnel{r:resp.Body,w:pw,closeFn:func(){cancel();_ = pw.Close();_ = pr.Close();_ = resp.Body.Close()}},nil + } + conn,err:=c.dial();if err!=nil{return nil,err} + if *proxy==""{return &tunnel{r:conn,w:conn,closeFn:func(){conn.Close()}},nil} + _ = conn.SetDeadline(time.Now().Add(10*time.Second)) + if _,err=fmt.Fprintf(conn,"CONNECT %s HTTP/1.1\r\nHost: %s\r\n\r\n",*target,*target);err!=nil{conn.Close();return nil,err} + reader:=bufio.NewReader(conn) + resp,err:=http.ReadResponse(reader,&http.Request{Method:"CONNECT"}) + if err!=nil{conn.Close();return nil,err} + if resp.StatusCode!=200{resp.Body.Close();conn.Close();return nil,fmt.Errorf("CONNECT status %d",resp.StatusCode)} + _ = conn.SetDeadline(time.Time{}) + return &tunnel{r:reader,w:conn,closeFn:func(){conn.Close()}},nil +} +func (t *tunnel) exchange(payload, received []byte) error { + timer:=time.AfterFunc(10*time.Second,t.close);defer timer.Stop() + written:=make(chan error,1) + go func(){_,err:=io.Copy(t.w,bytes.NewReader(payload));written<-err}() + _,err:=io.ReadFull(t.r,received) + if err!=nil{t.close();<-written;return err} + if err=<-written;err!=nil{return err} + if !bytes.Equal(payload,received){return fmt.Errorf("tunnel body mismatch")} + return nil +} + +type result struct { + Success int `json:"success"` + Errors int `json:"errors"` + ErrorSamples []string `json:"error_samples"` + Seconds float64 `json:"seconds"` + RequestsPerSecond float64 `json:"rps"` + MiBPerSecond float64 `json:"mib_s"` + P50 float64 `json:"p50_ms"` + P95 float64 `json:"p95_ms"` + P99 float64 `json:"p99_ms"` + Dials int64 `json:"tcp_dials_including_warmup"` + Protocol string `json:"protocol"` + Concurrency int `json:"concurrency"` + BodyBytes int `json:"body_bytes"` + WarmupSuccess int `json:"warmup_success"` + WarmupErrors int `json:"warmup_errors"` +} +func run() error { + c,err:=newClients();if err!=nil{return err};defer c.close() + tunnels:=make([]*tunnel,*concurrency) + if *kind!="http"{ + var wg sync.WaitGroup;var mu sync.Mutex;var errs []string + for i:=range tunnels{wg.Add(1);go func(i int){defer wg.Done();t,e:=c.openTunnel(i);mu.Lock();defer mu.Unlock();if e!=nil{errs=append(errs,e.Error())}else{tunnels[i]=t}}(i)} + wg.Wait() + defer func(){for _,t:=range tunnels{if t!=nil{t.close()}}}() + if *kind=="idle"{emit(map[string]any{"ready_idle":*concurrency-len(errs),"errors":len(errs),"tcp_connections":c.dials.Load(),"error_samples":errs});time.Sleep(*hold);return nil} + if len(errs)>0{return fmt.Errorf("tunnel setup: %v",errs)} + } + payload:=bytes.Repeat([]byte("x"),*size) + phase:=func(d time.Duration)result{ + var mu sync.Mutex;var wg sync.WaitGroup;var latencies []float64;var samples []string;errors:=0 + start:=time.Now();deadline:=start.Add(d) + for i:=0;i<*concurrency;i++{wg.Add(1);go func(i int){ + defer wg.Done();recv:=make([]byte,*size);var local []float64;localErrors:=0;var localSamples []string + for time.Now().Before(deadline){ + t:=time.Now();var e error + if *kind=="http"{_,e=c.request(i,payload,recv)}else{e=tunnels[i].exchange(payload,recv)} + if e!=nil{localErrors++;if len(localSamples)<2{localSamples=append(localSamples,e.Error())};time.Sleep(time.Millisecond)}else{local=append(local,float64(time.Since(t).Nanoseconds())/1e6)} + } + mu.Lock();latencies=append(latencies,local...);errors+=localErrors + for _,s:=range localSamples{if len(samples)<5{samples=append(samples,s)}};mu.Unlock() + }(i)} + wg.Wait();elapsed:=time.Since(start).Seconds();sort.Float64s(latencies) + pct:=func(q float64)float64{if len(latencies)==0{return 0};i:=int(float64(len(latencies)-1)*q);return latencies[i]} + return result{Success:len(latencies),Errors:errors,ErrorSamples:samples,Seconds:elapsed,RequestsPerSecond:float64(len(latencies))/elapsed, + MiBPerSecond:float64(len(latencies))*float64(*size)/(1<<20)/elapsed,P50:pct(.50),P95:pct(.95),P99:pct(.99), + Protocol:*protocol,Concurrency:*concurrency,BodyBytes:*size} + } + warm:=phase(*warmup) + r:=phase(*duration);r.Dials=c.dials.Load();r.WarmupSuccess=warm.Success;r.WarmupErrors=warm.Errors + emit(r) + return nil +} diff --git a/benchmarks/e2e/nodelay_experiment.py b/benchmarks/e2e/nodelay_experiment.py new file mode 100644 index 0000000..6378a4b --- /dev/null +++ b/benchmarks/e2e/nodelay_experiment.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python3 +"""Apply only the reviewed experimental socket option to an isolated checkout. + +Baseline executable must be copied before running this script. The resulting +binary and git diff are reported separately; no repository ref is changed. +""" +from pathlib import Path +import sys +root = Path(sys.argv[1]) +p = root / 'src/connection.rs' +s = p.read_text() +old = ' let negotiate = async {' +assert s.count(old) == 1 +s = s.replace(old, ' stream.set_nodelay(true)?;\n' + old) +p.write_text(s) +p = root / 'src/transport.rs' +s = p.read_text() +assert s.count('pub async fn connect(') == 1 +s = s.replace('pub async fn connect(', 'async fn connect_inner(', 1) +s += ''' + +/// Experimental low-latency socket option; no framing or policy changes. +pub async fn connect( + host: &str, + port: u16, + bind: Option, + seconds: u64, +) -> io::Result { + let stream = connect_inner(host, port, bind, seconds).await?; + stream.set_nodelay(true)?; + Ok(stream) +} +''' +p.write_text(s) diff --git a/benchmarks/e2e/run.py b/benchmarks/e2e/run.py new file mode 100755 index 0000000..a0cd634 --- /dev/null +++ b/benchmarks/e2e/run.py @@ -0,0 +1,305 @@ +#!/usr/bin/env python3 +"""Bounded local-only proxy benchmarks with retained raw rounds and metadata.""" +from __future__ import annotations +import argparse +import collections +import contextlib +import json +import os +from pathlib import Path +import platform +import random +import socket +import statistics +import subprocess +import tempfile +import time + + +def snapshot(pid: int) -> dict[str, float]: + try: + root = Path(f"/proc/{pid}") + fields = (root / "stat").read_text().rsplit(") ", 1)[1].split() + status = {line.split(":", 1)[0]: line.split(":", 1)[1].strip() + for line in (root / "status").read_text().splitlines() if ":" in line} + return {"cpu_seconds": (int(fields[11]) + int(fields[12])) / os.sysconf("SC_CLK_TCK"), + "rss_mib": int(status.get("VmRSS", "0 kB").split()[0]) / 1024, + "threads": int(status.get("Threads", "0")), "fds": len(list((root / "fd").iterdir()))} + except OSError: + # poll() and /proc reads are not atomic. An exiting process may deny + # fd inspection before its procfs directory disappears. Skip only this + # resource sample; the driver's request/error accounting is separate. + return {} + + +def stop(p: subprocess.Popen) -> None: + if p.poll() is None: + p.terminate() + try: + p.wait(timeout=5) + except subprocess.TimeoutExpired: + p.kill() + p.wait(timeout=5) + + +def ready(port: int, p: subprocess.Popen) -> None: + deadline = time.monotonic() + 10 + while time.monotonic() < deadline: + if p.poll() is not None: + raise RuntimeError(f"server exited with {p.returncode}") + try: + with socket.create_connection(("127.0.0.1", port), timeout=.2): + return + except OSError: + time.sleep(.05) + raise RuntimeError(f"port {port} never became ready") + + +def checked(command: list[str]) -> str: + return subprocess.run(command, check=True, text=True, capture_output=True, timeout=15).stdout.strip() + + +def main() -> None: + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument("--rust", required=True) + ap.add_argument("--c-proxy", required=True) + ap.add_argument("--rust-nodelay", help="optional explicitly patched experimental binary") + ap.add_argument("--driver", required=True) + ap.add_argument("--output", default="benchmark-results") + ap.add_argument("--rounds", type=int, default=3) + ap.add_argument("--seconds", type=int, default=4) + args = ap.parse_args() + if not 1 <= args.rounds <= 5 or not 1 <= args.seconds <= 15: + raise ValueError("bounded rounds/duration required") + args.rust, args.c_proxy, args.driver = [str(Path(x).resolve(strict=True)) for x in (args.rust, args.c_proxy, args.driver)] + if args.rust_nodelay: + args.rust_nodelay = str(Path(args.rust_nodelay).resolve(strict=True)) + out = Path(args.output).resolve() + out.mkdir(parents=True, exist_ok=True) + cpus = sorted(os.sched_getaffinity(0)) + if len(cpus) < 3: + raise RuntimeError("benchmark needs >=3 logical CPUs") + proxy_cpu, origin_cpu, driver_cpu = cpus[:3] + env = dict(os.environ, TOKIO_WORKER_THREADS="1", GOMAXPROCS="1", RUST_LOG="off") + for k in list(env): + if k.lower() in {"http_proxy", "https_proxy", "all_proxy", "no_proxy"}: + del env[k] + meta = {"date_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + "rust_commit": "d500d2510475daafa8269e09caea6d2043c26aa5", + "c_release": "1.11.3", "c_tar_sha256": "9bcf46db1a2375ff3e3d27a41982f1efec4706cce8899ff9f33323a8218f7592", + "kernel": platform.platform(), "cpu_affinity": cpus, + "proxy_cpu": proxy_cpu, "origin_cpu": origin_cpu, "generator_cpu": driver_cpu, + "lscpu": checked(["lscpu"]), "topology": checked(["lscpu", "-e=CPU,CORE,SOCKET"]), + "go": checked(["go", "version"]), "rustc": checked(["rustc", "--version"]), + "gcc": checked(["gcc", "--version"]).splitlines()[0], + "curl": checked(["/usr/bin/curl", "--version"]).splitlines()[0], + "memory": Path("/proc/meminfo").read_text(), "rounds": args.rounds, "measurement_seconds": args.seconds, + "warmup_seconds": 1, "sampler_interval_seconds": .1, + "runtime": {"TOKIO_WORKER_THREADS": 1, "GOMAXPROCS": 1}, + "limits": Path("/proc/self/limits").read_text(), + "methodology": "closed-loop fixed concurrency; every response byte validated; successful full-body latency; no Internet origin or TLS bypass", + "c_build": "release tarball ./configure --disable-manpage-support CFLAGS=-O3 -DNDEBUG; make", + "rust_build": "cargo build --release --locked on pinned source, unchanged baseline runtime code", + "nodelay_experiment": bool(args.rust_nodelay), + "nodelay_change": "TCP_NODELAY=true on accepted and outgoing sockets; separate binary, same base/dependencies", + "limits_note": "affinity uses logical CPUs; SMT siblings may share a physical core"} + (out / "metadata.json").write_text(json.dumps(meta, indent=2)) + print("METADATA " + json.dumps(meta), flush=True) + with tempfile.TemporaryDirectory(prefix="proxy-benchmark-cert-") as certdir: + cert, key = Path(certdir) / "cert.pem", Path(certdir) / "key.pem" + checked(["openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes", "-keyout", str(key), + "-out", str(cert), "-days", "1", "-subj", "/CN=localhost", "-addext", "subjectAltName=DNS:localhost"]) + key.chmod(0o600) + @contextlib.contextmanager + def service(impl: str, name: str): + if impl == "direct": + yield None + return + binary = args.c_proxy if impl == "c" else (args.rust_nodelay if "nodelay" in impl else args.rust) + port = 18889 if impl.endswith("-tls") else 18888 + common = f"Listen 127.0.0.1\nPort {port}\nTimeout 60\nMaxClients 1024\nAllow 127.0.0.1\nConnectPort 18081\n" + if impl == "c": + # Foreground: capture stdout. No optional file-path directives + # (C requires quoted file paths and regular log files). + content = common + "LogLevel Critical\n" + else: + content = common + "LogLevel Off\nShutdownTimeout 1\nMaxInflightRequests 1024\nMaxConcurrentStreams 32\n" + content += f"TLSCert {cert}\nTLSKey {key}\nHTTP2 Yes\n" if impl.endswith("-tls") else "AllowH2C Yes\n" + conf = out / f"{name}.conf" + conf.write_text(content) + log = (out / f"{name}.proxy.log").open("wb") + cmd = ["taskset", "-c", str(proxy_cpu), binary, "-c", str(conf)] + if impl == "c": cmd.append("-d") + p = subprocess.Popen(cmd, stdout=log, stderr=log, env=env) + try: + try: + ready(port, p) + except RuntimeError as error: + raise RuntimeError(f"{name}: {error}: " + (out / f"{name}.proxy.log").read_text(errors="replace")) from error + time.sleep(.2) + yield p + finally: + stop(p) + log.close() + conf.write_text(content.replace(str(cert), "TEST_CERT.pem").replace(str(key), "TEST_KEY.pem")) + + origin_log = (out / "origin.log").open("wb") + origin = subprocess.Popen(["taskset", "-c", str(origin_cpu), args.driver, "-mode=origin"], env=env, stdout=origin_log, stderr=origin_log) + try: + ready(18080, origin) + modes = [("c", "h1"), ("rust", "h1"), ("rust", "h2c"), ("rust-tls", "h2tls")] + if args.rust_nodelay: + modes += [("rust-nodelay", "h2c"), ("rust-nodelay-tls", "h2tls")] + for impl, proto in modes: + with service(impl, f"preflight-{impl}-{proto}"): + port = 18889 if impl.endswith("-tls") else 18888 + completed = subprocess.run([args.driver, f"-protocol={proto}", f"-proxy=127.0.0.1:{port}", + f"-ca={cert}", "-c=1", "-connections=1", "-duration=200ms", "-warmup=0s"], + env=env, capture_output=True, text=True, timeout=15, check=True) + result = json.loads(completed.stdout) + if result["errors"] or not result["success"]: + raise RuntimeError(f"preflight failed {impl}/{proto}: {result}") + print(f"PREFLIGHT {impl}/{proto}: validated responses={result['success']}, errors=0", flush=True) + cases = [] + def case(name, impl, proto="h1", c=32, size=1024, method="GET", fresh=False, kind="http"): + cases.append(dict(name=name, impl=impl, protocol=proto, c=c, size=size, method=method, fresh=fresh, kind=kind)) + case("direct-h1-fresh-32", "direct", fresh=True) + case("direct-h1-fresh-128", "direct", c=128, fresh=True) + case("direct-h1-reuse-32", "direct") + case("direct-get-1MiB-8", "direct", c=8, size=1<<20, fresh=True) + for impl in ("c", "rust"): + for c in (1, 32, 128): + case(f"{impl}-h1-fresh-{c}", impl, c=c, fresh=True) + case(f"{impl}-h1-reuse-32", impl) + case(f"{impl}-get-1MiB-8", impl, c=8, size=1<<20, fresh=True) + case(f"{impl}-post-1MiB-8", impl, c=8, size=1<<20, method="POST", fresh=True) + for proto in ("h2c", "h2tls"): + for c in (1, 32, 128): + case(f"rust-{proto}-{c}", "rust-tls" if proto == "h2tls" else "rust", proto, c) + case("rust-h1tls-reuse-32", "rust-tls", "h1tls") + case("rust-h2tls-get-1MiB-8", "rust-tls", "h2tls", 8, 1<<20) + for impl, proto in (("direct", "h1"), ("c", "h1"), ("rust", "h1"), ("rust-tls", "h2tls")): + case(f"{impl}-{proto}-tunnel-1MiB-8", impl, proto, 8, 1<<20, kind="tunnel") + if args.rust_nodelay: + for proto in ("h2c", "h2tls"): + for c in (1, 32): + case(f"nodelay-{proto}-{c}", "rust-nodelay-tls" if proto == "h2tls" else "rust-nodelay", proto, c) + case("nodelay-h1-reuse-32", "rust-nodelay") + case("nodelay-post-1MiB-8", "rust-nodelay", c=8, size=1<<20, method="POST", fresh=True) + case("nodelay-h1-tunnel-1MiB-8", "rust-nodelay", c=8, size=1<<20, kind="tunnel") + (out / "cases.json").write_text(json.dumps(cases, indent=2)) + all_rounds = [] + rng = random.Random(20260919) + for r in range(1, args.rounds + 1): + order = cases.copy(); rng.shuffle(order) + for item in order: + name = f"r{r}-{item['name']}" + with service(item["impl"], name) as p: + port = 18889 if item["impl"].endswith("-tls") else 18888 + command = ["taskset", "-c", str(driver_cpu), args.driver, + f"-protocol={item['protocol']}", f"-c={item['c']}", f"-size={item['size']}", + f"-method={item['method']}", f"-kind={item['kind']}", + f"-connections={(item['c'] + 31)//32}", f"-ca={cert}", + f"-duration={args.seconds}s", "-warmup=1s", "-fresh="+str(item["fresh"]).lower(), + "-target=127.0.0.1:" + ("18080" if item["kind"] == "http" else "18081")] + if p is not None: command.append(f"-proxy=127.0.0.1:{port}") + stdout = (out / f"{name}.jsonl").open("w") + stderr = (out / f"{name}.load.log").open("w") + loader = subprocess.Popen(command, stdout=stdout, stderr=stderr, env=env) + pids = {"origin": origin.pid, "generator": loader.pid} + if p is not None: pids["proxy"] = p.pid + initial = {k: snapshot(v) for k, v in pids.items()} + samples = collections.defaultdict(list) + start = time.monotonic() + try: + while loader.poll() is None: + if time.monotonic() - start > args.seconds + 40: raise RuntimeError(f"load deadline {name}") + for k, v in pids.items(): + s = snapshot(v) + if s: samples[k].append(s) + time.sleep(.1) + elapsed = time.monotonic() - start + finally: + stop(loader); stdout.close(); stderr.close() + if loader.returncode: + raise RuntimeError(f"load failed {name}: " + (out / f"{name}.load.log").read_text()[-5000:]) + result = json.loads((out / f"{name}.jsonl").read_text()) + result.update(case=item["name"], round=r) + for k, values in samples.items(): + begin = initial[k].get("cpu_seconds", 0) + result[f"{k}_cpu_pct"] = (values[-1]["cpu_seconds"] - begin) / elapsed * 100 + result[f"{k}_peak_rss_mib"] = max(s["rss_mib"] for s in values) + result[f"{k}_peak_threads"] = max(s["threads"] for s in values) + result[f"{k}_peak_fds"] = max(s["fds"] for s in values) + all_rounds.append(result) + (out / "rounds.json").write_text(json.dumps(all_rounds, indent=2)) + print(f"ROUND {r} {item['name']}: {result['rps']:.1f} req/s p99={result['p99_ms']:.3f}ms errors={result['errors']}", flush=True) + + idle = [] + for impl, proto in (("c", "h1"), ("rust", "h1"), ("rust-tls", "h2tls")): + for c in (128, 512): + name = f"idle-{impl}-{proto}-{c}" + with service(impl, name) as p: + baseline = snapshot(p.pid) + port = 18889 if impl.endswith("-tls") else 18888 + output = (out / f"{name}.jsonl").open("w") + errfile = (out / f"{name}.log").open("w") + loader = subprocess.Popen(["taskset", "-c", str(driver_cpu), args.driver, "-kind=idle", f"-protocol={proto}", + f"-proxy=127.0.0.1:{port}", "-target=127.0.0.1:18081", f"-c={c}", + f"-connections={(c+31)//32}", f"-ca={cert}", "-hold=6s"], + env=env, stdout=output, stderr=errfile) + try: + deadline = time.monotonic() + 30 + while not (out / f"{name}.jsonl").read_text().strip(): + if loader.poll() is not None or time.monotonic() > deadline: + raise RuntimeError("idle setup: " + (out / f"{name}.log").read_text()) + time.sleep(.1) + detail = json.loads((out / f"{name}.jsonl").read_text()) + time.sleep(.5) + occupied = snapshot(p.pid) + t = time.monotonic(); time.sleep(3) + after = snapshot(p.pid) + detail.update(case=name, baseline=baseline, occupied=occupied, + idle_cpu_pct=(after["cpu_seconds"]-occupied["cpu_seconds"])/(time.monotonic()-t)*100) + loader.wait(timeout=15) + time.sleep(1) + detail["after_close"] = snapshot(p.pid) + idle.append(detail) + print("IDLE " + json.dumps(detail), flush=True) + finally: + stop(loader); output.close(); errfile.close() + (out / "idle.json").write_text(json.dumps(idle, indent=2)) + summary = [] + for item in cases: + rs = [x for x in all_rounds if x["case"] == item["name"]] + row = {"case": item["name"], "success_total": sum(x["success"] for x in rs), "errors_total": sum(x["errors"] for x in rs), + "warmup_errors_total": sum(x["warmup_errors"] for x in rs)} + for k in ("rps", "mib_s", "p50_ms", "p99_ms", "proxy_cpu_pct", "proxy_peak_rss_mib", "proxy_peak_threads", + "proxy_peak_fds", "generator_cpu_pct", "origin_cpu_pct", "tcp_dials_including_warmup"): + row[k] = statistics.median(x.get(k, 0) for x in rs) + row["rps_min"] = min(x["rps"] for x in rs); row["rps_max"] = max(x["rps"] for x in rs) + summary.append(row) + (out / "summary.json").write_text(json.dumps(summary, indent=2)) + print("SUMMARY_JSON " + json.dumps(summary, separators=(",", ":")), flush=True) + lines = ["# Loopback benchmark — pinned proxy implementations", "", "Rust: `d500d2510475daafa8269e09caea6d2043c26aa5`; C: `1.11.3`.", "", + f"{args.rounds} rounds; 1 s warmup + {args.seconds} s measurement. Shuffled order. One logical CPU per process; physical cores may be shared through SMT.", "", + "Cases prefixed nodelay use a separate experimental binary with TCP_NODELAY enabled; this is not main.", "", + "Closed-loop latency, successful full-body responses only; not an open-loop tail-latency SLA. All response bytes checked. RSS/CPU sampled over warmup and measurement. Shared CI runner, no WAN/TLS-loss modeling.", "", + "Values are medians of per-round values. RPS is completed, validated responses / elapsed measurement+drain time. Tunnel MiB/s is one-way payload; echo carries the same payload back.", "", + "| Case | req/s | req/s range | MiB/s | p50 ms | p99 ms | errors | proxy RSS MiB | proxy CPU % |", "|---|---:|---:|---:|---:|---:|---:|---:|---:|"] + for x in summary: + lines.append(f"| {x['case']} | {x['rps']:.1f} | {x['rps_min']:.1f}–{x['rps_max']:.1f} | {x['mib_s']:.1f} | {x['p50_ms']:.3f} | {x['p99_ms']:.3f} | {x['errors_total']} | {x['proxy_peak_rss_mib']:.2f} | {x['proxy_cpu_pct']:.1f} |") + lines += ["", "## Held CONNECT tunnels", "", "Idle cases are one observation, not repeated or a leak/soak certification.", "", "| Case | Established | TCP connections | RSS MiB | threads | FDs | idle CPU % | FDs after close |", "|---|---:|---:|---:|---:|---:|---:|---:|"] + for x in idle: + s = x["occupied"] + lines.append(f"| {x['case']} | {x['ready_idle']} | {x['tcp_connections']} | {s['rss_mib']:.2f} | {s['threads']} | {s['fds']} | {x['idle_cpu_pct']:.2f} | {x['after_close']['fds']} |") + (out / "REPORT.md").write_text("\n".join(lines) + "\n") + if os.environ.get("GITHUB_STEP_SUMMARY"): + with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as f: f.write("\n".join(lines) + "\n") + if any(x["errors_total"] or x["warmup_errors_total"] for x in summary) or any(x["errors"] for x in idle): + raise RuntimeError("benchmark recorded errors; consult report, do not claim clean performance") + finally: + stop(origin); origin_log.close() + +if __name__ == "__main__": + main() diff --git a/docs/benchmarks/2026-09-19.md b/docs/benchmarks/2026-09-19.md new file mode 100644 index 0000000..a0f367f --- /dev/null +++ b/docs/benchmarks/2026-09-19.md @@ -0,0 +1,137 @@ +# Tinyproxy-Rust: measured loopback performance — 2026-09-19 + +## Source identity and verification + +Completed run: https://github.com/Ray0907/tinyproxy-rust/actions/runs/35413653419 + +- Unchanged Rust runtime baseline: `d500d2510475daafa8269e09caea6d2043c26aa5` (HTTP/2 merge). +- Benchmark harness: `93353a2dcdec2ecf0d9dae5e373611b99a06e6e3`. +- Comparator: official C Tinyproxy 1.11.3, release archive SHA-256 `9bcf46db1a2375ff3e3d27a41982f1efec4706cce8899ff9f33323a8218f7592`. +- Separate experimental Rust binary: same baseline and dependencies, with TCP_NODELAY enabled on accepted and outgoing TCP sockets. **This experiment is not applied to main.** Its exact patch and binary digest are in the artifact. + +All 35 timed workloads completed three shuffled rounds: **105 observations, 1,557,891 validated measured completions, zero measured request errors, and zero warmup errors**. Completions include direct controls, HTTP requests, and tunnel echo transfers. All six idle-tunnel setups also had zero errors. Every successful payload was checked byte-for-byte. + +Both Rust binaries passed **57 regression tests** and five verified-TLS curl interoperability checks before measurement. The experimental binary also passed Clippy with warnings denied. The Actions job, including builds, tests, timed workloads and artifact upload, completed successfully. + +Raw artifact: https://github.com/Ray0907/tinyproxy-rust/actions/runs/35413653419/artifacts/10574962709 + +Artifact ZIP SHA-256: `df3fe8feb3894866be5344c51d81d0d147dcb55cd35a4686bd5a61f81cb2b77d`. Retention is 30 days, through 2026-10-19. It contains raw rounds, summaries, idle samples, test/build logs, resolved dependency files, configurations, source IDs and executable hashes, but no generated private keys. Earlier incomplete attempts are excluded; their harness problems are documented in [METHODOLOGY.md](METHODOLOGY.md). + +## Method and environment + +Measured on a GitHub Actions Ubuntu 24.04 VM, AMD EPYC 7763, four logical CPUs on two exposed physical cores (SMT enabled). Rust 1.98.1, Go 1.27.1, GCC 13.3. Rust was built with `cargo build --release --locked`; C with `-O3 -DNDEBUG`. + +Proxy, origin and generator were pinned to logical CPUs 0, 1 and 2 respectively. **CPU 0 and CPU 1 are SMT siblings on the same physical core: this is not full physical-core isolation.** Both proxies had the same one-logical-CPU affinity. Rust used one Tokio worker; Go used GOMAXPROCS=1. + +Each round had 1 second warmup and a 4-second measured admission window. Throughput includes draining requests admitted before the deadline. Latency covers complete successful response bodies. Tables show medians of three per-round measurements, not pooled percentiles. Configurations used MaxClients 1024; Rust additionally used MaxInflightRequests 1024 and MaxConcurrentStreams 32. Normal request logging, authentication and filter-list costs were not enabled in throughput tests; source ACLs allowed localhost only. + +These are short **closed-loop, fixed-concurrency, loopback tests**, not WAN measurements, fixed-arrival-rate SLOs, long soak tests, or a comprehensive security audit. CPU/RSS sampling spans warmup and measurement; peak RSS is resident process memory, excluding kernel socket memory and virtual stack reservations. The raw data includes direct-to-origin controls and generator/origin CPU usage to expose test-side bottlenecks. + +## 1. HTTP/1: equal fresh-connection workloads + +1 KiB response, a new client TCP connection for every request: + +| Concurrency | C req/s | Rust req/s | Rust / C | C p99 ms | Rust p99 ms | +|---|---:|---:|---:|---:|---:| +| 1 | 2,031.2 | 2,536.6 | 1.25x | 0.638 | 0.483 | +| 32 | 3,107.1 | 5,240.8 | 1.69x | 14.174 | 7.806 | +| 128 | 3,016.5 | 5,061.5 | 1.68x | 57.434 | 31.293 | + +The concurrency-32 RPS ranges across rounds were 3,088.3–3,125.1 for C and 5,154.1–5,243.7 for Rust. Median proxy CPU utilization was 95.0% and 97.2% of their assigned logical CPU respectively; generator utilization was 55.9% and 78.4%. The generator was not at its own observed saturation point in these paired proxy cases, but shared-core contention remains a limitation. + +When client reuse was allowed at concurrency 32, C achieved 3,183.1 req/s and Rust 6,519.2 req/s. **That 2.05x comparison includes a connection-behavior difference:** C redialed a median 15,962 times including warmup, whereas Rust used 32 TCP connections. It must not be described as an identical connection-lifecycle comparison. Rust still opens HTTP/1.1 origin connections per request; origin pooling is not implemented here. + +## 2. HTTP/2: a real fixed-delay problem and a controlled experiment + +1 KiB response. One client-to-proxy HTTP/2 connection for concurrency 1 or 32; TLS cases validate the localhost certificate and negotiate ALPN h2. + +| Proxy hop / concurrency | Baseline req/s | NODELAY req/s | Baseline p50 ms | NODELAY p50 ms | Baseline p99 ms | NODELAY p99 ms | +|---|---:|---:|---:|---:|---:|---:| +| h2c / 1 | 24.4 | 3,249.9 | 41.004 | 0.300 | 41.093 | 0.399 | +| h2c / 32 | 751.1 | 6,495.8 | 42.959 | 5.013 | 43.523 | 6.597 | +| TLS h2 / 1 | 24.4 | 3,109.2 | 41.002 | 0.317 | 41.103 | 0.383 | +| TLS h2 / 32 | 754.6 | 6,305.5 | 42.655 | 5.171 | 44.073 | 6.773 | + +The unchanged baseline therefore has an approximately 41 ms wait in these low-concurrency small-response workloads, despite passing functional tests. The separate NODELAY build removes that wait. At 32 concurrent TLS h2 streams, measured throughput increases **8.36x** and p99 falls from 44.073 to 6.773 ms. Baseline proxy CPU in that case was only 11.5%; the experimental binary reached 97.7%, consistent with removing an I/O wait rather than speeding up an already CPU-bound implementation. + +The only runtime change in the experiment is `set_nodelay(true)` at the accepted socket and after dialing an outgoing socket. Tokio documents that this disables Nagle buffering: https://docs.rs/tokio/latest/tokio/net/struct.TcpStream.html#method.set_nodelay . The result supports a TCP buffering/delayed-ACK explanation, but no packet capture was taken to establish the detailed packet/ACK sequence. It is not evidence that HTTP/2 is inherently faster than HTTP/1. The experiment was not run at concurrency 128. + +HTTP/2 here is the **client-to-proxy hop**. Plain HTTP origins are still reached over HTTP/1.1. HTTPS CONNECT remains an opaque tunnel. The benchmark does not measure an HTTP/2 origin pool or TLS interception. + +## 3. Large transfers: gains, but NODELAY is not free + +Concurrency 8, 1 MiB payload. MiB/s counts one payload direction. POST returns the uploaded payload; CONNECT echoes the payload back, so total two-way traffic is larger. + +| Workload | C MiB/s | Rust baseline MiB/s | NODELAY MiB/s | +|---|---:|---:|---:| +| GET, fresh HTTP/1 | 341.9 | 1,030.9 | not measured | +| POST + response, fresh HTTP/1 | 265.2 | 391.2 | 351.4 | +| Established HTTP/1 CONNECT echo | 125.1 | 289.5 | 276.6 | + +Rust's baseline GET throughput is 3.01x C in this workload, but no universal speed ratio follows from a short loopback test. + +**The NODELAY experiment has a tradeoff:** POST throughput decreases 10.2%, although POST p99 improves from 57.390 to 25.751 ms. HTTP/1 CONNECT echo throughput decreases 4.5%; its proxy CPU utilization increases from 53.3% to 97.8%, while p99 improves from 49.235 to 35.255 ms. Those costs must be considered before broadly enabling the option. HTTP/2 small-response latency and bulk TCP relay buffering should be tuned separately. + +Baseline HTTP/2-over-TLS CONNECT echo measured 307.5 MiB/s. It has different framing/encryption costs from plaintext C/H1 CONNECT and is not used as an equal-transport C comparison. + +## 4. Held CONNECT tunnels: fewer threads and sockets, not lower RSS than C + +The following are single short observations with 512 successfully established tunnels, not repeated load/soak tests: + +| Implementation | Client TCP connections | Proxy RSS MiB | Threads | Proxy FDs | Idle CPU % | +|---|---:|---:|---:|---:|---:| +| C / HTTP/1 | 512 | 10.77 | 513 | 1,028 | 0.00 | +| Rust / HTTP/1 | 512 | 20.32 | 2 | 1,034 | 0.00 | +| Rust / TLS HTTP/2 | 16 | 17.82 | 2 | 538 | 0.33 | + +C has lower resident memory in these cases. Rust reduces threads, and H2 multiplexing reduces client-facing TCP sockets. Each CONNECT tunnel still requires its own origin socket. Do not turn the thread count or virtual stack reservations into an unsupported claim that Rust has lower actual memory use. + +One second after clients closed, descriptors returned to the before-load counts for every idle case: 4 for C and 10 for Rust. That observation is encouraging but not a proof of long-duration leak freedom. + +## Complete timed summary + +Values below are medians of three rounds. RPS includes only validated completions; p99 is full-body latency of successful operations. Direct rows have no proxy process, hence proxy RSS/CPU are not applicable. + +| Case | req/s | RPS range | MiB/s | p50 ms | p99 ms | errors | proxy RSS MiB | +|---|---:|---:|---:|---:|---:|---:|---:| +| direct-h1-fresh-32 | 7712.0 | 7698.6–7716.1 | 7.5 | 3.942 | 7.356 | 0 | n/a | +| direct-h1-fresh-128 | 6911.0 | 6894.4–7140.3 | 6.7 | 19.072 | 26.229 | 0 | n/a | +| direct-h1-reuse-32 | 35280.9 | 34358.2–35605.0 | 34.5 | 0.899 | 2.033 | 0 | n/a | +| direct-get-1MiB-8 | 2888.7 | 2865.5–2931.9 | 2888.7 | 2.693 | 4.330 | 0 | n/a | +| c-h1-fresh-1 | 2031.2 | 2004.2–2036.4 | 2.0 | 0.486 | 0.638 | 0 | 3.15 | +| c-h1-fresh-32 | 3107.1 | 3088.3–3125.1 | 3.0 | 10.176 | 14.174 | 0 | 4.04 | +| c-h1-fresh-128 | 3016.5 | 3010.2–3085.9 | 2.9 | 41.714 | 57.434 | 0 | 5.59 | +| c-h1-reuse-32 | 3183.1 | 3176.0–3207.5 | 3.1 | 9.929 | 13.871 | 0 | 4.03 | +| c-get-1MiB-8 | 341.9 | 339.0–342.9 | 341.9 | 17.554 | 46.150 | 0 | 3.46 | +| c-post-1MiB-8 | 265.2 | 260.5–266.0 | 265.2 | 27.858 | 52.298 | 0 | 4.27 | +| rust-h1-fresh-1 | 2536.6 | 2491.1–2558.2 | 2.5 | 0.387 | 0.483 | 0 | 4.75 | +| rust-h1-fresh-32 | 5240.8 | 5154.1–5243.7 | 5.1 | 6.215 | 7.806 | 0 | 6.28 | +| rust-h1-fresh-128 | 5061.5 | 4982.6–5065.2 | 4.9 | 25.225 | 31.293 | 0 | 10.80 | +| rust-h1-reuse-32 | 6519.2 | 6465.5–6556.0 | 6.4 | 5.072 | 5.723 | 0 | 6.43 | +| rust-get-1MiB-8 | 1030.9 | 1007.8–1094.4 | 1030.9 | 7.761 | 9.648 | 0 | 9.00 | +| rust-post-1MiB-8 | 391.2 | 380.4–396.6 | 391.2 | 14.084 | 57.390 | 0 | 7.58 | +| rust-h2c-1 | 24.4 | 24.4–24.4 | 0.0 | 41.004 | 41.093 | 0 | 4.72 | +| rust-h2c-32 | 751.1 | 750.6–754.4 | 0.7 | 42.959 | 43.523 | 0 | 5.53 | +| rust-h2c-128 | 3050.4 | 3019.8–3091.0 | 3.0 | 42.051 | 50.732 | 0 | 7.41 | +| rust-h2tls-1 | 24.4 | 24.4–24.4 | 0.0 | 41.002 | 41.103 | 0 | 5.48 | +| rust-h2tls-32 | 754.6 | 753.4–757.0 | 0.7 | 42.655 | 44.073 | 0 | 6.22 | +| rust-h2tls-128 | 3038.9 | 3036.6–3049.4 | 3.0 | 42.050 | 46.266 | 0 | 8.47 | +| rust-h1tls-reuse-32 | 6089.3 | 6071.9–6188.1 | 5.9 | 5.397 | 6.418 | 0 | 7.14 | +| rust-h2tls-get-1MiB-8 | 725.5 | 720.3–734.6 | 725.5 | 11.244 | 13.747 | 0 | 8.22 | +| direct-h1-tunnel-1MiB-8 | 2865.4 | 2745.5–2933.8 | 2865.4 | 1.060 | 21.773 | 0 | n/a | +| c-h1-tunnel-1MiB-8 | 125.1 | 123.7–125.9 | 125.1 | 62.997 | 93.665 | 0 | 3.35 | +| rust-h1-tunnel-1MiB-8 | 289.5 | 280.0–290.0 | 289.5 | 42.281 | 49.235 | 0 | 4.89 | +| rust-tls-h2tls-tunnel-1MiB-8 | 307.5 | 302.0–312.1 | 307.5 | 25.695 | 29.500 | 0 | 6.72 | +| nodelay-h2c-1 | 3249.9 | 3228.1–3298.3 | 3.2 | 0.300 | 0.399 | 0 | 4.80 | +| nodelay-h2c-32 | 6495.8 | 6462.9–6512.1 | 6.3 | 5.013 | 6.597 | 0 | 6.09 | +| nodelay-h2tls-1 | 3109.2 | 3102.6–3138.6 | 3.0 | 0.317 | 0.383 | 0 | 5.43 | +| nodelay-h2tls-32 | 6305.5 | 6252.4–6329.0 | 6.2 | 5.171 | 6.773 | 0 | 6.73 | +| nodelay-h1-reuse-32 | 6433.7 | 6363.9–6440.3 | 6.3 | 5.137 | 5.730 | 0 | 6.42 | +| nodelay-post-1MiB-8 | 351.4 | 350.4–356.5 | 351.4 | 22.785 | 25.751 | 0 | 7.91 | +| nodelay-h1-tunnel-1MiB-8 | 276.6 | 275.6–281.0 | 276.6 | 28.838 | 35.255 | 0 | 4.88 | + +## Recommended next measurements + +Prioritize the demonstrated small-response wait, while preserving the measured bulk-transfer tradeoff. Test accepted/outgoing socket options separately, preserve vectored I/O through transport wrappers, and compare bounded relay buffer sizes before applying one policy to every transport. Then evaluate origin connection pooling with its own correctness and lifecycle tests. These are recommendations based on this run, not already measured improvements. + +See [METHODOLOGY.md](METHODOLOGY.md) and `.github/workflows/benchmark-e2e.yml` for reproduction commands, workload definitions, resource accounting and limitations. Neither this report nor the benchmark branch changes main or makes a universal superiority claim. diff --git a/docs/benchmarks/METHODOLOGY.md b/docs/benchmarks/METHODOLOGY.md new file mode 100644 index 0000000..e4f9d65 --- /dev/null +++ b/docs/benchmarks/METHODOLOGY.md @@ -0,0 +1,54 @@ +# End-to-end benchmark methodology + +## What is being tested + +The baseline is the exact runtime source at `d500d2510475daafa8269e09caea6d2043c26aa5`, including its Cargo.lock, built with `cargo build --release --locked`. The comparator is the official C Tinyproxy 1.11.3 release tarball, checked against SHA-256 `9bcf46db1a2375ff3e3d27a41982f1efec4706cce8899ff9f33323a8218f7592` and built with `./configure --disable-manpage-support CFLAGS='-O3 -DNDEBUG'` and `make`. + +An optional second Rust executable enables TCP_NODELAY on accepted and outgoing TCP sockets. It is labeled `nodelay-*`, never reported as the unmodified baseline, and is not committed to main by the benchmark workflow. Its exact diff and executable digest are retained. Baseline and experiment both run the regression suite and verified-TLS curl interoperability tests before measurement. + +The independent Go load generator and origin live under `benchmarks/e2e`. The runner resolves the explicitly selected Go module version and retains go.mod/go.sum, compiler versions, source commits, executable hashes, CPU topology, memory and file-descriptor limits. Go is test tooling only; the proxy runtime remains Rust and requires no external service or database. + +## Workloads and accounting + +The driver uses loopback-only local HTTP and echo servers. Requests are never sent to Internet origins. GET bodies and POST upload/response bodies are verified byte for byte. Compression is disabled. HTTP errors, protocol errors, size/content mismatches, transport failures and timeouts are counted rather than included as successful throughput. + +Each case has a 1-second warmup and a 4-second measured admission window, repeated three times. Case order is shuffled with seed 20260919. Each proxy process starts afresh for each case; the origin persists. Throughput divides successful completions by elapsed measurement time including the final admitted requests draining. Latencies cover complete successful bodies, not just response headers. Failed request counts and examples, including warmup errors, are retained separately. Percentiles and throughput in the summary are medians of per-round values, not pooled percentiles; raw rounds preserve all reported values and round-to-round throughput ranges. + +HTTP/1 has separate `fresh` and `reuse` cases. `fresh` disables client connection reuse. `reuse` permits reuse, but an implementation can close a connection, requiring the client to redial. The driver reports actual TCP dial counts including warmup. These two cases must not be conflated when discussing implementation efficiency. + +HTTP/2 cases use exactly one client-to-proxy connection for 1 or 32 workers and four connections for 128 workers, with at most 32 concurrent streams per connection. Plain HTTP origins are still reached via HTTP/1.1 by the Rust proxy; this benchmark is not an HTTP/2 origin pooling benchmark. `h2c` is cleartext prior knowledge; `h2tls` verifies a generated localhost certificate and confirms ALPN `h2`. `h1tls` is a TLS proxy-hop control, not ordinary cleartext HTTP/1. + +CONNECT throughput sends a 1 MiB payload to a raw TCP echo origin and receives the same bytes back, with concurrent upload/read to avoid artificial flow-control deadlocks. The reported MiB/s counts the payload in one direction; the network carries the same amount back. It does not include tunnel establishment. A TLS-to-proxy H2 tunnel is not cryptographically cost-equivalent to a plaintext C/H1 tunnel. + +Idle cases hold 128 or 512 CONNECT tunnels. H2 packs these into 4 or 16 client-to-proxy TCP connections respectively; each tunnel still has its own origin TCP connection. The script records before-load RSS/threads/FDs, occupied values, three seconds of idle CPU, and values one second after closing all client connections. These are individual observations, not a long-running memory-leak test. + +## Resource controls and limitations + +Proxy, origin and load generator have separate logical-CPU affinities. Rust uses one Tokio worker and Go uses GOMAXPROCS=1. Logical CPUs can be SMT siblings on shared physical cores; affinity is not physical-core isolation and the retained topology must be consulted. Both proxy implementations are subject to the same one-logical-CPU affinity. MaxClients is 1024; Rust MaxInflightRequests is 1024 and MaxConcurrentStreams is 32. Both allow only localhost clients in these tests. Logging is suppressed to the lowest practical level (Off for Rust, Critical for C); normal per-request logging, authentication and filter costs are not included in the throughput tests. + +Resource sampling reads /proc every 100 ms over setup/warmup/measurement. Peak RSS is a sampled resident-process maximum, not virtual address space and not kernel socket memory. CPU percentages refer to one logical CPU; short bursts and process exit can cause sampling error. Samples lost to a procfs exit race are skipped; the independent load generator's success/error accounting is not changed. Direct-to-origin workloads and generator/origin CPU measurements provide checks for test-side bottlenecks, but do not eliminate them. + +This is a short, closed-loop benchmark on a shared CI VM. It does not establish open-loop p99/p999 service-level objectives, WAN performance, packet-loss behavior, long-duration stability, DoS resistance, full HTTP conformance, or performance on another CPU. Closed-loop latency can hide queueing under a fixed arrival rate. Low-concurrency TLS cases do not include a new TLS handshake for every request. No broad claim that Rust or HTTP/2 is intrinsically faster is justified. + +## Incomplete attempts and harness corrections + +Early attempts failed because optional C file-path directives were unquoted. The initial LogFile /dev/null choice was also unsuitable: even a correctly quoted /dev/null is not a regular log file accepted by C Tinyproxy's safe opener. The corrected foreground configuration omits both LogFile and PidFile and captures stdout instead. It performs a validated HTTP preflight on every proxy mode before timed rounds. + +A subsequent attempt successfully measured both proxies but the monitor stopped on PermissionError while inspecting /proc//fd as a load-generator process exited. The sampler now skips OSError exit races; it does not modify or suppress the driver's request-error counts. These are harness setup/monitoring failures, not measured proxy correctness failures or zero-throughput results. Incomplete attempts remain separate artifacts and are not pooled into a completed run's three-round summary. Runner CPU models may differ between attempts, making such pooling particularly inappropriate. + +## Running and retaining results + +Run `.github/workflows/benchmark-e2e.yml` from the benchmark branch. It has read-only repository permissions, checks out the pinned baseline separately, builds all executables, tests baseline and experiment, executes shuffled measurements, and uploads `benchmark-results` even if a case fails. The report appears in the Actions job summary. Artifacts are retained for 30 days; copy important results before they expire. Generated test private keys stay outside the uploaded result directory. + +For local reproduction, use a Linux machine with at least three available logical CPUs, Rust, Go, gcc/make, Python 3.10+, taskset, openssl and HTTP/2-enabled curl 8.1+. Reproduce the build commands from the workflow and then run: + +```sh +ulimit -n 32768 +python3 benchmarks/e2e/run.py \ + --rust ./rust-baseline \ + --c-proxy ./c-source/src/tinyproxy \ + --driver ./bench-driver \ + --output benchmark-results --rounds 3 --seconds 4 +``` + +To add the labeled TCP_NODELAY experiment, build it separately using the reviewed `nodelay_experiment.py` on a disposable checkout and pass `--rust-nodelay ./rust-nodelay`. Do not overwrite the baseline executable. Consult the workflow for the exact build and validation sequence. The configuration and payload formats are intentionally identical for paired baseline/experimental cases.