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): perf users start staggered with jitter, tool-call streams get a first token, small_bodies_5rps sends from the mixed case's callers (#46776)
Kerry Lu5fd6379a7826
diff --git a/tests/e2e/perf/cases/small_bodies_5rps.py b/tests/e2e/perf/cases/small_bodies_5rps.pyindex e118e453396..52fe41623e3 100644--- a/tests/e2e/perf/cases/small_bodies_5rps.py+++ b/tests/e2e/perf/cases/small_bodies_5rps.py@@ -1,20 +1,23 @@-"""Small bodies at a low rate on the small gateway: the shape of github issue #46276 (short chat-requests, master key and virtual keys, no JWT, no guardrails) at 5 rps on one 4-worker pod, far-under what the pod sustains, so nothing queues and gateway_added_seconds is the gateway's own-per-request overhead. A slower middleware chain or an extra Redis round trip per request shows up-directly instead of hiding behind queue wait."""+"""Small bodies at a low rate on the small gateway: the request sizes of github issue #46276 (short+chat requests, half streamed) from the same callers as the mixed case (two teams, JWT users in and+out of a team, virtual keys, the pre and post guardrail) at 5 rps on one 4-worker pod, far under+what the pod sustains, so nothing queues and gateway_added_seconds is the gateway's own per-request+overhead. A slower middleware chain or an extra Redis round trip per request shows up directly+instead of hiding behind queue wait."""from __future__ import annotationsfrom typing import Finalfrom setup.performance_test_case import (+ Guardrail,Limit,MockLatency,PerformanceTestCase,RequestShape,Team,Traffic,+ User,VirtualKey,)@@ -22,16 +25,32 @@ TINY: Final = RequestShape("tiny", input_tokens=(2_500, 4_000))CASE: Final = PerformanceTestCase(name="small_bodies_5rps",- teams=(Team("team-a", models=("gpt-6-luna", "claude-sonnet-5", "claude-sonnet-5-bedrock")),),- users=(),+ teams=(+ Team("team-a", models=("gpt-6-luna", "claude-sonnet-5"), max_budget=5000.0, rpm_limit=6000),+ Team("team-b", models=("claude-sonnet-5-bedrock", "claude-sonnet-5"), max_budget=5000.0),+ ),+ users=(+ User("alice", team="team-a"),+ User("bob", team="team-a"),+ User("carol", team="team-a"),+ User("dave", team="team-b"),+ User("erin", team="team-b"),+ User("frank", team="team-b"),+ User("grace"),+ User("heidi"),+ User("ivan"),+ User("judy", max_budget=1000.0),+ ),virtual_keys=(- VirtualKey("key-a1", team="team-a"),- VirtualKey("key-a2", team="team-a"),+ VirtualKey("key-a1", team="team-a", models=("gpt-6-luna",), rpm_limit=1200),+ VirtualKey("key-a2", team="team-a", user="alice"),+ VirtualKey("key-b1", team="team-b"),+ VirtualKey("key-b2", team="team-b", user="dave"),VirtualKey("key-plain"),),model_groups=("gpt-6-luna", "claude-sonnet-5", "claude-sonnet-5-bedrock"),mock_latency=MockLatency(seconds=1.0, jitter_seconds=0.25),- guardrails=(),+ guardrails=(Guardrail("perf-pre", mode="pre_call"), Guardrail("perf-post", mode="post_call")),traffic=Traffic(seed=11,rps=5.0,diff --git a/tests/e2e/perf/setup/locustfile.py b/tests/e2e/perf/setup/locustfile.pyindex fe8080959e5..1609617bd73 100644--- a/tests/e2e/perf/setup/locustfile.py+++ b/tests/e2e/perf/setup/locustfile.py@@ -10,13 +10,14 @@ line), paces to `PERF_RPS` over `PERF_USERS` users, and quits once the last requfrom __future__ import annotationsimport os+import randomimport timefrom collections.abc import Iteratorfrom pathlib import Pathfrom typing import Final, castimport gevent-from locust import FastHttpUser, constant_throughput, task+from locust import FastHttpUser, taskfrom locust.contrib.fasthttp import FastResponse, ResponseContextManagerfrom setup.wire import Endpoint, WireRecord, WireRequest, request_bodyfrom pydantic import TypeAdapter@@ -28,6 +29,9 @@ _RECORDS_PATH: Final = Path(os.environ["PERF_RECORDS_FILE"])_RPS: Final = float(os.environ["PERF_RPS"])_USERS: Final = int(os.environ["PERF_USERS"])_NEXT: Final[Iterator[WireRequest]] = iter(_PLAN)+_INTERVAL_S: Final = _USERS / _RPS+_JITTER: Final = 0.25+_RNG: Final = random.Random(_PLAN[0].marker if _PLAN else "empty-plan")_RECORDS: Final = _RECORDS_PATH.open("a", encoding="utf-8")_written = 0BLOCK_REASON: Final = "perf-test-block"@@ -84,6 +88,32 @@ def delta_of_event(endpoint: Endpoint, payload: dict[str, object]) -> str:return ""+_RESPONSES_TOKEN_EVENTS: Final = frozenset(+ {+ "response.output_text.delta",+ "response.refusal.delta",+ "response.reasoning_text.delta",+ "response.reasoning_summary_text.delta",+ "response.function_call_arguments.delta",+ }+)+++def token_in_event(endpoint: Endpoint, payload: dict[str, object]) -> bool:+ """Whether one SSE event carries a generated token of any kind: visible text, reasoning or tool-call arguments.+ The first such event is the stream's first token. `delta_of_event` stays visible text only because the body+ check compares it with the text the mock generated, and a tool-call reply has none."""+ if delta_of_event(endpoint, payload):+ return True+ if endpoint == "chat_completions":+ choices: Final = _as_list(payload.get("choices"))+ delta: Final = _as_dict(_as_dict(choices[0]).get("delta")) if choices else {}+ return any(delta.get(key) for key in ("reasoning_content", "reasoning", "tool_calls", "function_call"))+ if endpoint == "responses":+ return payload.get("type") in _RESPONSES_TOKEN_EVENTS+ return payload.get("type") == "content_block_delta"++def _events(buffer: bytes) -> tuple[list[dict[str, object]], bytes]:"""Complete SSE events in `buffer` as their JSON data, plus the unfinished tail."""events: list[dict[str, object]] = []@@ -169,12 +199,26 @@ def _authorization(user: FastHttpUser, item: WireRequest) -> str:class PlanUser(FastHttpUser):- """One simulated client; all users share the plan and together hold the planned rate."""+ """One simulated client; all users share the plan and together hold the planned rate. Each user starts at+ a random point of its first interval and jitters every later interval by up to `_JITTER` either way, so the+ users never fire in lockstep; the mean interval is unchanged and `rps` stays the total rate."""- wait_time = constant_throughput(_RPS / _USERS)network_timeout = 120.0connection_timeout = 30.0+ def on_start(self) -> None:+ self._last_run = 0.0+ self._last_wait = 0.0+ gevent.sleep(_RNG.uniform(0.0, _INTERVAL_S))++ def wait_time(self) -> float:+ target: Final = _INTERVAL_S * _RNG.uniform(1.0 - _JITTER, 1.0 + _JITTER)+ now: Final = time.monotonic()+ run_s: Final = now - self._last_run - self._last_wait if self._last_run else 0.0+ self._last_wait = max(0.0, target - run_s)+ self._last_run = now+ return self._last_wait+@taskdef send(self) -> None:item: Final = next(_NEXT, None)@@ -221,11 +265,9 @@ class PlanUser(FastHttpUser):buffer += lineevents, buffer = _events(buffer)for event in events:- delta = delta_of_event(item.endpoint, event)- if delta:- if first_token_s is None:- first_token_s = now- text += delta+ if first_token_s is None and token_in_event(item.endpoint, event):+ first_token_s = now+ text += delta_of_event(item.endpoint, event)else:body_text = context.text or ""first_byte_s = time.perf_counter() - started