The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
test(e2e): derive the throughput SLO per replica and surface locust's error breakdown (#35494)
Yassin Kortam3d35eee5601a
diff --git a/tests/e2e/e2e_config.py b/tests/e2e/e2e_config.pyindex e62b866f0a9..34770bc596b 100644--- a/tests/e2e/e2e_config.py+++ b/tests/e2e/e2e_config.py@@ -80,15 +80,23 @@ EXPECT_RUST = os.environ.get("E2E_EXPECT_RUST", "").strip().lower() in ("1", "tr# Deliberately modest concurrency. The suite shares its proxy with every other# suite in the run, and 750 users at spawn rate 50 saturated the request path hard# enough to distort latency-sensitive neighbours (and to spend real provider money-# fast). The SLO is scaled with the user count to keep the same per-user throughput-# expectation (~0.47 RPS/user), so this still catches a request-path regression-# rather than becoming a formality. Raise all four via env for a real load run.+# fast).LOAD_USERS = int(os.environ.get("E2E_LOAD_USERS", "200"))LOAD_SPAWN_RATE = float(os.environ.get("E2E_LOAD_SPAWN_RATE", "20"))LOAD_DURATION_SECONDS = float(os.environ.get("E2E_LOAD_DURATION_SECONDS", "60"))-LOAD_MIN_RPS = float(os.environ.get("E2E_LOAD_MIN_RPS", "90"))LOAD_MAX_FAILURE_RATIO = float(os.environ.get("E2E_LOAD_MAX_FAILURE_RATIO", "0.01"))+# The throughput floor is derived per replica instead of being an absolute fleet+# number, so the verdict does not depend on how many replicas happen to be warm.+# One closed-loop user only ever occupies one replica at a time, so a short serial+# pass measures a single replica's request path: its throughput is 1/latency, and+# the concurrent phase then has to reach at least that much no matter how large+# the fleet is. An absolute floor instead asserted replicas x per-replica rate,+# which reactive autoscaling decides rather than the request path.+LOAD_BASELINE_SECONDS = float(os.environ.get("E2E_LOAD_BASELINE_SECONDS", "15"))+LOAD_MAX_SERIAL_LATENCY_SECONDS = float(os.environ.get("E2E_LOAD_MAX_SERIAL_LATENCY_SECONDS", "0.5"))+LOAD_MIN_CONCURRENCY_EFFICIENCY = float(os.environ.get("E2E_LOAD_MIN_CONCURRENCY_EFFICIENCY", "0.8"))+WEEKLY_ANOMALY_OPT_IN_ENV = "E2E_WEEKLY_ANOMALY"ANOMALY_SESSIONS = int(os.environ.get("E2E_ANOMALY_SESSIONS", "6"))ANOMALY_TURNS_PER_SESSION = int(os.environ.get("E2E_ANOMALY_TURNS_PER_SESSION", "6"))diff --git a/tests/e2e/load/locust_load.py b/tests/e2e/load/locust_load.pyindex 990e24ee064..fc1ed490186 100644--- a/tests/e2e/load/locust_load.py+++ b/tests/e2e/load/locust_load.py@@ -1,24 +1,38 @@from __future__ import annotations+import csvimport osimport subprocessimport sys+import tempfilefrom dataclasses import dataclass+from itertools import accumulatefrom pathlib import Pathfrom pydantic import BaseModel, TypeAdapter_LOCUSTFILE = Path(__file__).with_name("locustfile.py")+_CSV_PREFIX = "locust"+_GENERATOR_SATURATION_MARKER = "CPU usage above"+_MAX_REPORTED_ERRORS = 5-class _LocustStatEntry(BaseModel):+class LocustStatEntry(BaseModel):num_requests: intnum_failures: intstart_time: floatlast_request_timestamp: float+ response_times: dict[int, int]-_STATS_ADAPTER: TypeAdapter[list[_LocustStatEntry]] = TypeAdapter(list[_LocustStatEntry])+_STATS_ADAPTER: TypeAdapter[list[LocustStatEntry]] = TypeAdapter(list[LocustStatEntry])+++@dataclass(frozen=True, slots=True)+class LoadError:+ name: str+ error: str+ occurrences: int@dataclass(frozen=True, slots=True)@@ -26,20 +40,93 @@ class LoadResult:requests: intfailures: intrequests_per_second: float+ median_response_seconds: float+ errors: tuple[LoadError, ...]+ generator_warnings: tuple[str, ...]@propertydef failure_ratio(self) -> float:return self.failures / self.requests if self.requests else 1.0+ def diagnosis(self) -> str:+ """What the failed requests actually got, so a red run reads without log archaeology."""+ ranked = sorted(self.errors, key=lambda error: error.occurrences, reverse=True)+ lines = [f"{error.occurrences}x {error.name}: {error.error}" for error in ranked[:_MAX_REPORTED_ERRORS]]+ remainder = len(ranked) - len(lines)+ if remainder > 0:+ lines.append(f"and {remainder} more distinct errors")+ if not lines:+ lines.append("locust recorded no error breakdown")+ return "; ".join((*lines, *self.generator_warnings))+++def median_seconds(entries: list[LocustStatEntry]) -> float:+ samples = sorted(+ (milliseconds, count) for entry in entries for milliseconds, count in entry.response_times.items()+ )+ total = sum(count for _, count in samples)+ if total == 0:+ return 0.0+ running = accumulate(count for _, count in samples)+ return next(+ milliseconds for (milliseconds, _), seen in zip(samples, running) if seen >= total / 2+ ) / 1000.0+-def _aggregate(entries: list[_LocustStatEntry]) -> LoadResult:+def aggregate_stats(+ entries: list[LocustStatEntry],+ errors: tuple[LoadError, ...],+ generator_warnings: tuple[str, ...],+) -> LoadResult:requests = sum(entry.num_requests for entry in entries)failures = sum(entry.num_failures for entry in entries)if not entries or requests == 0:- return LoadResult(requests=requests, failures=failures, requests_per_second=0.0)+ return LoadResult(+ requests=requests,+ failures=failures,+ requests_per_second=0.0,+ median_response_seconds=0.0,+ errors=errors,+ generator_warnings=generator_warnings,+ )elapsed = max(entry.last_request_timestamp for entry in entries) - min(entry.start_time for entry in entries)- rps = requests / elapsed if elapsed > 0 else 0.0- return LoadResult(requests=requests, failures=failures, requests_per_second=rps)+ return LoadResult(+ requests=requests,+ failures=failures,+ requests_per_second=requests / elapsed if elapsed > 0 else 0.0,+ median_response_seconds=median_seconds(entries),+ errors=errors,+ generator_warnings=generator_warnings,+ )+++def read_errors(failures_csv: Path) -> tuple[LoadError, ...]:+ """Locust's per-error breakdown, which its --json summary omits entirely.++ Written on a one-second tick, so the final second of a run may be missing. That is fine+ for a diagnostic: the counts that decide the assertions come from the JSON summary.+ A run with no failures writes no rows, and locust omits the file altogether.+ """+ if not failures_csv.exists():+ return ()+ with failures_csv.open(newline="") as handle:+ return tuple(+ LoadError(name=row["Name"], error=row["Error"], occurrences=int(row["Occurrences"]))+ for row in csv.DictReader(handle)+ )+++def read_generator_warnings(stderr: str) -> tuple[str, ...]:+ """Locust reports its own CPU saturation on stderr; a saturated generator caps the measured rate.++ Kept from the marker onward so the per-line timestamp does not defeat the de-duplication.+ """+ saturated = (+ line[line.index(_GENERATOR_SATURATION_MARKER) :].strip()+ for line in stderr.splitlines()+ if _GENERATOR_SATURATION_MARKER in line+ )+ return tuple(dict.fromkeys(saturated))def run_chat_load(@@ -51,43 +138,51 @@ def run_chat_load(spawn_rate: float,duration_seconds: float,) -> LoadResult:- completed = subprocess.run(- [- sys.executable,- "-m",- "locust",- "--headless",- "--json",- "--locustfile",- str(_LOCUSTFILE),- "--host",- base_url,- "--users",- str(users),- "--spawn-rate",- str(spawn_rate),- "--run-time",- f"{int(duration_seconds)}s",- "--exit-code-on-error",- "0",- ],- env={**os.environ, "LOAD_API_KEY": api_key, "LOAD_MODEL": model},- capture_output=True,- text=True,- timeout=duration_seconds + 120,- check=False,- )- if completed.returncode != 0:- raise RuntimeError(- f"locust exited {completed.returncode} before it could report throughput "- f"(a startup failure, not request failures, which are folded into the JSON summary via "- f"--exit-code-on-error 0):\n{completed.stderr}"+ with tempfile.TemporaryDirectory(prefix="e2e-load-") as report_dir:+ csv_prefix = Path(report_dir) / _CSV_PREFIX+ completed = subprocess.run(+ [+ sys.executable,+ "-m",+ "locust",+ "--headless",+ "--json",+ "--csv",+ str(csv_prefix),+ "--locustfile",+ str(_LOCUSTFILE),+ "--host",+ base_url,+ "--users",+ str(users),+ "--spawn-rate",+ str(spawn_rate),+ "--run-time",+ f"{int(duration_seconds)}s",+ "--exit-code-on-error",+ "0",+ ],+ env={**os.environ, "LOAD_API_KEY": api_key, "LOAD_MODEL": model},+ capture_output=True,+ text=True,+ timeout=duration_seconds + 120,+ check=False,+ )+ if completed.returncode != 0:+ raise RuntimeError(+ f"locust exited {completed.returncode} before it could report throughput "+ f"(a startup failure, not request failures, which are folded into the JSON summary via "+ f"--exit-code-on-error 0):\n{completed.stderr}"+ )+ try:+ entries = _STATS_ADAPTER.validate_json(completed.stdout)+ except ValueError as exc:+ raise RuntimeError(+ f"locust exited 0 but did not print a parseable --json throughput summary on stdout; "+ f"got stdout={completed.stdout!r}, stderr={completed.stderr!r}"+ ) from exc+ return aggregate_stats(+ entries,+ read_errors(csv_prefix.with_name(f"{_CSV_PREFIX}_failures.csv")),+ read_generator_warnings(completed.stderr),)- try:- entries = _STATS_ADAPTER.validate_json(completed.stdout)- except ValueError as exc:- raise RuntimeError(- f"locust exited 0 but did not print a parseable --json throughput summary on stdout; "- f"got stdout={completed.stdout!r}, stderr={completed.stderr!r}"- ) from exc- return _aggregate(entries)diff --git a/tests/e2e/load/test_chat_completions_throughput_e2e.py b/tests/e2e/load/test_chat_completions_throughput_e2e.pyindex dd9ca370c6f..6cfa4f35914 100644--- a/tests/e2e/load/test_chat_completions_throughput_e2e.py+++ b/tests/e2e/load/test_chat_completions_throughput_e2e.py@@ -1,9 +1,11 @@import pytestfrom e2e_config import (+ LOAD_BASELINE_SECONDS,LOAD_DURATION_SECONDS,LOAD_MAX_FAILURE_RATIO,- LOAD_MIN_RPS,+ LOAD_MAX_SERIAL_LATENCY_SECONDS,+ LOAD_MIN_CONCURRENCY_EFFICIENCY,LOAD_SPAWN_RATE,LOAD_USERS,PROXY_BASE_URL,@@ -16,19 +18,37 @@ pytestmark = [pytest.mark.e2e, pytest.mark.load]class TestChatCompletionsThroughput:- @pytest.mark.skip(- reason=(- "LIT-5054: the SLO measures how many gateway replicas happen to be warm, not the "- "request path. Clearing the floor needs roughly 5-7 replicas at ~10-14 RPS each, "- "stage idles at one, and reactive HPA scale-up lands minutes into a ~3 minute "- "test. It has failed both assertions on consecutive days: 93.3% errors at an "- "inflated 264 RPS (closed-loop RPS rises when requests fail fast, and those "- "requests never reached a pod), then 16.7 RPS with zero failures. Unskip once the "- "assertion is independent of fleet size."- )- )@pytest.mark.covers("reliability.perf.throughput.under_slo")def test_sustains_throughput_slo_under_load(self, client: LoadClient, load_key: str) -> None:+ baseline = run_chat_load(+ base_url=PROXY_BASE_URL,+ api_key=load_key,+ model=LOAD_MODEL,+ users=1,+ spawn_rate=1,+ duration_seconds=LOAD_BASELINE_SECONDS,+ )++ assert baseline.requests > 0 and baseline.requests_per_second > 0, (+ f"no requests completed against {PROXY_BASE_URL} in the {LOAD_BASELINE_SECONDS}s serial "+ f"baseline; the load generator never drove traffic (proxy unreachable or model unservable). "+ f"{baseline.diagnosis()}"+ )+ assert baseline.failure_ratio <= LOAD_MAX_FAILURE_RATIO, (+ f"{baseline.failures}/{baseline.requests} requests failed in the serial baseline "+ f"({baseline.failure_ratio:.1%} > {LOAD_MAX_FAILURE_RATIO:.1%} allowed), so it calibrates "+ f"nothing: a request that fails in milliseconds reads as a fast one, passing the latency "+ f"budget and inflating the floor it derives. {baseline.diagnosis()}"+ )+ assert baseline.median_response_seconds <= LOAD_MAX_SERIAL_LATENCY_SECONDS, (+ f"one user with no competing load saw a median of {baseline.median_response_seconds * 1000:.0f}ms "+ f"per request, over the {LOAD_MAX_SERIAL_LATENCY_SECONDS * 1000:.0f}ms budget; the request path "+ f"itself is slow, before any concurrency. {baseline.diagnosis()}"+ )++ replica_rps = baseline.requests_per_second+ min_rps = replica_rps * LOAD_MIN_CONCURRENCY_EFFICIENCY+result = run_chat_load(base_url=PROXY_BASE_URL,api_key=load_key,@@ -40,14 +60,20 @@ class TestChatCompletionsThroughput:assert result.requests > 0, (f"no requests completed against {PROXY_BASE_URL} in {LOAD_DURATION_SECONDS}s; "- f"the load generator never drove traffic (proxy unreachable or model unservable)"+ f"the load generator never drove traffic (proxy unreachable or model unservable). "+ f"{result.diagnosis()}")assert result.failure_ratio <= LOAD_MAX_FAILURE_RATIO, (f"{result.failures}/{result.requests} requests failed "f"({result.failure_ratio:.1%} > {LOAD_MAX_FAILURE_RATIO:.1%} allowed); "- f"throughput of {result.requests_per_second:.1f} RPS is not a clean read under this error rate"+ f"throughput of {result.requests_per_second:.1f} RPS is not a clean read under this error rate, "+ f"since closed-loop throughput rises when requests fail fast. {result.diagnosis()}")- assert result.requests_per_second >= LOAD_MIN_RPS, (+ assert result.requests_per_second >= min_rps, (f"sustained {result.requests_per_second:.1f} RPS over {LOAD_DURATION_SECONDS}s with "- f"{LOAD_USERS} users, below the {LOAD_MIN_RPS} RPS SLO; the proxy request path regressed under load"+ f"{LOAD_USERS} users, below the {min_rps:.1f} RPS floor that one replica set on its own "+ f"({replica_rps:.1f} RPS serial at a {baseline.median_response_seconds * 1000:.0f}ms median, "+ f"x {LOAD_MIN_CONCURRENCY_EFFICIENCY:.0%}); concurrency made the request path slower per "+ f"request than a single user did, so the fleet is serialising rather than merely saturated. "+ f"{result.diagnosis()}")diff --git a/tests/e2e/load/test_locust_load.py b/tests/e2e/load/test_locust_load.pynew file mode 100644index 00000000000..e3cc6f3efd5--- /dev/null+++ b/tests/e2e/load/test_locust_load.py@@ -0,0 +1,163 @@+from __future__ import annotations++from pathlib import Path++from locust_load import (+ LoadError,+ LoadResult,+ LocustStatEntry,+ aggregate_stats,+ median_seconds,+ read_errors,+ read_generator_warnings,+)++_FAILURES_HEADER = "Method,Name,Error,Occurrences,First Seen,Last Seen\n"+++def _entry(+ *,+ num_requests: int,+ num_failures: int = 0,+ start_time: float = 1000.0,+ last_request_timestamp: float = 1010.0,+ response_times: dict[int, int] | None = None,+) -> LocustStatEntry:+ return LocustStatEntry(+ num_requests=num_requests,+ num_failures=num_failures,+ start_time=start_time,+ last_request_timestamp=last_request_timestamp,+ response_times=response_times if response_times is not None else {50: num_requests},+ )+++def _result(+ *,+ errors: tuple[LoadError, ...] = (),+ generator_warnings: tuple[str, ...] = (),+) -> LoadResult:+ return LoadResult(+ requests=10,+ failures=10,+ requests_per_second=1.0,+ median_response_seconds=0.05,+ errors=errors,+ generator_warnings=generator_warnings,+ )+++class TestSerialLatency:+ def test_median_is_the_middle_sample_not_the_mean_a_slow_tail_would_drag(self) -> None:+ # Nine fast requests and one very slow one: the mean is 1.99s, the median is 20ms.+ entry = _entry(num_requests=10, response_times={20: 9, 20000: 1})++ assert median_seconds([entry]) == 0.02++ def test_median_merges_the_histograms_of_every_stats_entry(self) -> None:+ # Per entry the median would be 10ms and 90ms; merged, the middle of the five samples is 90ms.+ entries = [+ _entry(num_requests=2, response_times={10: 2}),+ _entry(num_requests=3, response_times={90: 3}),+ ]++ assert median_seconds(entries) == 0.09++ def test_an_even_split_takes_the_lower_middle_sample_as_locust_itself_does(self) -> None:+ entry = _entry(num_requests=4, response_times={10: 2, 90: 2})++ assert median_seconds([entry]) == 0.01++ def test_no_samples_reports_zero_rather_than_dividing_by_an_empty_histogram(self) -> None:+ assert median_seconds([]) == 0.0+++class TestAggregate:+ def test_throughput_spans_the_whole_window_and_latency_comes_from_the_histogram(self) -> None:+ entry = _entry(+ num_requests=180,+ start_time=1000.0,+ last_request_timestamp=1060.0,+ response_times={57: 180},+ )++ result = aggregate_stats([entry], (), ())++ assert result.requests_per_second == 3.0+ assert result.median_response_seconds == 0.057+ assert result.failure_ratio == 0.0++ def test_throughput_spans_from_the_earliest_start_when_locust_reports_several_entries(self) -> None:+ entries = [+ _entry(num_requests=60, start_time=1000.0, last_request_timestamp=1030.0),+ _entry(num_requests=60, start_time=1020.0, last_request_timestamp=1060.0),+ ]++ result = aggregate_stats(entries, (), ())++ assert result.requests_per_second == 2.0++ def test_a_run_that_drove_no_traffic_reports_a_total_failure_ratio(self) -> None:+ result = aggregate_stats([], (), ())++ assert result.requests == 0+ assert result.requests_per_second == 0.0+ assert result.failure_ratio == 1.0+++class TestErrorBreakdown:+ def test_locust_failure_rows_become_the_error_breakdown(self, tmp_path: Path) -> None:+ failures_csv = tmp_path / "locust_failures.csv"+ failures_csv.write_text(+ _FAILURES_HEADER+ + 'POST,/chat/completions,"LocustBadStatusCode(code=401)",381,2026-07-30 12:42:01,2026-07-30 12:45:00\n'+ )++ assert read_errors(failures_csv) == (+ LoadError(name="/chat/completions", error="LocustBadStatusCode(code=401)", occurrences=381),+ )++ def test_a_run_with_no_failures_writes_no_csv_and_reports_no_errors(self, tmp_path: Path) -> None:+ assert read_errors(tmp_path / "locust_failures.csv") == ()++ def test_diagnosis_leads_with_the_most_common_error(self) -> None:+ result = _result(+ errors=(+ LoadError(name="/chat/completions", error="ConnectionRefused", occurrences=12),+ LoadError(name="/chat/completions", error="LocustBadStatusCode(code=503)", occurrences=43675),+ )+ )++ assert result.diagnosis().startswith("43675x /chat/completions: LocustBadStatusCode(code=503)")++ def test_diagnosis_caps_the_list_and_says_how_many_it_left_out(self) -> None:+ result = _result(+ errors=tuple(+ LoadError(name="/chat/completions", error=f"error-{index}", occurrences=index)+ for index in range(1, 9)+ )+ )++ assert result.diagnosis().count("x /chat/completions") == 5+ assert "and 3 more distinct errors" in result.diagnosis()++ def test_diagnosis_says_so_when_locust_recorded_nothing(self) -> None:+ assert _result().diagnosis() == "locust recorded no error breakdown"+++class TestGeneratorSaturation:+ def test_repeated_cpu_warnings_collapse_to_one_and_reach_the_diagnosis(self) -> None:+ stderr = (+ "[2026-07-31 12:47:01] WARNING/locust.runners: CPU usage above 90%!\n"+ "[2026-07-31 12:47:02] INFO/locust.main: Run time limit reached\n"+ "[2026-07-31 12:47:03] WARNING/locust.runners: CPU usage above 90%!\n"+ )++ warnings = read_generator_warnings(stderr)++ assert len(warnings) == 1+ assert "CPU usage above 90%!" in warnings[0]+ assert "CPU usage above 90%!" in _result(generator_warnings=warnings).diagnosis()++ def test_ordinary_locust_chatter_is_not_reported_as_a_warning(self) -> None:+ assert read_generator_warnings("[2026-07-31] INFO/locust.main: Shutting down (exit code 0)\n") == ()