mirror of
https://github.com/BerriAI/litellm.git
synced 2026-11-28 00:00:38 +00:00
Some checks failed
CodSpeed Benchmarks / benchmarks (push) Waiting to run
Cost map pins recheck / rerun-cost-map-guard (push) Waiting to run
Publish lint base counts / publish (type-discipline, litellm/scripts/type_discipline_gate.py) (push) Waiting to run
Publish lint base counts / publish (basedpyright, litellm/scripts/type_check_gate.py) (push) Waiting to run
Publish lint base counts / publish (openapi-docs, litellm/scripts/openapi_docs_gate.py) (push) Waiting to run
Publish lint base counts / publish (ruff-strict, litellm/scripts/ruff_strict_gate.py) (push) Waiting to run
Publish lint base counts / publish (test-quality, litellm/scripts/test_quality_gate.py) (push) Waiting to run
Root entry limit / root-entry-limit (push) Waiting to run
Scorecard supply-chain security / Scorecard analysis (push) Waiting to run
lint / lint passed (push) Blocked by required conditions
lint / lint plan (push) Waiting to run
lint / python (push) Blocked by required conditions
lint / typecheck (push) Blocked by required conditions
lint / semgrep (push) Waiting to run
lint / e2e-harness (push) Blocked by required conditions
lint / secret-scan (push) Waiting to run
lint / ui (push) Blocked by required conditions
lint / ui-api-types (push) Blocked by required conditions
lint / code-quality (push) Waiting to run
lint / ci-coverage (push) Waiting to run
smoke / smoke-rust-bridge (push) Waiting to run
smoke / dashboard-build (push) Waiting to run
smoke / py (push) Blocked by required conditions
smoke / all-extras-py (push) Blocked by required conditions
smoke / windows-sdk (push) Waiting to run
smoke / proxy-build-from-pip (push) Waiting to run
smoke / smoke passed (push) Blocked by required conditions
LiteLLM Rust DB / db-queries (push) Waiting to run
unit / rust-bridge (push) Waiting to run
unit / llms-providers (push) Blocked by required conditions
unit / proxy-endpoints (push) Blocked by required conditions
unit / proxy-feature-endpoints (push) Blocked by required conditions
unit / endpoints-and-responses (push) Blocked by required conditions
unit / enterprise-routing (push) Blocked by required conditions
unit / jwt-and-keys (push) Blocked by required conditions
unit / key-generation (push) Blocked by required conditions
unit / logging-misc (push) Blocked by required conditions
unit / mcp-oauth (push) Blocked by required conditions
unit / proxy-runtime (push) Blocked by required conditions
unit / proxy-server-core (push) Blocked by required conditions
unit / root (push) Blocked by required conditions
unit / proxy-utils (push) Blocked by required conditions
unit / core-auth-request (push) Blocked by required conditions
unit / auth-checks (push) Blocked by required conditions
unit / budgets (push) Blocked by required conditions
unit / custom-logging (push) Blocked by required conditions
unit / db-and-spend (push) Blocked by required conditions
unit / guardrails-hooks (push) Blocked by required conditions
unit / core-auth-spend (push) Blocked by required conditions
unit / core-logging-request-path (push) Blocked by required conditions
unit / core-management-cost (push) Blocked by required conditions
unit / core-utils-route (push) Blocked by required conditions
unit / core-router (push) Blocked by required conditions
unit / core-router-core (push) Blocked by required conditions
unit / core-router-retries (push) Blocked by required conditions
unit / changed-tests (push) Blocked by required conditions
unit / lint-runtime (push) Blocked by required conditions
unit / plan (push) Waiting to run
unit / enterprise-managed-files (push) Blocked by required conditions
unit / enterprise-repositories-secrets (push) Blocked by required conditions
unit / proxy-server (push) Blocked by required conditions
unit / lens-python-310 (push) Blocked by required conditions
unit / caching-local (push) Blocked by required conditions
unit / core-utils (push) Blocked by required conditions
unit / endpoints (push) Blocked by required conditions
unit / enterprise-package (push) Blocked by required conditions
unit / integrations (push) Blocked by required conditions
unit / llms-anthropic (push) Blocked by required conditions
unit / llms-bedrock (push) Blocked by required conditions
unit / llms-openai-meta (push) Blocked by required conditions
unit / llms-vertex-ai (push) Blocked by required conditions
unit / mcp-elicitation (push) Blocked by required conditions
unit / mcp-server (push) Blocked by required conditions
unit / proxy-auth (push) Blocked by required conditions
unit / proxy-extras (push) Blocked by required conditions
unit / proxy-hooks-client (push) Blocked by required conditions
unit / proxy-infra-db-spend (push) Blocked by required conditions
unit / proxy-infra-root-a-p (push) Blocked by required conditions
unit / proxy-infra-root-q-z (push) Blocked by required conditions
unit / proxy-infra-routing (push) Blocked by required conditions
unit / proxy-subprocess (push) Blocked by required conditions
unit / responses-caching-types (push) Blocked by required conditions
unit / router (push) Blocked by required conditions
unit / rust-bridge-harness (push) Blocked by required conditions
unit / ui-unit (push) Waiting to run
unit / docs (push) Blocked by required conditions
unit / helm (push) Blocked by required conditions
unit / OpenAI 2.20.0 compatibility (push) Blocked by required conditions
unit / OpenAI 3.0.0 compatibility (push) Blocked by required conditions
unit / OpenAI 3.25.0 compatibility (push) Blocked by required conditions
unit / redis-py 5.3.1 compatibility (push) Blocked by required conditions
unit / redis-py 6.4.0 compatibility (push) Blocked by required conditions
unit / redis-py 7.4.1 compatibility (push) Blocked by required conditions
unit / redis-py 8.0.1 compatibility (push) Blocked by required conditions
unit / unit passed (push) Blocked by required conditions
GitHub Actions Security Analysis / zizmor (push) Waiting to run
Terraform Modules / fmt, validate, test (aws) (push) Has been cancelled
Terraform Modules / fmt, validate, test (gcp) (push) Has been cancelled
Co-authored-by: mateo <277851410+mateo-berri@users.noreply.github.com> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
142 lines
5.3 KiB
Python
142 lines
5.3 KiB
Python
import dataclasses
|
|
import json
|
|
import math
|
|
import re
|
|
from collections.abc import Mapping, Set
|
|
from datetime import datetime, timezone
|
|
from pathlib import Path
|
|
from types import SimpleNamespace
|
|
from typing import Final
|
|
|
|
from pydantic import BaseModel
|
|
|
|
GOLDEN_PATH: Final = (
|
|
Path(__file__).resolve().parents[1] / "unit" / "proxy" / "hooks" / "parallel_request_limiter_v3_golden.json"
|
|
)
|
|
TTL_TOLERANCE_MS: Final = 10_000
|
|
_STAMP: Final = re.compile(r"\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?: UTC|[+-]\d{2}:\d{2}|Z)?")
|
|
_NUMERIC: Final = re.compile(r"-?\d+(?:\.\d+)?")
|
|
_SPAN: Final = 10**7
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True, eq=False)
|
|
class Ttl:
|
|
milliseconds: int
|
|
|
|
def __eq__(self, other: object) -> bool:
|
|
return isinstance(other, Ttl) and abs(self.milliseconds - other.milliseconds) < TTL_TOLERANCE_MS
|
|
|
|
|
|
def _instant(text: str) -> datetime:
|
|
parsed: Final = datetime.fromisoformat(text.removesuffix(" UTC").replace("Z", "+00:00"))
|
|
return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=timezone.utc)
|
|
|
|
|
|
def _relative(seconds: float, origin: float) -> str | None:
|
|
if not origin:
|
|
return None
|
|
if abs(seconds - origin) < _SPAN:
|
|
return f"<t{seconds - origin:+.3f}>"
|
|
if abs(seconds / 1000 - origin) < _SPAN:
|
|
return f"<tms{seconds / 1000 - origin:+.3f}>"
|
|
return None
|
|
|
|
|
|
def _text(value: str, origin: float) -> str:
|
|
if _NUMERIC.fullmatch(value) and (relative := _relative(float(value), origin)) is not None:
|
|
return f"str{relative}"
|
|
if not origin:
|
|
return value
|
|
return _STAMP.sub(lambda match: f"<t{_instant(match.group(0)).timestamp() - origin:+.3f}>", value)
|
|
|
|
|
|
def plain(value: object, origin: float) -> object:
|
|
match value:
|
|
case Ttl(milliseconds=milliseconds):
|
|
return {"__ttl_s__": -(-milliseconds // 1000)}
|
|
case bool() | None:
|
|
return value
|
|
case int() | float():
|
|
if isinstance(value, float) and not math.isfinite(value):
|
|
return {"__float__": repr(value)}
|
|
relative = _relative(value, origin)
|
|
return value if relative is None else relative
|
|
case str():
|
|
return _text(value, origin)
|
|
case bytes():
|
|
return {"__bytes__": value.hex()}
|
|
case BaseException():
|
|
return {"__error__": type(value).__name__, "text": _text(str(value), origin)}
|
|
case BaseModel():
|
|
return {"__model__": type(value).__name__, **_mapping(value.model_dump(mode="json"), origin)}
|
|
case SimpleNamespace():
|
|
return {"__namespace__": _mapping(vars(value), origin)}
|
|
case Mapping():
|
|
return _mapping(value, origin)
|
|
case Set():
|
|
return {"__set__": sorted((plain(item, origin) for item in value), key=_order)}
|
|
case list() | tuple():
|
|
return [plain(item, origin) for item in value]
|
|
case _ if dataclasses.is_dataclass(value) and not isinstance(value, type):
|
|
return {"__dataclass__": type(value).__name__, **_mapping(dataclasses.asdict(value), origin)}
|
|
case _:
|
|
raise TypeError(f"no golden form for {type(value).__qualname__}")
|
|
|
|
|
|
def _mapping(value: Mapping[object, object], origin: float) -> dict[str, object]:
|
|
return {str(key): plain(item, origin) for key, item in sorted(value.items(), key=lambda pair: str(pair[0]))}
|
|
|
|
|
|
def _order(value: object) -> str:
|
|
return json.dumps(value, sort_keys=True)
|
|
|
|
|
|
def matches(expected: object, actual: object) -> bool:
|
|
match expected, actual:
|
|
case {"__ttl_s__": int() as want}, {"__ttl_s__": int() as got}:
|
|
return abs(want - got) * 1000 < TTL_TOLERANCE_MS
|
|
case dict(), dict():
|
|
return expected.keys() == actual.keys() and all(matches(expected[key], actual[key]) for key in expected)
|
|
case list(), list():
|
|
return len(expected) == len(actual) and all(matches(want, got) for want, got in zip(expected, actual))
|
|
case _:
|
|
return expected == actual
|
|
|
|
|
|
class Golden:
|
|
def __init__(self, path: Path = GOLDEN_PATH) -> None:
|
|
self.expected: Final[dict[str, list[object]]] = json.loads(path.read_text())
|
|
self.case = ""
|
|
self.origin = 0.0
|
|
self.position = 0
|
|
self.skipped = False
|
|
|
|
def start(self, case: str) -> None:
|
|
self.case = case
|
|
self.origin = 0.0
|
|
self.position = 0
|
|
self.skipped = False
|
|
|
|
def skip_case(self) -> None:
|
|
self.skipped = True
|
|
|
|
def anchor(self, start: datetime) -> None:
|
|
self.origin = start.timestamp()
|
|
|
|
def upcoming(self, context: object = None) -> object:
|
|
expected: Final = self.expected.get(self.case)
|
|
assert expected is not None, f"{self.case} has no recorded golden values"
|
|
assert self.position < len(expected), (self.case, self.position, context)
|
|
return expected[self.position]
|
|
|
|
def agree(self, native: object, context: object = None) -> None:
|
|
expected: Final = self.upcoming(context)
|
|
actual: Final = plain(native, self.origin)
|
|
assert matches(expected, actual), (self.case, self.position, context, expected, actual)
|
|
self.position += 1
|
|
|
|
def finish_case(self) -> None:
|
|
if self.skipped:
|
|
return
|
|
recorded: Final = len(self.expected.get(self.case, []))
|
|
assert self.position == recorded, f"{self.case} consumed {self.position} of {recorded} recorded golden values"
|