From 4e0da23bbc272930eb802701f9f19c8b41ad4a7c Mon Sep 17 00:00:00 2001 From: "Kurzacz, Kamil" Date: Fri, 4 Dec 2026 12:53:21 +0100 Subject: [PATCH 1/4] fix(benchmarks): run benchmark.py users in processes with asyncio benchmark.py ran every user as a thread in one process, so at high concurrency the GIL delayed requests long enough that Envoy closed TLS handshakes the client had not finished, and the immediate retries pushed runs past the failure limit with no successful requests. Users now run as asyncio tasks in several processes (16 users each). Every request still opens its own TCP and TLS connection, users start over a short ramp, errors back off with jitter, and tokens are counted in the main process after each response. The options, output file and CSV columns are unchanged. Signed-off-by: Kurzacz, Kamil --- src/tests/e2e/benchmarks/chatqna/benchmark.py | 297 ++++++++++-------- .../e2e/benchmarks/chatqna/requirements.txt | 1 + 2 files changed, 166 insertions(+), 132 deletions(-) diff --git a/src/tests/e2e/benchmarks/chatqna/benchmark.py b/src/tests/e2e/benchmarks/chatqna/benchmark.py index 91fe7912..34b53fb4 100644 --- a/src/tests/e2e/benchmarks/chatqna/benchmark.py +++ b/src/tests/e2e/benchmarks/chatqna/benchmark.py @@ -3,22 +3,30 @@ # SPDX-License-Identifier: Apache-2.0 import argparse +import asyncio import csv import json import logging +import math +import multiprocessing import os +import queue +import random import signal import sys import threading import time -import linecache -import random -from concurrent.futures import ThreadPoolExecutor -from functools import partial -from queue import Empty, Queue -import requests -import urllib3 -from transformers import AutoTokenizer + +import aiohttp + +USERS_PER_PROCESS = 16 +CONNECT_TIMEOUT_S = 10 +READ_TIMEOUT_S = 180 +RATE_LIMIT_SLEEP_S = 5 +BACKOFF_BASE_S = 0.5 +BACKOFF_MAX_S = 8.0 +SPAWN_HEADROOM_S = 5.0 +DRAIN_TIMEOUT_S = READ_TIMEOUT_S + 30 class QueryPool: def __init__(self, file_path, n_tokens, tokenizer): @@ -70,15 +78,6 @@ def get(self): self.next += 1 return question -class Result: - def __init__(self): - self.question_len = 0 - self.answer_len = 0 - self.first_chunk = 0 - self.overall = 0 - self.err = None - self.code = 0 - def parse_args(): parser = argparse.ArgumentParser(description="Load testing tool.") parser.add_argument("-f", type=str, help="Question File Location") @@ -91,147 +90,181 @@ def parse_args(): parser.add_argument("-b", type=str, default="uat.txt", help="Path to file with UAT") parser.add_argument("-x", type=int, default=0, help="Fix length of input query to X tokens (0 means no fixing)") parser.add_argument("-w", type=int, default=1, help="Warmup request per thread to skip") + parser.add_argument("-p", type=int, default=0, help=f"Load processes (0 means one per {USERS_PER_PROCESS} users)") + parser.add_argument("--ramp", type=str, default="2s", help="Spread worker starts over this time, on top of -u") return parser.parse_args() def duration_to_seconds(duration_str): units = {"s": 1, "m": 60, "h": 3600} return float(duration_str[:-1]) * units[duration_str[-1]] -def collect_results(stop_event, result_queue, output_file): - with open(output_file, "w", newline="") as csvfile: - writer = csv.writer(csvfile) - while not stop_event.is_set() or not result_queue.empty(): - try: - res = result_queue.get(timeout=0.1) - writer.writerow([res.question_len, res.answer_len, res.first_chunk, res.overall, res.err, res.code]) - csvfile.flush() - except Empty: - continue - -def worker(wid, ctx, server, pool, result_queue, delay, tokenizer, bearer_file, warmup_req): - time.sleep(delay) - iteration = 0 - bearer = linecache.getline(bearer_file, (wid + 1)).replace('\n','') - logging.info(f"[{wid}] worker started with {delay} delay") - if not bearer: - logging.error(f"[{wid}] no bearer, quitting") - return - - while not ctx.is_set(): - question = pool.get() - res = call_chatqna(server, question, wid, tokenizer, bearer) - if iteration >= warmup_req and res.answer_len != 1 and res.code == 200 and not res.err: - result_queue.put(res) - if res.answer_len != 1 and res.code == 200 and not res.err: - iteration = iteration + 1 - if ctx.is_set(): - break +def read_bearers(path, users): + with open(path) as f: + lines = [line.strip() for line in f] + return [lines[u] if u < len(lines) else "" for u in range(users)] -def call_chatqna(url, question, wid, tokenizer, bearer): - - headers = {"Content-Type": "application/json", "authorization": "Bearer " + bearer} - data = json.dumps({"text": question}) +def backoff_s(consecutive_failures): + return min(BACKOFF_BASE_S * 2 ** (consecutive_failures - 1), BACKOFF_MAX_S) * (0.5 + random.random()) - res = Result() - input_tokens = tokenizer.encode(question, add_special_tokens=False) - res.question_len = len(input_tokens) - - start = time.time() +async def call_chatqna(session, url, headers, body): + """One request on its own connection: (code, answer, first_chunk, overall, err).""" + chunks = [] + first_chunk = 0.0 + start = time.perf_counter() try: - with urllib3.warnings.catch_warnings(): - urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) - response = requests.post(url, headers=headers, data=data, - stream=True, verify=False, - timeout=(10, 180)) - res.code = response.status_code - answer = "" - lines = "" - if response.status_code == 200: - reader = response.iter_lines() - for line in reader: - lines = lines + line.decode("unicode_escape") + async with session.post(url, headers=headers, data=body) as response: + if response.status != 200: + await response.read() + return response.status, "", 0.0, time.perf_counter() - start, None + async for line in response.content: + line = line.rstrip(b"\r\n") if line == b"data: [DONE]": break if line.startswith(b"data: "): - line = line[6:].decode("utf-8") - line = json.loads(line)['choices'][0]['delta']['content'] - answer = answer + line - if res.first_chunk == 0: - res.first_chunk = time.time() - start - logging.debug(f"[{wid}] A: {line}") - res.overall = time.time() - start - output_tokens = tokenizer.encode(answer, add_special_tokens=False) - res.answer_len = len(output_tokens) - if res.answer_len == 1: - logging.error(f"[{wid}] unexpected output {lines}") - os.kill(os.getpid(), signal.SIGUSR1) - elif response.status_code == 429: - logging.error(f"[{wid}] hitting ratelimiter, sleeping for 5 seconds") - time.sleep(5) - else: - totaltime = time.time() - start - logging.error(f"[{wid}] unexpected response code {response.status_code} after {totaltime}") - os.kill(os.getpid(), signal.SIGUSR1) - except Exception as e: - res.err = str(e) - logging.error(f"[{wid}] exception {e}") - os.kill(os.getpid(), signal.SIGUSR1) - - return res - -def signal_handler(var, signal, frame): - var[0] = var[0] + 1 + chunks.append(json.loads(line[6:])["choices"][0]["delta"]["content"]) + if not first_chunk: + first_chunk = time.perf_counter() - start + return 200, "".join(chunks), first_chunk, time.perf_counter() - start, None + except (aiohttp.ClientError, asyncio.TimeoutError, OSError, ValueError, KeyError) as e: + return 0, "", first_chunk, time.perf_counter() - start, f"{type(e).__name__}: {e}" + +async def worker(wid, users, args, questions, bearer, results, stop, start_at): + if not bearer: + logging.error(f"[{wid}] no bearer, quitting") + return + await asyncio.sleep(max(0.0, start_at - time.monotonic())) + logging.info(f"[{wid}] worker started") + headers = {"Content-Type": "application/json", "authorization": "Bearer " + bearer} + timeout = aiohttp.ClientTimeout(sock_connect=CONNECT_TIMEOUT_S, sock_read=READ_TIMEOUT_S) + # force_close: every request opens its own TCP and TLS connection, as an independent user would. + connector = aiohttp.TCPConnector(force_close=True, ssl=False, limit=0) + failures = 0 + index = wid + async with aiohttp.ClientSession(connector=connector, timeout=timeout) as session: + while not stop.is_set(): + q = index % len(questions) + index += users + body = json.dumps({"text": questions[q]}) + code, answer, first_chunk, overall, err = await call_chatqna(session, args.s, headers, body) + results.put((wid, q, code, answer, first_chunk, overall, err)) + if code == 429: + logging.error(f"[{wid}] hitting ratelimiter, sleeping for {RATE_LIMIT_SLEEP_S} seconds") + await asyncio.sleep(RATE_LIMIT_SLEEP_S) + elif code != 200 or err: + failures += 1 + await asyncio.sleep(backoff_s(failures)) + else: + failures = 0 + +def run_workers(wids, users, args, questions, bearers, results, stop, start_at): + signal.signal(signal.SIGINT, signal.SIG_IGN) + ramp = duration_to_seconds(args.ramp) + delay = duration_to_seconds(args.u) + + async def run(): + await asyncio.gather(*( + worker(w, users, args, questions, bearers[w], results, stop, start_at + w * delay + ramp * w / users) + for w in wids + )) + + asyncio.run(run()) + +class Collector: + """Counts tokens and writes rows in the main process, off the request path.""" + + def __init__(self, writer, tokenizer, question_lens, warmup_req): + self.writer = writer + self.tokenizer = tokenizer + self.question_lens = question_lens + self.warmup_req = warmup_req + self.iterations = {} + self.failures = 0 + + def add(self, wid, q, code, answer, first_chunk, overall, err): + if code == 429: + return + answer_len = len(self.tokenizer.encode(answer, add_special_tokens=False)) if answer else 0 + if code != 200 or err or answer_len == 1: + self.failures += 1 + if err: + logging.error(f"[{wid}] exception {err}") + elif code != 200: + logging.error(f"[{wid}] unexpected response code {code} after {overall}") + else: + logging.error(f"[{wid}] unexpected output {answer!r}") + return + iteration = self.iterations.get(wid, 0) + self.iterations[wid] = iteration + 1 + if iteration >= self.warmup_req: + self.writer.writerow([self.question_lens[q], answer_len, first_chunk, overall, None, code]) def main(): args = parse_args() print(' \n'.join(f'{k}: {v}' for k, v in vars(args).items())) + # Imported here so the spawned load processes, which re-import this module, skip it. + from transformers import AutoTokenizer tokenizer = AutoTokenizer.from_pretrained(args.m) logging.basicConfig(stream=sys.stderr, level=logging.INFO) - stop_event = threading.Event() - signal.signal(signal.SIGINT, lambda s, f: stop_event.set()) + interrupted = threading.Event() + signal.signal(signal.SIGINT, lambda s, f: interrupted.set()) - pool = QueryPool(args.f, args.x, tokenizer) + questions = list(QueryPool(args.f, args.x, tokenizer).questions) + question_lens = [len(tokenizer.encode(q, add_special_tokens=False)) for q in questions] num_workers = args.c + bearers = read_bearers(args.b, num_workers) duration = duration_to_seconds(args.d) - delay_unit = duration_to_seconds(args.u) output_file = f"./bench_{time.strftime('%m%d-%H%M')}_c-{num_workers}_d-{args.u}.result.csv" - result_queue = Queue() - failures_allowed = args.e - failed_count = [0] - error = 0 - signal.signal(signal.SIGUSR1, partial(signal_handler, failed_count)) - - with ThreadPoolExecutor(max_workers=num_workers) as executor: - collector_thread = threading.Thread(target=collect_results, args=(stop_event, result_queue, output_file)) - collector_thread.start() - - start_time = time.time() - futures = [] - for i in range(num_workers): - delay = i * delay_unit - futures.append( - executor.submit( - worker, i, stop_event, args.s, pool, result_queue, delay, tokenizer, args.b, args.w - ) - ) - - while time.time() - start_time < duration and not stop_event.is_set(): - time.sleep(1) - if failed_count[0] > failures_allowed: - print(f"allowed failures {failed_count[0]} exceeded, quitting") - executor.shutdown(wait=False, cancel_futures=True) - error = 1 - break - - stop_event.set() - for future in futures: - future.result() + ctx = multiprocessing.get_context("spawn") + results = ctx.Queue() + stop = ctx.Event() + processes = min(args.p, num_workers) if args.p > 0 else max(1, min(math.ceil(num_workers / USERS_PER_PROCESS), os.cpu_count() or 1)) + start_at = time.monotonic() + SPAWN_HEADROOM_S + procs = [ + ctx.Process(target=run_workers, args=(list(range(p, num_workers, processes)), num_workers, args, + questions, bearers, results, stop, start_at), daemon=True) + for p in range(processes) + ] + logging.info(f"{num_workers} workers in {processes} processes") - collector_thread.join() - sys.exit(error) + error = 0 + try: + for proc in procs: + proc.start() + with open(output_file, "w", newline="") as csvfile: + collector = Collector(csv.writer(csvfile), tokenizer, question_lens, args.w) + deadline = start_at + duration + while time.monotonic() < deadline and not interrupted.is_set(): + try: + collector.add(*results.get(timeout=0.5)) + csvfile.flush() + except queue.Empty: + pass + if collector.failures > args.e: + print(f"allowed failures {collector.failures} exceeded, quitting") + error = 1 + break + stop.set() + drain_until = time.monotonic() + DRAIN_TIMEOUT_S + while any(proc.is_alive() for proc in procs) and time.monotonic() < drain_until: + try: + collector.add(*results.get(timeout=0.5)) + except queue.Empty: + pass + while True: + try: + collector.add(*results.get_nowait()) + except queue.Empty: + break + finally: + stop.set() + for proc in procs: + proc.join(timeout=5) + if proc.is_alive(): + proc.terminate() + sys.exit(error) if __name__ == "__main__": main() diff --git a/src/tests/e2e/benchmarks/chatqna/requirements.txt b/src/tests/e2e/benchmarks/chatqna/requirements.txt index 87441f89..8421e2d7 100644 --- a/src/tests/e2e/benchmarks/chatqna/requirements.txt +++ b/src/tests/e2e/benchmarks/chatqna/requirements.txt @@ -1,3 +1,4 @@ +aiohttp==3.14.5 requests==2.33.1 urllib3>=2.6.0 transformers[sentencepiece]==5.10.0 From 264fdfb158e81f492b191ce696ab4255b023327a Mon Sep 17 00:00:00 2001 From: "Kurzacz, Kamil" Date: Fri, 4 Dec 2026 14:06:32 +0100 Subject: [PATCH 2/4] docs(benchmarks): explain how -p splits benchmark.py users over processes Signed-off-by: Kurzacz, Kamil --- src/tests/e2e/benchmarks/chatqna/benchmark.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/tests/e2e/benchmarks/chatqna/benchmark.py b/src/tests/e2e/benchmarks/chatqna/benchmark.py index 34b53fb4..affbbc5c 100644 --- a/src/tests/e2e/benchmarks/chatqna/benchmark.py +++ b/src/tests/e2e/benchmarks/chatqna/benchmark.py @@ -90,7 +90,13 @@ def parse_args(): parser.add_argument("-b", type=str, default="uat.txt", help="Path to file with UAT") parser.add_argument("-x", type=int, default=0, help="Fix length of input query to X tokens (0 means no fixing)") parser.add_argument("-w", type=int, default=1, help="Warmup request per thread to skip") - parser.add_argument("-p", type=int, default=0, help=f"Load processes (0 means one per {USERS_PER_PROCESS} users)") + parser.add_argument("-p", type=int, default=0, + help="Number of processes to split the -c users across. Each process runs its share of " + "users as asyncio tasks, in parallel with the other processes, so users in different " + "processes never wait for each other's Python work. Users are dealt round-robin (-c 10 -p 3: 0,3,6,9 / " + f"1,4,7 / 2,5,8). 0 means one process per {USERS_PER_PROCESS} users, at most the " + "CPU count; a value above -c is capped at -c. It does not change what a user does: " + "each still sends one request at a time on a new connection") parser.add_argument("--ramp", type=str, default="2s", help="Spread worker starts over this time, on top of -u") return parser.parse_args() From a4d12e3b806132b80fb2bcb77b41ad2760592b8e Mon Sep 17 00:00:00 2001 From: Kamil Kurzacz Date: Fri, 4 Dec 2026 14:08:54 +0100 Subject: [PATCH 3/4] Update description --- src/tests/e2e/benchmarks/chatqna/benchmark.py | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/src/tests/e2e/benchmarks/chatqna/benchmark.py b/src/tests/e2e/benchmarks/chatqna/benchmark.py index affbbc5c..e3a6b513 100644 --- a/src/tests/e2e/benchmarks/chatqna/benchmark.py +++ b/src/tests/e2e/benchmarks/chatqna/benchmark.py @@ -90,13 +90,7 @@ def parse_args(): parser.add_argument("-b", type=str, default="uat.txt", help="Path to file with UAT") parser.add_argument("-x", type=int, default=0, help="Fix length of input query to X tokens (0 means no fixing)") parser.add_argument("-w", type=int, default=1, help="Warmup request per thread to skip") - parser.add_argument("-p", type=int, default=0, - help="Number of processes to split the -c users across. Each process runs its share of " - "users as asyncio tasks, in parallel with the other processes, so users in different " - "processes never wait for each other's Python work. Users are dealt round-robin (-c 10 -p 3: 0,3,6,9 / " - f"1,4,7 / 2,5,8). 0 means one process per {USERS_PER_PROCESS} users, at most the " - "CPU count; a value above -c is capped at -c. It does not change what a user does: " - "each still sends one request at a time on a new connection") + parser.add_argument("-p", type=int, default=0, help="Number of processes to split the -c users across. Use it to override default settings (0 means use USERS_PER_PROCESS const)") parser.add_argument("--ramp", type=str, default="2s", help="Spread worker starts over this time, on top of -u") return parser.parse_args() From 4392c946b399bf8e81c9c4314d561955f408145e Mon Sep 17 00:00:00 2001 From: "Kurzacz, Kamil" Date: Fri, 4 Dec 2026 14:25:07 +0100 Subject: [PATCH 4/4] fix(benchmarks): fail benchmark.py on missing tokens and honour proxy settings benchmark.py now stops with exit code 1 before any load when the bearer file is missing or has fewer than -c tokens. Before, the workers without a token quit with a log line and the run went on with fewer users, still exiting 0 under a -c file name. The aiohttp session also reads HTTP(S)_PROXY and no_proxy, as requests did. Signed-off-by: Kurzacz, Kamil --- out.log | 2 ++ src/tests/e2e/benchmarks/chatqna/benchmark.py | 17 ++++++++++++----- 2 files changed, 14 insertions(+), 5 deletions(-) create mode 100644 out.log diff --git a/out.log b/out.log new file mode 100644 index 00000000..20aea0c7 --- /dev/null +++ b/out.log @@ -0,0 +1,2 @@ +exit=0 +exit=0 diff --git a/src/tests/e2e/benchmarks/chatqna/benchmark.py b/src/tests/e2e/benchmarks/chatqna/benchmark.py index e3a6b513..b689d939 100644 --- a/src/tests/e2e/benchmarks/chatqna/benchmark.py +++ b/src/tests/e2e/benchmarks/chatqna/benchmark.py @@ -129,9 +129,6 @@ async def call_chatqna(session, url, headers, body): return 0, "", first_chunk, time.perf_counter() - start, f"{type(e).__name__}: {e}" async def worker(wid, users, args, questions, bearer, results, stop, start_at): - if not bearer: - logging.error(f"[{wid}] no bearer, quitting") - return await asyncio.sleep(max(0.0, start_at - time.monotonic())) logging.info(f"[{wid}] worker started") headers = {"Content-Type": "application/json", "authorization": "Bearer " + bearer} @@ -140,7 +137,8 @@ async def worker(wid, users, args, questions, bearer, results, stop, start_at): connector = aiohttp.TCPConnector(force_close=True, ssl=False, limit=0) failures = 0 index = wid - async with aiohttp.ClientSession(connector=connector, timeout=timeout) as session: + # trust_env: honour HTTP(S)_PROXY / no_proxy like requests does. + async with aiohttp.ClientSession(connector=connector, timeout=timeout, trust_env=True) as session: while not stop.is_set(): q = index % len(questions) index += users @@ -213,7 +211,16 @@ def main(): questions = list(QueryPool(args.f, args.x, tokenizer).questions) question_lens = [len(tokenizer.encode(q, add_special_tokens=False)) for q in questions] num_workers = args.c - bearers = read_bearers(args.b, num_workers) + try: + bearers = read_bearers(args.b, num_workers) + except OSError as e: + logging.error(f"cannot read the bearer file {args.b}: {e}") + sys.exit(1) + missing = [w for w, bearer in enumerate(bearers) if not bearer] + if missing: + logging.error(f"{args.b} has a bearer for {num_workers - len(missing)} of {num_workers} workers " + f"(one per line, missing from line {missing[0] + 1}); generate at least -c tokens") + sys.exit(1) duration = duration_to_seconds(args.d) output_file = f"./bench_{time.strftime('%m%d-%H%M')}_c-{num_workers}_d-{args.u}.result.csv"