mirror of
https://github.com/BerriAI/litellm.git
synced 2026-11-25 22:20:43 +00:00
* test(unit): reset module state only when a test changed it The proxy conftest deep-copied every snapshotted litellm attribute before each test, and the copy of litellm.model_cost alone was a median 0.12 s for each of 56,031 proxy tests on the runner. The reset now copies an attribute back only when it no longer equals the snapshot. The enterprise and MCP server conftests reloaded litellm before every test, 3.27 s and 0.21 s per test. They now use the same reset. * test(unit): remove six flaky tests They failed on main without a code change behind them between 2026-11-05 and 2026-11-14: the vector store hook SDK fallback, the concurrent user config TPM count, three Prometheus metrics server port tests and the OpenCode list cost billing test. * ci: run four heavy unit shards on 16-core runners and keep two smoke jobs off pull requests proxy-feature-endpoints, proxy-endpoints, root and llms-providers ran 1.9 to 2.2 times faster with 8 workers on a 16-core runner in a benchmark run. windows-sdk and proxy-build-from-pip still run on pushes to main and manual runs. proxy-build-from-pip installs a published release and never runs the pull request's code. * test: move 109 tests that start a process or open a socket into tests/integration tests/unit is in-process by its own rules, and these tests spawn a Python interpreter, a shell or a local TCP or HTTP server. They took 921 s of unit shard time per run, 396 s of it in the MCP client transport tests. Each one now lives in a *_real_io.py file under the integration directory for its domain and runs with that directory's group. The tests themselves are unchanged apart from one repository-root path in the CLI test. * test(unit): copy back only the dict entries a test changed A test module that registers models at import leaves litellm.model_cost four entries larger than the snapshot before every test in its directory, so the reset still deep-copied the whole price map for each of them. It now rebuilds a changed dict from the live entries that still match and copies only the rest. * ci(smoke): keep the two jobs that skip on pull requests out of the smoke gate A skipped job passing the gate is what test_unit_passed_gate guards against, so the gate goes back to requiring success from every job it needs and windows-sdk and proxy-build-from-pip stop being part of it. They still run and report on pushes to main and manual runs.
213 lines
7.4 KiB
Python
213 lines
7.4 KiB
Python
"""The separate metrics server must aggregate PROMETHEUS_MULTIPROC_DIR, expose /metrics plus a probe-friendly
|
|
/health, and follow its parent's lifetime.
|
|
|
|
Everything here runs on loopback against a child of this test process; no LLM keys or external network.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
import socket
|
|
import subprocess
|
|
import sys
|
|
import threading
|
|
import time
|
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
from pathlib import Path
|
|
from typing import Final
|
|
from unittest.mock import patch
|
|
|
|
import httpx
|
|
import pytest
|
|
from fastapi.testclient import TestClient
|
|
from prometheus_client import values
|
|
|
|
from litellm.proxy.prometheus_metrics_server import (
|
|
PID_HEADER,
|
|
MetricsServerStartupError,
|
|
build_metrics_app,
|
|
main,
|
|
metrics_url,
|
|
start_metrics_server_process,
|
|
)
|
|
|
|
_STARTUP_TIMEOUT_SECONDS: Final = 60.0
|
|
_SHUTDOWN_TIMEOUT_SECONDS: Final = 15.0
|
|
|
|
|
|
def _write_worker_sample(pid: int, value: float) -> None:
|
|
"""Write one counter sample into PROMETHEUS_MULTIPROC_DIR the way a proxy worker would."""
|
|
counter: Final = values.MultiProcessValue(process_identifier=lambda: pid)(
|
|
"counter",
|
|
"litellm_requests_metric_total",
|
|
"litellm_requests_metric_total",
|
|
("model",),
|
|
("gpt-5",),
|
|
"Total number of LLM calls",
|
|
)
|
|
counter.inc(value)
|
|
|
|
|
|
def _free_port() -> int:
|
|
with socket.socket() as sock:
|
|
sock.bind(("127.0.0.1", 0))
|
|
return sock.getsockname()[1]
|
|
|
|
|
|
def _wait_for_metrics(port: int, pid: int) -> httpx.Response:
|
|
deadline: Final = time.monotonic() + _STARTUP_TIMEOUT_SECONDS
|
|
while time.monotonic() < deadline:
|
|
try:
|
|
response: Final = httpx.get(f"http://127.0.0.1:{port}/metrics", follow_redirects=True, timeout=1.0)
|
|
if response.status_code == 200 and response.headers.get(PID_HEADER) == str(pid):
|
|
return response
|
|
except httpx.TransportError:
|
|
pass
|
|
time.sleep(0.2)
|
|
raise AssertionError(f"metrics server on port {port} never served metrics")
|
|
|
|
|
|
def _wait_until_down(port: int) -> None:
|
|
deadline: Final = time.monotonic() + _SHUTDOWN_TIMEOUT_SECONDS
|
|
while time.monotonic() < deadline:
|
|
try:
|
|
httpx.get(f"http://127.0.0.1:{port}/metrics", timeout=1.0)
|
|
except httpx.TransportError:
|
|
return
|
|
time.sleep(0.2)
|
|
raise AssertionError(f"metrics server on port {port} kept running after its parent died")
|
|
|
|
|
|
def test_metrics_app_aggregates_multiproc_dir_and_reports_pid(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
|
|
monkeypatch.setenv("PROMETHEUS_MULTIPROC_DIR", str(tmp_path))
|
|
_write_worker_sample(pid=1001, value=2)
|
|
_write_worker_sample(pid=1002, value=3)
|
|
other_dir: Final = tmp_path / "other"
|
|
other_dir.mkdir()
|
|
|
|
client: Final = TestClient(build_metrics_app(str(tmp_path)))
|
|
metrics: Final = client.get("/metrics")
|
|
assert metrics.status_code == 200
|
|
assert metrics.headers[PID_HEADER] == str(os.getpid())
|
|
assert 'litellm_requests_metric_total{model="gpt-5"} 5.0' in metrics.text
|
|
|
|
health: Final = client.get("/health")
|
|
assert health.status_code == 200
|
|
assert health.json() == {"status": "healthy", "multiproc_dir": str(tmp_path)}
|
|
assert client.get("/docs").status_code == 404
|
|
|
|
empty: Final = TestClient(build_metrics_app(str(other_dir))).get("/metrics")
|
|
assert empty.status_code == 200
|
|
assert "litellm_requests_metric_total" not in empty.text
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("host", "expected"),
|
|
(
|
|
("0.0.0.0", "http://127.0.0.1:4001/metrics"),
|
|
("::", "http://[::1]:4001/metrics"),
|
|
("10.1.2.3", "http://10.1.2.3:4001/metrics"),
|
|
("metrics.internal", "http://metrics.internal:4001/metrics"),
|
|
),
|
|
)
|
|
def test_metrics_url_probes_loopback_for_wildcard_binds(host: str, expected: str):
|
|
assert metrics_url(host, 4001) == expected
|
|
|
|
|
|
def test_main_serves_the_app_for_the_given_dir_with_uvicorn(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
|
|
monkeypatch.setenv("PROMETHEUS_MULTIPROC_DIR", str(tmp_path))
|
|
_write_worker_sample(pid=2001, value=6)
|
|
with patch("uvicorn.run") as run:
|
|
main(["--host", "10.1.2.3", "--port", "4001", "--multiproc_dir", str(tmp_path)])
|
|
|
|
run.assert_called_once()
|
|
assert run.call_args.kwargs["host"] == "10.1.2.3"
|
|
assert run.call_args.kwargs["port"] == 4001
|
|
client: Final = TestClient(run.call_args.args[0])
|
|
metrics: Final = client.get("/metrics")
|
|
assert metrics.status_code == 200
|
|
assert metrics.headers[PID_HEADER] == str(os.getpid())
|
|
assert 'litellm_requests_metric_total{model="gpt-5"} 6.0' in client.get("/metrics").text
|
|
|
|
|
|
def test_main_falls_back_to_env_multiproc_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
|
|
monkeypatch.setenv("PROMETHEUS_MULTIPROC_DIR", str(tmp_path))
|
|
with patch("uvicorn.run") as run:
|
|
main(["--port", "4001"])
|
|
|
|
(app,), served_on = run.call_args
|
|
assert served_on["host"] == "0.0.0.0"
|
|
metrics: Final = TestClient(app).get("/metrics")
|
|
assert metrics.status_code == 200
|
|
assert metrics.headers[PID_HEADER] == str(os.getpid())
|
|
|
|
|
|
def test_main_rejects_missing_multiproc_dir(monkeypatch: pytest.MonkeyPatch):
|
|
monkeypatch.delenv("PROMETHEUS_MULTIPROC_DIR", raising=False)
|
|
with patch("uvicorn.run") as run, pytest.raises(SystemExit) as exit_info:
|
|
main(["--port", "4001"])
|
|
|
|
assert exit_info.value.code == 2
|
|
run.assert_not_called()
|
|
|
|
|
|
class _ImpostorMetrics(BaseHTTPRequestHandler):
|
|
"""An unrelated service already on the port that answers /metrics with 200 and plausible metrics."""
|
|
|
|
def do_GET(self) -> None:
|
|
body: Final = b"# HELP impostor_metric A plausible metric\n# TYPE impostor_metric counter\nimpostor_metric 1\n"
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", "text/plain")
|
|
self.end_headers()
|
|
self.wfile.write(body)
|
|
|
|
def log_message(self, format: str, *args: object) -> None:
|
|
return
|
|
|
|
|
|
def test_metrics_server_process_serves_and_exits_with_parent(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
|
|
monkeypatch.setenv("PROMETHEUS_MULTIPROC_DIR", str(tmp_path))
|
|
_write_worker_sample(pid=2001, value=7)
|
|
port: Final = _free_port()
|
|
server_argv: Final = (
|
|
sys.executable,
|
|
"-m",
|
|
"litellm.proxy.prometheus_metrics_server",
|
|
"--host",
|
|
"127.0.0.1",
|
|
"--port",
|
|
str(port),
|
|
"--multiproc_dir",
|
|
str(tmp_path),
|
|
)
|
|
parent: Final = subprocess.Popen(
|
|
(
|
|
sys.executable,
|
|
"-c",
|
|
"import subprocess, sys, time; p = subprocess.Popen(sys.argv[1:]); print(p.pid, flush=True); time.sleep(600)",
|
|
*server_argv,
|
|
),
|
|
stdout=subprocess.PIPE,
|
|
text=True,
|
|
)
|
|
assert parent.stdout is not None
|
|
server_pid: Final = int(parent.stdout.readline())
|
|
try:
|
|
metrics: Final = _wait_for_metrics(port, server_pid)
|
|
assert metrics.status_code == 200
|
|
assert metrics.headers[PID_HEADER] == str(server_pid)
|
|
|
|
scrape: Final = httpx.get(f"http://127.0.0.1:{port}/metrics", follow_redirects=True, timeout=10.0)
|
|
assert scrape.status_code == 200
|
|
assert scrape.headers[PID_HEADER] == str(server_pid)
|
|
assert 'litellm_requests_metric_total{model="gpt-5"} 7.0' in scrape.text
|
|
|
|
parent.kill()
|
|
parent.wait(timeout=10)
|
|
_wait_until_down(port)
|
|
finally:
|
|
parent.kill()
|
|
try:
|
|
os.kill(server_pid, 9)
|
|
except ProcessLookupError:
|
|
pass
|