litellm/tests/e2e/perf/setup/performance_test_case.py
Kerry Lu fbd078bcbe
test(e2e): perf rig (out-of-process mocks, PerformanceTestCase runner, per-request limits) and the small_bodies_5rps case (#46713)
* test(e2e): out-of-process mock OpenAI, Anthropic, Bedrock and guardrail servers for the perf cases

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test(e2e): coding-agent request corpus and real provider captures for the perf mocks

Request bodies come from a deterministic coding-agent session (system prompt, Read/Edit/Write/Bash/Grep/Glob tools, tool_use and tool_result turns carrying real source files picked by the request marker) in OpenAI chat, Responses and Anthropic formats. captures/ holds one real response per provider, route, shape and stream mode (gpt-6-luna, claude-sonnet-5, us.anthropic.claude-sonnet-5), cold prompt cache, body only, raw stream chunks with time offsets

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test(e2e): replay module for the perf mocks, captured provider responses picked by route, mode and request size

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test(e2e): perf mocks replay the captured provider responses, knobs shrink to flake and speed

The OpenAI, Anthropic and Bedrock mocks answer with the captured body or stream chunks for their route, mode and nearest request size, ids swapped per request, on the captured clock scaled by the p knob. The synthetic reply builders, the per-token stream pacing and the hand-rolled Bedrock event-stream encoder are gone

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test(e2e): perf mock request log names its provider

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test(e2e): perf guardrail mock remembers the request marker by call id for the response hook

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test(e2e): perf mock captures retaken cold, one marker and system-prompt prefix per cell

Run 2 shared one marker across cells, so every stream capture was served from the provider's prompt cache (cache_read_input_tokens up to 523946) and the json cells had small prefix hits. Every cell now carries its own marker, also prepended to the system prompt, and all 30 captures report zero cached tokens

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test(e2e): perf corpus reads tests/e2e files so the lane's runner image has them

* test(e2e): perf long_context json captures for Claude retaken with a 16k output cap, no longer cut mid-thinking

* test(e2e): perf mocks keep only what the replay path and the test read

* test(e2e): perf mocks interpolate the provider's time to first byte from the captures around the request size

* test(e2e): perf captures at 100k (short) and 500k (long) tokens with tools, the fixed-size set removed

* test(e2e): PerformanceTestCase schema, deterministic request plan and wire records for the perf cases

RequestShape names a corpus session (input_tokens, tools, output_tokens) and wire.request_body builds it with setup/corpus/session.py, so a 300k request is 85 file reads of real source in the endpoint's own format. The plan no longer predicts reply text, the mocks replay captured provider responses and the runner joins what the client saw against the mock's log by marker

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test(e2e): perf Metric gains time_to_first_token_seconds

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test(e2e): perf User loses the unused role field, every JWT user is an internal_user

* test(e2e): perf RequestShape sizes requests from an input-token range, short and long stock shapes

* test(e2e): perf case runner (provision, Locust plan replay, observe) and the 50 rps mixed-provider case

provision.py checks the deployed config against the case and builds the callers, run.py replays the plan from a separate Locust process (locustfile.py) recording status, header, first-byte, first-token and total time per request, observe.py joins the records with what the mocks received and the workers' RSS to score every Limit, and compares each served body with the capture the mock replayed for it as a diagnostic. The case sends 15,000 requests at 50 rps over three model groups, two guardrails and the three request shapes

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test(e2e): perf case asserts time_to_first_token_seconds at percentile 50 and 99

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test(e2e): perf provision creates every JWT user as internal_user

* test(e2e): perf observe reads only the mock log fields that remain

* test(e2e): 50 rps case sends short and long coding-agent sessions sized per request

* test(e2e): perf run keeps the per-request records as perf-records.jsonl under E2E_ARTIFACT_DIR

* test(e2e): the mixed small-gateway case runs at 25 rps (50 saturated one 4-worker pod on main and on v1.105.1)

* test(e2e): small_bodies_high_rate perf case, the github issue 46276 shape (11 to 17 KB chat bodies, keys only, 200 rps)

* test(e2e): the mixed small-gateway case runs at 10 rps for 6,000 requests (25 rps still saturated one pod on v1.105.1)

* ci: python lint job gets 20 minutes, the e2e harness phase (625 tests plus the replay harness suite) pushes a run past 15 when tests/e2e changes

* test(e2e): small-bodies perf case runs at 5 rps so gateway_added_seconds is per-request overhead, not queue wait

* test(e2e): mixed-provider perf case runs at 5 rps x 3,000 requests from 100 users

* test(e2e): mixed-provider perf case sends happy-path traffic only (no flaky deployment, no guardrail interventions or blocks)

* test(e2e): perf gateway model_list is three happy-path deployments, one per provider

* test(e2e): Postgres and Redis work per request as perf case limits

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test(e2e): perf mocks wait a case-level latency with jitter instead of replaying captured timings, cpu_seconds_per_request limit from metrics-server

* test(e2e): perf suite PR carries the small_bodies_5rps case only, the mixed-provider case moves to its own PR

* test(e2e): small_bodies_5rps limits from the ten v1.105.1 baselines (1.5x on datastore counts, 2x on latency and cpu, absolute on errors and memory)

* test(e2e): perf mocks keep only the short captures the small case reads, captured timings and the Bedrock invoke route removed

* test(e2e): perf mocks generate each reply from the request (provider schema, usage, ids, event order, chunk sizes) instead of replaying captures

---------

Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-15 20:14:40 +00:00

191 lines
7.8 KiB
Python

"""The schema of a perf test: a `PerformanceTestCase` names what the gateway is deployed with
(model groups and guardrails, both written out in the gateway's config) and lists what the test
itself creates and sends: teams, Keycloak users, virtual keys, the request shapes, the traffic plan
and the `Limit`s that decide pass or fail. Add a case by adding a module to `cases/`.
The same shape as `CostTrackingTestCase` in the cost suite: frozen dataclasses with plain defaults,
so a case is a literal a reviewer can read top to bottom.
"""
from __future__ import annotations
from collections.abc import Mapping
from dataclasses import dataclass, field
from typing import Final, Literal
Endpoint = Literal["chat_completions", "responses", "messages"]
MockProvider = Literal["openai", "anthropic", "bedrock"]
GuardrailMode = Literal["pre_call", "post_call"]
Metric = Literal[
"unexpected_status_count",
"gateway_added_seconds",
"time_to_first_token_seconds",
"memory_growth_megabytes",
"postgres_calls_per_request",
"cpu_seconds_per_request",
"redis_calls_per_request",
]
@dataclass(frozen=True, slots=True)
class Team:
"""One team (`/team/new`). `models` names the model groups the team may call; empty means all."""
name: str
models: tuple[str, ...] = ()
max_budget: float | None = None
rpm_limit: int | None = None
tpm_limit: int | None = None
@dataclass(frozen=True, slots=True)
class User:
"""One Keycloak user who calls the gateway with a JWT. `team` puts them in that team's group."""
name: str
team: str | None = None
max_budget: float | None = None
@dataclass(frozen=True, slots=True)
class VirtualKey:
"""One virtual key (`/key/generate`), scoped to a team and/or a user when named."""
name: str
team: str | None = None
user: str | None = None
models: tuple[str, ...] = ()
rpm_limit: int | None = None
max_budget: float | None = None
@dataclass(frozen=True, slots=True)
class Guardrail:
"""A guardrail the gateway's config defines (a `generic_guardrail_api` pointed at the mock
guardrail, `default_on`); the case names it so the plan knows which hooks every request sees."""
name: str
mode: GuardrailMode
@dataclass(frozen=True, slots=True)
class RequestShape:
"""What one request looks like: a coding-agent session (`setup/corpus/session.py`, the system prompt, the
Read/Edit/Write/Bash/Grep/Glob tools when `tools` is set, then file-reading turns carrying real source files)
whose size in input tokens is drawn per request from the `input_tokens` range, and the output cap. The mocks
answer with a reply generated for the request, sized from that cap, a tool call when `tools` is set."""
name: str
input_tokens: tuple[int, int]
tools: bool = False
output_tokens: int = 1_024
SHORT: Final = RequestShape("short", input_tokens=(5_000, 100_000), tools=True)
LONG: Final = RequestShape("long", input_tokens=(300_000, 1_000_000), tools=True)
@dataclass(frozen=True, slots=True)
class Traffic:
"""The plan: `total_requests` drawn from `seed`, sent at `rps` by `concurrency` simulated
users. Shares are fractions of the requests: `endpoints` and `shapes` must each sum to 1,
`intervene_share` picks non-streaming requests the guardrail rewrites, `block_share` picks
requests it blocks."""
seed: int
rps: float
total_requests: int
endpoints: Mapping[Endpoint, float] = field(default_factory=lambda: {"chat_completions": 1.0})
shapes: Mapping[RequestShape, float] = field(default_factory=lambda: {SHORT: 1.0})
stream_share: float = 0.0
intervene_share: float = 0.0
block_share: float = 0.0
concurrency: int = 20
@property
def expected_seconds(self) -> float:
return self.total_requests / self.rps
@dataclass(frozen=True, slots=True)
class Limit:
"""One pass/fail rule: `metric` (at `percentile`, or the whole-run value) must not exceed `max`.
Metrics without a Limit are still reported."""
metric: Metric
max: float
percentile: int | None = None
@property
def label(self) -> str:
return f"{self.metric} percentile {self.percentile}" if self.percentile is not None else self.metric
@dataclass(frozen=True, slots=True)
class MockLatency:
"""Seconds a mock provider waits before its first byte, plus or minus up to `jitter_seconds` per request
(drawn from the request marker, so a rerun waits the same). Zero means the mocks answer at once."""
seconds: float = 0.0
jitter_seconds: float = 0.0
@dataclass(frozen=True, slots=True)
class PerformanceTestCase:
"""`model_groups` and `guardrails` name what the gateway config deploys (setup checks they are
there); everything else the test creates or sends. `mock_latency` is how long every mock provider waits
before answering, set on the mock pods at setup, so the provider side of each request is a known
constant and the rest of the client's time is the gateway's."""
name: str
teams: tuple[Team, ...]
users: tuple[User, ...]
virtual_keys: tuple[VirtualKey, ...]
model_groups: tuple[str, ...]
guardrails: tuple[Guardrail, ...]
traffic: Traffic
limits: tuple[Limit, ...]
mock_latency: MockLatency = field(default_factory=lambda: MockLatency())
def team(self, name: str) -> Team:
return next(team for team in self.teams if team.name == name)
@property
def has_post_guardrail(self) -> bool:
return any(guardrail.mode == "post_call" for guardrail in self.guardrails)
def validate(self) -> None:
"""Fail fast on a case that cannot run: dangling names, shares that do not add up, a model
group no caller may use."""
team_names: Final = {team.name for team in self.teams}
user_names: Final = {user.name for user in self.users}
group_names: Final = set(self.model_groups)
for names, label in (
([team.name for team in self.teams], "team"),
([user.name for user in self.users], "user"),
([key.name for key in self.virtual_keys], "key"),
(list(self.model_groups), "model group"),
([guardrail.name for guardrail in self.guardrails], "guardrail"),
):
assert len(names) == len(set(names)), f"{self.name}: duplicate {label} names in {names}"
for team in self.teams:
assert set(team.models) <= group_names, f"{self.name}: team {team.name} names unknown models {team.models}"
for user in self.users:
assert user.team is None or user.team in team_names, (
f"{self.name}: user {user.name} in unknown team {user.team}"
)
for key in self.virtual_keys:
assert key.team is None or key.team in team_names, f"{self.name}: key {key.name} in unknown team {key.team}"
assert key.user is None or key.user in user_names, (
f"{self.name}: key {key.name} for unknown user {key.user}"
)
assert set(key.models) <= group_names, f"{self.name}: key {key.name} names unknown models {key.models}"
assert abs(sum(self.traffic.endpoints.values()) - 1.0) < 1e-9, f"{self.name}: endpoint shares must sum to 1"
assert abs(sum(self.traffic.shapes.values()) - 1.0) < 1e-9, f"{self.name}: shape shares must sum to 1"
assert 0 <= self.traffic.stream_share <= 1, f"{self.name}: stream_share out of range"
assert self.traffic.intervene_share + self.traffic.block_share <= 1, f"{self.name}: guardrail shares exceed 1"
assert self.traffic.total_requests > 0 and self.traffic.rps > 0, f"{self.name}: empty traffic"
assert self.model_groups, f"{self.name}: no model groups"
assert 0 <= self.mock_latency.jitter_seconds <= self.mock_latency.seconds or self.mock_latency.seconds == 0, (
f"{self.name}: mock latency jitter {self.mock_latency.jitter_seconds} s exceeds {self.mock_latency.seconds} s"
)