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
feat(telemetry): keep reports in a local table with a persistent instance id and an admin export route (#45490)
devin-ai-integration[bot]083d48f62f1e
diff --git a/backend/routes/allowlist.py b/backend/routes/allowlist.pyindex 83e2221e866..60d695653b5 100644--- a/backend/routes/allowlist.py+++ b/backend/routes/allowlist.py@@ -32,6 +32,7 @@ BACKEND_PATH_PREFIXES: tuple[str, ...] = ("/token","/onboarding/","/audit",+ "/telemetry/","/oauth/","/invitation/","/jwt/",diff --git a/litellm-proxy-extras/litellm_proxy_extras/migrations/20261009000100_telemetry_reports/migration.sql b/litellm-proxy-extras/litellm_proxy_extras/migrations/20261009000100_telemetry_reports/migration.sqlnew file mode 100644index 00000000000..635bb325d0f--- /dev/null+++ b/litellm-proxy-extras/litellm_proxy_extras/migrations/20261009000100_telemetry_reports/migration.sql@@ -0,0 +1,12 @@+CREATE TABLE IF NOT EXISTS "LiteLLM_TelemetryReport" (+ "id" TEXT NOT NULL,+ "window_start" DOUBLE PRECISION NOT NULL,+ "window_end" DOUBLE PRECISION NOT NULL,+ "report" JSONB NOT NULL,+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ CONSTRAINT "LiteLLM_TelemetryReport_pkey" PRIMARY KEY ("id")+);++CREATE INDEX IF NOT EXISTS "LiteLLM_TelemetryReport_window_end_idx" ON "LiteLLM_TelemetryReport"("window_end");++CREATE INDEX IF NOT EXISTS "LiteLLM_TelemetryReport_created_at_idx" ON "LiteLLM_TelemetryReport"("created_at");diff --git a/litellm-proxy-extras/litellm_proxy_extras/schema.prisma b/litellm-proxy-extras/litellm_proxy_extras/schema.prismaindex f3ebee52dcd..ca58247a2c9 100644--- a/litellm-proxy-extras/litellm_proxy_extras/schema.prisma+++ b/litellm-proxy-extras/litellm_proxy_extras/schema.prisma@@ -2045,3 +2045,14 @@ model LiteLLM_LensTraceSignal {@@id([trace_id, trace_ref])}++model LiteLLM_TelemetryReport {+ id String @id+ window_start Float+ window_end Float+ report Json+ created_at DateTime @default(now())++ @@index([window_end])+ @@index([created_at])+}diff --git a/litellm/integrations/otel/model/spans.py b/litellm/integrations/otel/model/spans.pyindex a3b64fc22dd..76fc969cfc0 100644--- a/litellm/integrations/otel/model/spans.py+++ b/litellm/integrations/otel/model/spans.py@@ -335,6 +335,7 @@ _PRISMA_MODELS: Final[frozenset[str]] = frozenset("LiteLLM_PolicyTable","LiteLLM_PolicyAttachmentTable","LiteLLM_ToolTable",+ "LiteLLM_TelemetryReport","LiteLLM_AccessGroupTable","LiteLLM_ClaudeCodePluginTable","LiteLLM_MemoryTable",diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex 190abfea70e..306cb6bd95c 100644--- a/litellm/proxy/proxy_server.py+++ b/litellm/proxy/proxy_server.py@@ -756,6 +756,7 @@ from litellm.proxy.spend_tracking.spend_event_producer import (SpendEventProducer,build_spend_event_producer,)+from litellm.proxy.telemetry.endpoints import router as telemetry_routerfrom litellm.proxy.telemetry.middleware import TelemetryMiddlewarefrom litellm.proxy.telemetry.runtime import TelemetryRuntimefrom litellm.proxy.telemetry.settings import describe_errors as describe_telemetry_errors@@ -1707,12 +1708,22 @@ async def proxy_startup_event(app: FastAPI) -> AsyncGenerator[ProxyLifespanStateverbose_proxy_logger.warning("telemetry: invalid settings, leaving it off: %s", describe_telemetry_errors(telemetry_settings))- else:- await telemetry_runtime.start(- litellm_version=version,- settings=telemetry_settings,- register=litellm.logging_callback_manager.add_litellm_callback,+ telemetry_start: Final = (+ None+ if isinstance(telemetry_settings, ValidationError)+ else asyncio.create_task(+ telemetry_runtime.start(+ litellm_version=version,+ settings=telemetry_settings,+ db=lambda: ( # pyright: ignore[reportArgumentType] # PrismaWrapper forwards raw queries via __getattr__+ getattr(prisma_client.db, "writer", prisma_client.db) if prisma_client is not None else None+ ),+ register=litellm.logging_callback_manager.add_litellm_callback,+ ))+ )+ if telemetry_start is not None:+ telemetry_start.add_done_callback(_log_telemetry_start_failure)try:async with AsyncExitStack() as admin_mcp_stack:try:@@ -1766,6 +1777,9 @@ async def proxy_startup_event(app: FastAPI) -> AsyncGenerator[ProxyLifespanStateverbose_proxy_logger.error("Error stopping the spend view setup task: %s", e)await _drain_spend_event_producer_on_shutdown()+ if telemetry_start is not None:+ telemetry_start.cancel()+ await asyncio.gather(telemetry_start, return_exceptions=True)await telemetry_runtime.stop()# Shutdown event - finish or cancel in-flight scheduled jobs before the shutdown flushes and the DB disconnect@@ -2626,6 +2640,14 @@ app.add_middleware(sink_factory=lambda: gateway_request_accumulator if prisma_client is not None else None,)telemetry_runtime: Final = TelemetryRuntime()+++def _log_telemetry_start_failure(task: asyncio.Task[None]) -> None:+ error: Final = None if task.cancelled() else task.exception()+ if error is not None:+ verbose_proxy_logger.warning("telemetry: failed to start, leaving it off: %s", error)++app.add_middleware(TelemetryMiddleware,sink_provider=lambda: telemetry_runtime.sink,@@ -20419,6 +20441,7 @@ app.include_router(coordination_redis_settings_router)app.include_router(user_agent_analytics_router)app.include_router(gateway_request_router)app.include_router(request_error_router)+app.include_router(telemetry_router)app.include_router(enterprise_router)app.include_router(ui_discovery_endpoints_router)app.include_router(agent_skills_discovery_router)diff --git a/litellm/proxy/schema.prisma b/litellm/proxy/schema.prismaindex f3ebee52dcd..ca58247a2c9 100644--- a/litellm/proxy/schema.prisma+++ b/litellm/proxy/schema.prisma@@ -2045,3 +2045,14 @@ model LiteLLM_LensTraceSignal {@@id([trace_id, trace_ref])}++model LiteLLM_TelemetryReport {+ id String @id+ window_start Float+ window_end Float+ report Json+ created_at DateTime @default(now())++ @@index([window_end])+ @@index([created_at])+}diff --git a/litellm/proxy/telemetry/endpoints.py b/litellm/proxy/telemetry/endpoints.pynew file mode 100644index 00000000000..d690fc7fec4--- /dev/null+++ b/litellm/proxy/telemetry/endpoints.py@@ -0,0 +1,217 @@+from collections.abc import Mapping+from typing import Annotated, Final++from fastapi import APIRouter, Depends, HTTPException, Query+from pydantic import BaseModel, ConfigDict, JsonValue, TypeAdapter++from litellm._logging import verbose_proxy_logger+from litellm.proxy._types import CommonProxyErrors, LitellmUserRoles, UserAPIKeyAuth+from litellm.proxy.auth.user_api_key_auth import user_api_key_auth+from litellm.proxy.telemetry.runtime import StoredChoice, TelemetryRuntime+from litellm.proxy.telemetry.settings import FLUSH_INTERVAL_SECONDS, TelemetryDestination+from litellm.proxy.telemetry.store import StoredReport, TelemetryStore, store_read_errors+from litellm.telemetry.consent import OFF, REQUIRES, TelemetryConsent, parse_consent+from litellm.telemetry.records import TelemetryGroup+from litellm.telemetry.report import report_to_json+from litellm.telemetry.sample import sample_report++router: Final = APIRouter()+++class TelemetryReportsResponse(BaseModel):+ model_config = ConfigDict(frozen=True)++ reports: tuple[StoredReport, ...]+ next_after: float | None+ next_after_id: str | None+++def telemetry_store() -> TelemetryStore | None:+ from litellm.proxy.proxy_server import prisma_client, telemetry_runtime++ known: Final = telemetry_runtime.store+ if known is not None or prisma_client is None:+ return known+ return TelemetryStore(+ getattr(prisma_client.db, "writer", prisma_client.db), # pyright: ignore[reportArgumentType] # PrismaWrapper forwards raw queries via __getattr__+ telemetry_runtime.settings.retention_days,+ )++[email protected]("/telemetry/reports", tags=["Telemetry"], response_model=TelemetryReportsResponse)+async def export_telemetry_reports(+ user_api_key_dict: Annotated[UserAPIKeyAuth, Depends(user_api_key_auth)],+ store: Annotated[TelemetryStore | None, Depends(telemetry_store)],+ after: Annotated[float, Query(description="window_end of the last report already exported")] = 0.0,+ after_id: Annotated[str, Query(description="id of the last report already exported")] = "",+ limit: Annotated[int, Query(ge=1, le=5000)] = 500,+) -> TelemetryReportsResponse:+ """Stored telemetry reports, oldest first, for installs that keep telemetry local instead of sending it.+ Page with ``after=next_after&after_id=next_after_id`` until ``next_after`` is null. Another worker can commit a+ report just after a newer one is exported, so resume a later export a few windows before the last cursor and skip+ ids already seen"""+ if user_api_key_dict.user_role not in (LitellmUserRoles.PROXY_ADMIN, LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY):+ raise HTTPException(status_code=403, detail="Only proxy admin roles can export telemetry reports")+ if store is None:+ raise HTTPException(status_code=500, detail=CommonProxyErrors.db_not_connected_error.value)+ reports: Final = await store.reports_after(after, after_id, limit)+ if len(reports) < limit:+ return TelemetryReportsResponse(reports=reports, next_after=None, next_after_id=None)+ return TelemetryReportsResponse(reports=reports, next_after=reports[-1].window_end, next_after_id=reports[-1].id)+++_EVERYTHING: Final = TelemetryConsent(frozenset(TelemetryGroup))+_REPORT_JSON: Final = TypeAdapter(Mapping[str, JsonValue])+++class TelemetryGroupInfo(BaseModel):+ model_config = ConfigDict(frozen=True)++ group: TelemetryGroup+ requires: TelemetryGroup | None+ enabled: bool+++class TelemetrySettingsResponse(BaseModel):+ model_config = ConfigDict(frozen=True)++ groups: tuple[TelemetryGroupInfo, ...]+ stored_groups: tuple[TelemetryGroup, ...] | None+ vetoed: bool+ set_by_environment: bool+ environment_variables: tuple[str, ...]+ editable: bool+ destination: TelemetryDestination | None+ stored_destination: TelemetryDestination | None+ destination_set_by_environment: bool+ available_destinations: tuple[TelemetryDestination, ...]+ flush_interval_seconds: float+ retention_days: int+ report: Mapping[str, JsonValue] | None+ report_is_sample: bool+++class TelemetrySettingsUpdate(BaseModel):+ model_config = ConfigDict(frozen=True, extra="forbid")++ groups: tuple[str, ...]+ destination: TelemetryDestination | None = None+++def telemetry_runtime_dependency() -> TelemetryRuntime:+ from litellm.proxy.proxy_server import telemetry_runtime++ return telemetry_runtime+++def _available_destinations(runtime: TelemetryRuntime, has_database: bool) -> tuple[TelemetryDestination, ...]:+ return tuple(+ destination+ for destination, available in (+ (TelemetryDestination.LOCAL_TABLE, has_database),+ (TelemetryDestination.HTTP, runtime.settings.endpoint is not None),+ )+ if available+ )+++_STORE_UNAVAILABLE: Final = "Could not reach the stored telemetry settings, try again"+++async def _settings_response(+ runtime: TelemetryRuntime, stored: StoredChoice, has_database: bool, caller: UserAPIKeyAuth+) -> TelemetrySettingsResponse:+ policy: Final = runtime.policy+ effective: Final = policy.effective(stored.consent) if policy is not None else OFF+ last: Final = runtime.last_report+ preview: Final = (+ last+ if last is not None+ else await sample_report(+ effective if effective != OFF else _EVERYTHING, litellm_version=runtime.litellm_version+ )+ )+ return TelemetrySettingsResponse(+ groups=tuple(+ TelemetryGroupInfo(group=group, requires=REQUIRES[group], enabled=group in effective.groups)+ for group in TelemetryGroup+ ),+ stored_groups=(+ tuple(sorted(stored.consent.groups, key=tuple(TelemetryGroup).index))+ if stored.consent is not None+ else None+ ),+ vetoed=policy is None or policy.vetoed,+ set_by_environment=policy is None or policy.vetoed or policy.pinned is not None,+ environment_variables=policy.set_variables if policy is not None else (),+ editable=caller.user_role == LitellmUserRoles.PROXY_ADMIN+ and policy is not None+ and not policy.vetoed+ and policy.pinned is None+ and runtime.store is not None,+ destination=policy.effective_destination(stored.destination) if policy is not None else None,+ stored_destination=stored.destination,+ destination_set_by_environment=policy is not None and policy.destination is not None,+ available_destinations=_available_destinations(runtime, has_database),+ flush_interval_seconds=FLUSH_INTERVAL_SECONDS,+ retention_days=runtime.settings.retention_days,+ report=_REPORT_JSON.validate_python(report_to_json(preview)) if preview is not None else None,+ report_is_sample=last is None,+ )+++async def _stored(runtime: TelemetryRuntime) -> StoredChoice:+ try:+ return await runtime.stored_choice()+ except store_read_errors() as e:+ verbose_proxy_logger.warning("telemetry: could not read the stored settings: %s", e)+ raise HTTPException(status_code=503, detail=_STORE_UNAVAILABLE) from e++[email protected]("/telemetry/settings", tags=["Telemetry"], response_model=TelemetrySettingsResponse)+async def get_telemetry_settings(+ user_api_key_dict: Annotated[UserAPIKeyAuth, Depends(user_api_key_auth)],+ runtime: Annotated[TelemetryRuntime, Depends(telemetry_runtime_dependency)],+ store: Annotated[TelemetryStore | None, Depends(telemetry_store)],+) -> TelemetrySettingsResponse:+ """Which telemetry groups are on, whether env vars control them, where reports go and a last or sample report.+ Nothing is recorded until a destination is chosen by ``LITELLM_TELEMETRY_DESTINATION`` or a saved setting"""+ if user_api_key_dict.user_role not in (LitellmUserRoles.PROXY_ADMIN, LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY):+ raise HTTPException(status_code=403, detail="Only proxy admin roles can view telemetry settings")+ return await _settings_response(runtime, await _stored(runtime), store is not None, user_api_key_dict)++[email protected]("/telemetry/settings", tags=["Telemetry"], response_model=TelemetrySettingsResponse)+async def update_telemetry_settings(+ update: TelemetrySettingsUpdate,+ user_api_key_dict: Annotated[UserAPIKeyAuth, Depends(user_api_key_auth)],+ runtime: Annotated[TelemetryRuntime, Depends(telemetry_runtime_dependency)],+) -> TelemetrySettingsResponse:+ """Store the telemetry groups and destination for every worker, applied from the next report window"""+ if user_api_key_dict.user_role != LitellmUserRoles.PROXY_ADMIN:+ raise HTTPException(status_code=403, detail="Only the proxy admin can change telemetry settings")+ policy: Final = runtime.policy+ if policy is None or policy.vetoed or policy.pinned is not None:+ raise HTTPException(status_code=409, detail="Telemetry is set by LITELLM_TELEMETRY_* environment variables")+ store: Final = runtime.store+ if store is None:+ raise HTTPException(status_code=500, detail=CommonProxyErrors.db_not_connected_error.value)+ consent: Final = parse_consent(update.groups)+ if not isinstance(consent, TelemetryConsent):+ raise HTTPException(status_code=400, detail=consent.message())+ if update.destination is not None and policy.destination is not None:+ raise HTTPException(status_code=409, detail="The destination is set by LITELLM_TELEMETRY_DESTINATION")+ if update.destination is TelemetryDestination.HTTP and runtime.settings.endpoint is None:+ raise HTTPException(status_code=400, detail="Set LITELLM_TELEMETRY_ENDPOINT to send reports over HTTP")+ try:+ await store.save_settings(consent, update.destination)+ except store_read_errors() as e:+ verbose_proxy_logger.warning("telemetry: could not save the settings: %s", e)+ raise HTTPException(status_code=503, detail=_STORE_UNAVAILABLE) from e+ verbose_proxy_logger.info(+ "telemetry: %s set groups to %s and destination to %s",+ user_api_key_dict.user_id,+ sorted(g.value for g in consent.groups),+ update.destination and update.destination.value,+ )+ return await _settings_response(runtime, StoredChoice(consent, update.destination), True, user_api_key_dict)diff --git a/litellm/proxy/telemetry/runtime.py b/litellm/proxy/telemetry/runtime.pyindex a3746ad8bb7..c665d8cf88c 100644--- a/litellm/proxy/telemetry/runtime.py+++ b/litellm/proxy/telemetry/runtime.py@@ -4,7 +4,9 @@ import hashlibimport hmacimport secretsimport uuid-from collections.abc import Awaitable, Callable, Coroutine+from collections.abc import Awaitable, Callable, Coroutine, Iterator, Mapping+from dataclasses import dataclass+from types import MappingProxyTypefrom typing import Final, TypeAliasimport httpx@@ -15,24 +17,29 @@ from litellm.llms.custom_httpx.http_handler import ()from litellm.proxy.common_utils.encrypt_decrypt_utils import get_salt_keyfrom litellm.proxy.telemetry.attempt_logger import TelemetryAttemptLogger-from litellm.proxy.telemetry.settings import FLUSH_INTERVAL_SECONDS, EnvPolicy, TelemetrySettings, env_policy+from litellm.proxy.telemetry.settings import (+ FLUSH_INTERVAL_SECONDS,+ EnvPolicy,+ TelemetryDestination,+ TelemetrySettings,+ env_policy,+)+from litellm.proxy.telemetry.store import Database, LocalTableExporter, TelemetryStore, store_read_errorsfrom litellm.telemetry.aggregate import AggregatingSinkfrom litellm.telemetry.consent import OFF, ConsentGatedSink, TelemetryConsentfrom litellm.telemetry.http_exporter import HttpExporterfrom litellm.telemetry.records import InstanceInfo, TelemetryGroup-from litellm.telemetry.sink import Exporter+from litellm.telemetry.report import Report+from litellm.telemetry.sink import Exporter, ExportOutcomefrom litellm.types.llms.custom_http import httpxSpecialProvider--def shared_http_client() -> httpx.AsyncClient:- return get_async_httpx_client(httpxSpecialProvider.LoggingCallback, params={"timeout": 10.0}).client--StoredConsent: TypeAlias = Callable[[], Awaitable[TelemetryConsent | None]]-async def nothing_stored() -> TelemetryConsent | None:- return None+@dataclass(frozen=True, slots=True)+class StoredChoice:+ consent: TelemetryConsent | None = None+ destination: TelemetryDestination | None = Nonedef proxy_hash_secret() -> bytes:@@ -40,23 +47,84 @@ def proxy_hash_secret() -> bytes:return salt_key.encode() if salt_key is not None else secrets.token_bytes(32)+async def deployment_hash_secret(store: TelemetryStore | None, fallback: Callable[[], bytes]) -> bytes:+ if store is None:+ return fallback()+ try:+ return await store.deployment_hash_secret()+ except store_read_errors() as e:+ verbose_proxy_logger.warning(+ "telemetry: hashing deployments with the salt key, stored secret unreadable: %s", e+ )+ return fallback()++def deployment_hasher(secret: bytes) -> Callable[[str], str]:key: Final = hashlib.sha256(b"litellm-telemetry-deployment:" + secret).digest()return lambda model_id: hmac.new(key, model_id.encode(), hashlib.sha256).hexdigest()[:16]+class _RememberingExporter:+ def __init__(self, inner: Exporter) -> None:+ self._inner: Final = inner+ self.last_report: Report | None = None++ async def export(self, report: Report) -> ExportOutcome:+ outcome: Final = await self._inner.export(report)+ self.last_report = report if outcome is ExportOutcome.SENT else self.last_report+ return outcome+++def shared_http_client() -> httpx.AsyncClient:+ return get_async_httpx_client(httpxSpecialProvider.LoggingCallback, params={"timeout": 10.0}).client+++def _available_exporters(+ endpoint: str | None, store: TelemetryStore | None, http_client: Callable[[], httpx.AsyncClient]+) -> Iterator[tuple[TelemetryDestination, _RememberingExporter]]:+ if endpoint is not None:+ yield TelemetryDestination.HTTP, _RememberingExporter(HttpExporter(http_client(), endpoint))+ if store is not None:+ yield TelemetryDestination.LOCAL_TABLE, _RememberingExporter(LocalTableExporter(store))+++def _log_applied(consent: TelemetryConsent, destination: TelemetryDestination | None, *, recording: bool) -> None:+ groups: Final = sorted(group.value for group in consent.groups)+ if recording:+ verbose_proxy_logger.info(+ "telemetry: recording %s, reports go to %s", groups, destination and destination.value+ )+ elif consent != OFF:+ verbose_proxy_logger.warning(+ "telemetry: %s are on but no usable destination is chosen, recording nothing. Set "+ "LITELLM_TELEMETRY_DESTINATION or pick one on the Telemetry page",+ groups,+ )++class TelemetryRuntime:"""Owns the proxy's telemetry sink, re-reads which groups are on before every window, and flushes each window"""def __init__(self) -> None:self.sink: ConsentGatedSink | None = None- self.settings: TelemetrySettings = TelemetrySettings.model_construct()+ self.store: TelemetryStore | None = Noneself.policy: EnvPolicy | None = None- self._attach_logger: Callable[[], None] | None = None+ self.settings: TelemetrySettings = TelemetrySettings.model_construct()+ self.litellm_version: str = ""+ self.destination: TelemetryDestination | None = None+ self._exporters: Mapping[TelemetryDestination, _RememberingExporter] = MappingProxyType({})+ self._applied: tuple[TelemetryConsent, TelemetryDestination | None] | None = None+ self._instance: InstanceInfo | None = None+ self._attach_logger: Callable[[], Awaitable[None]] | None = Noneself._flush_task: asyncio.Task[None] | None = Noneself._flushing: asyncio.Future[None] | None = Noneself._pending: Final[set[asyncio.Task[None]]] = set() # mutable-ok: strong refs keep finalizers alive+ @property+ def last_report(self) -> Report | None:+ exporter: Final = self._exporters.get(self.destination) if self.destination is not None else None+ return exporter.last_report if exporter is not None else None+def spawn(self, coroutine: Coroutine[None, None, None]) -> None:task: Final = asyncio.create_task(coroutine)self._pending.add(task)@@ -67,67 +135,104 @@ class TelemetryRuntime:*,litellm_version: str,settings: TelemetrySettings,+ db: Callable[[], Database | None],register: Callable[[TelemetryAttemptLogger], None],- stored: StoredConsent = nothing_stored,http_client: Callable[[], httpx.AsyncClient] = shared_http_client,hash_secret: Callable[[], bytes] = proxy_hash_secret,flush_interval_s: float = FLUSH_INTERVAL_SECONDS,) -> None:- self.settings = settings+ self.settings, self.litellm_version = settings, litellm_versionpolicy: Final = env_policy(settings)self.policy = policyif policy.locked_off:return- if settings.endpoint is None:+ database: Final = db()+ store: Final = TelemetryStore(database, settings.retention_days) if database is not None else None+ if settings.endpoint is None and store is None:return- exporter: Final = HttpExporter(http_client(), str(settings.endpoint))- instance: Final = InstanceInfo(instance_id=uuid.uuid4().hex, litellm_version=litellm_version)- self._attach_logger = lambda: register(- TelemetryAttemptLogger(- lambda: self.sink, deployment_hasher(hash_secret()), blocks_enabled=self._counts_blocks+ self.store = store+ endpoint: Final = str(settings.endpoint) if settings.endpoint is not None else None+ self._exporters = MappingProxyType(dict(_available_exporters(endpoint, store, http_client)))++ async def attach_logger() -> None:+ register(+ TelemetryAttemptLogger(+ lambda: self.sink,+ deployment_hasher(await deployment_hash_secret(store, hash_secret)),+ blocks_enabled=self._counts_blocks,+ ))- )- await self._refresh(policy, stored, exporter, instance)- self._flush_task = asyncio.create_task(self._flush_every(policy, stored, exporter, instance, flush_interval_s))++ self._attach_logger = attach_logger+ await self.refresh()+ self._flush_task = asyncio.create_task(self._flush_every(flush_interval_s))++ async def _attach_logger_once(self) -> None:+ """Registers the attempt logger and creates its hash secret the first time a sink is built, so a proxy that never+ opts in carries no callback and writes nothing. It stays registered after groups are turned off, returning+ early, since removing it could skip in-flight calls"""+ attach: Final = self._attach_logger+ self._attach_logger = None+ if attach is not None:+ await attach()def _counts_blocks(self) -> bool:sink: Final = self.sinkreturn sink is not None and sink.consent.allows(TelemetryGroup.EVENT_DETAILS)- async def _refresh(- self, policy: EnvPolicy, stored: StoredConsent, exporter: Exporter, instance: InstanceInfo- ) -> None:- current: Final = self.sink- try:- consent: Final = policy.effective(await stored())- except Exception: # noqa: BLE001 -- a failed settings read keeps the current groups rather than flapping off- verbose_proxy_logger.debug("telemetry: could not read stored settings", exc_info=True)- return- if current is not None and current.consent == consent:- return- if consent == OFF:- self.sink = None+ async def stored_choice(self) -> StoredChoice:+ store: Final = self.store+ stored: Final = await store.settings() if store is not None else None+ if stored is None:+ return StoredChoice()+ if isinstance(stored.consent, TelemetryConsent):+ return StoredChoice(stored.consent, stored.destination)+ verbose_proxy_logger.warning("telemetry: ignoring stored groups, %s", stored.consent.message())+ return StoredChoice(destination=stored.destination)++ async def _instance_info(self) -> InstanceInfo:+ known: Final = self._instance+ if known is not None:+ return known+ store: Final = self.store+ instance: Final = InstanceInfo(+ instance_id=await store.instance_id() if store is not None else uuid.uuid4().hex,+ litellm_version=self.litellm_version,+ )+ self._instance = instance+ return instance++ async def refresh(self) -> None:+ """Apply the current groups and destination; only called between windows so every report has a single set"""+ policy: Final = self.policy+ if policy is None or not self._exporters:return- gated: Final = ConsentGatedSink(AggregatingSink(exporter), consent)- gated.set_instance(instance)- self._attach_logger_once()- self.sink = gated-- def _attach_logger_once(self) -> None:- """Registers the attempt logger the first time a group is on, so a proxy that never opts in carries no callback.- It stays registered after groups are turned off, returning early, since removing it could skip in-flight calls"""- attach: Final = self._attach_logger- self._attach_logger = None- if attach is not None:- attach()+ try:+ pinned: Final = policy.pinned is not None and policy.destination is not None+ stored: Final = StoredChoice() if pinned else await self.stored_choice()+ consent: Final = policy.effective(stored.consent)+ destination: Final = policy.effective_destination(stored.destination)+ if self._applied == (consent, destination):+ return+ exporter: Final = self._exporters.get(destination) if destination is not None else None+ sink: Final = (+ ConsentGatedSink(AggregatingSink(exporter), consent)+ if consent != OFF and exporter is not None+ else None+ )+ if sink is not None:+ sink.set_instance(await self._instance_info())+ await self._attach_logger_once()+ self.sink, self.destination, self._applied = sink, destination, (consent, destination)+ _log_applied(consent, destination, recording=sink is not None)+ except store_read_errors() as e:+ verbose_proxy_logger.debug("telemetry: keeping the current groups, could not read stored settings: %s", e)- async def _flush_every(- self, policy: EnvPolicy, stored: StoredConsent, exporter: Exporter, instance: InstanceInfo, interval_s: float- ) -> None:+ async def _flush_every(self, interval_s: float) -> None:while True:await asyncio.sleep(interval_s)await self._flush_window()- await self._refresh(policy, stored, exporter, instance)+ await self.refresh()async def _flush_window(self) -> None:flushing: Final = asyncio.ensure_future(self._flush_current())@@ -151,3 +256,4 @@ class TelemetryRuntime:await asyncio.gather(*self._pending, return_exceptions=True)await self._flush_current()self.sink = None+ self.store = Nonediff --git a/litellm/proxy/telemetry/settings.py b/litellm/proxy/telemetry/settings.pyindex b10ecac9e79..c6ba873f2f0 100644--- a/litellm/proxy/telemetry/settings.py+++ b/litellm/proxy/telemetry/settings.py@@ -1,9 +1,10 @@"""Environment policy for telemetry: the veto, the pinned groups, and which variables an admin should be told about"""from dataclasses import dataclass+from enum import Enumfrom typing import Annotated, Final-from pydantic import AfterValidator, Field, HttpUrl, ValidationError+from pydantic import AfterValidator, Field, HttpUrl, ValidationError, ValidationInfo, field_validatorfrom pydantic_settings import BaseSettings, SettingsConfigDictfrom litellm.telemetry.consent import OFF, TelemetryConsent, parse_consent@@ -12,6 +13,11 @@ ENV_PREFIX: Final = "LITELLM_TELEMETRY_"FLUSH_INTERVAL_SECONDS: Final = 300.0+class TelemetryDestination(str, Enum):+ LOCAL_TABLE = "local_table"+ HTTP = "http"++def _pinned_consent(groups: str) -> TelemetryConsent:consent: Final = parse_consent(groups.split(","))if not isinstance(consent, TelemetryConsent):@@ -33,7 +39,18 @@ class TelemetrySettings(BaseSettings):disabled: bool = Falsegroups: Annotated[str | None, AfterValidator(_valid_groups)] = Noneendpoint: HttpUrl | None = None+ destination: TelemetryDestination | None = Nonesettle_timeout_seconds: float = Field(default=2.0, ge=0)+ retention_days: int = Field(default=30, gt=0)++ @field_validator("destination")+ @classmethod+ def _http_needs_an_endpoint(+ cls, destination: TelemetryDestination | None, info: ValidationInfo+ ) -> TelemetryDestination | None:+ if destination is TelemetryDestination.HTTP and info.data.get("endpoint") is None:+ raise ValueError(f"http needs {ENV_PREFIX}ENDPOINT")+ return destinationdef load_settings() -> TelemetrySettings | ValidationError:@@ -55,6 +72,7 @@ def describe_errors(error: ValidationError) -> str:class EnvPolicy:vetoed: boolpinned: TelemetryConsent | None+ destination: TelemetryDestination | Noneset_variables: tuple[str, ...]def effective(self, stored: TelemetryConsent | None) -> TelemetryConsent:@@ -64,6 +82,9 @@ class EnvPolicy:return self.pinnedreturn stored if stored is not None else OFF+ def effective_destination(self, stored: TelemetryDestination | None) -> TelemetryDestination | None:+ return self.destination if self.destination is not None else stored+@propertydef locked_off(self) -> bool:return self.vetoed or self.pinned == OFF@@ -73,5 +94,6 @@ def env_policy(settings: TelemetrySettings) -> EnvPolicy:return EnvPolicy(vetoed=settings.disabled,pinned=_pinned_consent(settings.groups) if settings.groups is not None else None,+ destination=settings.destination,set_variables=tuple(sorted(f"{ENV_PREFIX}{name.upper()}" for name in settings.model_fields_set)),)diff --git a/litellm/proxy/telemetry/store.py b/litellm/proxy/telemetry/store.pynew file mode 100644index 00000000000..a63e56ca90c--- /dev/null+++ b/litellm/proxy/telemetry/store.py@@ -0,0 +1,181 @@+import json+import secrets+import uuid+from collections.abc import Awaitable+from dataclasses import dataclass+from typing import Final, Protocol++import httpx+from pydantic import BaseModel, ConfigDict, JsonValue, TypeAdapter+from typing_extensions import LiteralString++from litellm._logging import verbose_proxy_logger+from litellm.proxy.telemetry.settings import TelemetryDestination+from litellm.telemetry.consent import ConsentError, TelemetryConsent, parse_consent+from litellm.telemetry.report import Report, report_to_json+from litellm.telemetry.sink import ExportOutcome++INSTANCE_ID_PARAM: Final = "telemetry_instance_id"+HASH_SECRET_PARAM: Final = "telemetry_deployment_hash_secret"+SETTINGS_PARAM: Final = "telemetry_settings"+++class Database(Protocol):+ def query_raw(self, query: LiteralString, *args: object) -> Awaitable[object]: ...+ def execute_raw(self, query: LiteralString, *args: object) -> Awaitable[int]: ...+++class _ValueRow(BaseModel):+ model_config = ConfigDict(frozen=True)++ value: str+++class StoredReport(BaseModel):+ model_config = ConfigDict(frozen=True)++ id: str+ window_start: float+ window_end: float+ report: JsonValue+++class _StoredGroups(BaseModel):+ model_config = ConfigDict(frozen=True)++ groups: tuple[str, ...]+ destination: TelemetryDestination | None = None+++@dataclass(frozen=True, slots=True)+class StoredSettings:+ consent: TelemetryConsent | ConsentError+ destination: TelemetryDestination | None+++class _SettingsRow(BaseModel):+ model_config = ConfigDict(frozen=True)++ param_value: _StoredGroups+++_SETTINGS_ROWS: Final = TypeAdapter(tuple[_SettingsRow, ...])+_VALUE_ROWS: Final = TypeAdapter(tuple[_ValueRow, ...])+_REPORT_ROWS: Final = TypeAdapter(tuple[StoredReport, ...])+++class TelemetryStore:+ """The proxy DB side of telemetry: the install's stable instance id, deployment hash secret and report table"""++ def __init__(self, db: Database, retention_days: int) -> None:+ self._db: Final = db+ self._retention_days: Final = retention_days++ async def instance_id(self) -> str:+ return await self._persisted(INSTANCE_ID_PARAM, uuid.uuid4().hex)++ async def deployment_hash_secret(self) -> bytes:+ return (await self._persisted(HASH_SECRET_PARAM, secrets.token_hex(32))).encode()++ async def _persisted(self, param: str, candidate: str) -> str:+ await self._db.execute_raw(+ """INSERT INTO "LiteLLM_Config" (param_name, param_value) VALUES ($1, to_jsonb($2::text))+ ON CONFLICT (param_name) DO NOTHING""",+ param,+ candidate,+ )+ rows: Final = _VALUE_ROWS.validate_python(+ await self._db.query_raw(+ """SELECT param_value #>> '{}' AS value FROM "LiteLLM_Config" WHERE param_name = $1""",+ param,+ )+ )+ return rows[0].value++ async def settings(self) -> StoredSettings | None:+ rows: Final = _SETTINGS_ROWS.validate_python(+ await self._db.query_raw(+ """SELECT param_value FROM "LiteLLM_Config" WHERE param_name = $1""", SETTINGS_PARAM+ )+ )+ if not rows:+ return None+ stored: Final = rows[0].param_value+ return StoredSettings(consent=parse_consent(stored.groups), destination=stored.destination)++ async def save_settings(self, consent: TelemetryConsent, destination: TelemetryDestination | None) -> None:+ await self._db.execute_raw(+ """INSERT INTO "LiteLLM_Config" (param_name, param_value) VALUES ($1, $2::jsonb)+ ON CONFLICT (param_name) DO UPDATE SET param_value = EXCLUDED.param_value""",+ SETTINGS_PARAM,+ json.dumps(+ {+ "groups": sorted(group.value for group in consent.groups),+ "destination": destination.value if destination is not None else None,+ }+ ),+ )++ async def save(self, report_id: str, report: Report) -> None:+ await self._db.execute_raw(+ """INSERT INTO "LiteLLM_TelemetryReport" (id, window_start, window_end, report)+ VALUES ($1, $2, $3, $4::jsonb)+ ON CONFLICT (id) DO UPDATE SET window_end = EXCLUDED.window_end, report = EXCLUDED.report""",+ report_id,+ report.window_start,+ report.window_end,+ json.dumps(report_to_json(report)),+ )++ async def prune(self) -> None:+ await self._db.execute_raw(+ """DELETE FROM "LiteLLM_TelemetryReport" WHERE created_at < now() - make_interval(days => $1::int)""",+ self._retention_days,+ )++ async def reports_after(self, window_end: float, report_id: str, limit: int) -> tuple[StoredReport, ...]:+ return _REPORT_ROWS.validate_python(+ await self._db.query_raw(+ """SELECT id, window_start, window_end, report FROM "LiteLLM_TelemetryReport"+ WHERE (window_end, id) > ($1, $2) ORDER BY window_end, id LIMIT $3""",+ window_end,+ report_id,+ limit,+ )+ )+++def store_read_errors() -> tuple[type[Exception], ...]:+ from prisma.errors import PrismaError+ from pydantic import ValidationError++ return (PrismaError, OSError, httpx.HTTPError, ValidationError)+++class LocalTableExporter:+ """``Exporter`` that keeps reports in the proxy DB for manual export instead of sending them"""++ def __init__(self, store: TelemetryStore) -> None:+ self._store: Final = store+ self._retrying: tuple[float, str] | None = None++ def _report_id(self, report: Report) -> str:+ retrying: Final = self._retrying+ return retrying[1] if retrying is not None and retrying[0] == report.window_start else uuid.uuid4().hex++ async def export(self, report: Report) -> ExportOutcome:+ if not (report.requests or report.attempts or report.ui_events or report.dropped_records):+ return ExportOutcome.SENT+ report_id: Final = self._report_id(report)+ try:+ await self._store.save(report_id, report)+ except store_read_errors() as e:+ verbose_proxy_logger.debug("telemetry: could not store the report locally: %s", e)+ self._retrying = (report.window_start, report_id)+ return ExportOutcome.RETRY+ self._retrying = None+ try:+ await self._store.prune()+ except store_read_errors() as e:+ verbose_proxy_logger.debug("telemetry: could not prune old local reports: %s", e)+ return ExportOutcome.SENTdiff --git a/schema.prisma b/schema.prismaindex f3ebee52dcd..ca58247a2c9 100644--- a/schema.prisma+++ b/schema.prisma@@ -2045,3 +2045,14 @@ model LiteLLM_LensTraceSignal {@@id([trace_id, trace_ref])}++model LiteLLM_TelemetryReport {+ id String @id+ window_start Float+ window_end Float+ report Json+ created_at DateTime @default(now())++ @@index([window_end])+ @@index([created_at])+}diff --git a/tests/unit/proxy/telemetry/fake_database.py b/tests/unit/proxy/telemetry/fake_database.pynew file mode 100644index 00000000000..597ac5f9b48--- /dev/null+++ b/tests/unit/proxy/telemetry/fake_database.py@@ -0,0 +1,30 @@+import json+from dataclasses import dataclass+from typing import Final++from typing_extensions import LiteralString+++@dataclass+class SettingsDatabase:+ """In-memory ``LiteLLM_Config`` holding the telemetry instance id, hash secret and stored groups"""++ stored_groups: str | None = None+ fail_reads: bool = False+ instance_id: str = "persisted-install"+ hash_secret: str = "persisted-secret"+ inserted: tuple[str, ...] = ()++ async def query_raw(self, query: LiteralString, *args: object) -> object:+ if self.fail_reads:+ raise OSError("db down")+ if "AS value" in query:+ return ({"value": self.instance_id if args[0] == "telemetry_instance_id" else self.hash_secret},)+ stored: Final = self.stored_groups+ return () if stored is None else ({"param_value": json.loads(stored)},)++ async def execute_raw(self, query: LiteralString, *args: object) -> int:+ self.inserted = (*self.inserted, str(args[0]) if args else "")+ if args and args[0] == "telemetry_settings":+ self.stored_groups = str(args[1])+ return 1diff --git a/tests/unit/proxy/telemetry/test_endpoints.py b/tests/unit/proxy/telemetry/test_endpoints.pynew file mode 100644index 00000000000..abbbf41e51c--- /dev/null+++ b/tests/unit/proxy/telemetry/test_endpoints.py@@ -0,0 +1,266 @@+from dataclasses import dataclass+from collections.abc import Mapping+from typing import Final++from typing_extensions import LiteralString++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient+from httpx import ASGITransport, AsyncClient, Response++from litellm.proxy._types import CommonProxyErrors, LitellmUserRoles, UserAPIKeyAuth+from litellm.proxy.auth.user_api_key_auth import user_api_key_auth+from litellm.proxy.telemetry.endpoints import (+ TelemetrySettingsResponse,+ router,+ telemetry_runtime_dependency,+ telemetry_store,+)+from litellm.proxy.telemetry.runtime import TelemetryRuntime+from litellm.proxy.telemetry.settings import TelemetryDestination, TelemetrySettings+from litellm.proxy.telemetry.store import TelemetryStore+from tests.unit.proxy.telemetry.fake_database import SettingsDatabase+++@dataclass+class _ReportTable:+ rows: tuple[Mapping[str, object], ...]+ queried_with: tuple[object, ...] | None = None++ async def query_raw(self, query: LiteralString, *args: object) -> object:+ self.queried_with = args+ return self.rows++ async def execute_raw(self, query: LiteralString, *args: object) -> int:+ return 0+++def _row(report_id: str, window_end: float) -> Mapping[str, object]:+ return {"id": report_id, "window_start": window_end - 60, "window_end": window_end, "report": {"requests": []}}+++def _client(role: LitellmUserRoles, store: TelemetryStore | None) -> TestClient:+ app: Final = FastAPI()+ app.include_router(router)+ app.dependency_overrides[user_api_key_auth] = lambda: UserAPIKeyAuth(user_role=role)+ app.dependency_overrides[telemetry_store] = lambda: store+ return TestClient(app)+++def test_a_full_page_returns_a_cursor_at_its_last_report() -> None:+ table: Final = _ReportTable(rows=(_row("a", 100.0), _row("b", 100.0)))+ response: Final = _client(LitellmUserRoles.PROXY_ADMIN, TelemetryStore(table, retention_days=30)).get(+ "/telemetry/reports", params={"after": 40.0, "after_id": "z", "limit": 2}+ )+ assert response.status_code == 200, response.text+ assert response.json() == {+ "reports": [_row("a", 100.0), _row("b", 100.0)],+ "next_after": 100.0,+ "next_after_id": "b",+ }+ assert table.queried_with == (40.0, "z", 2)+++def test_a_short_page_is_the_last_one() -> None:+ table: Final = _ReportTable(rows=(_row("a", 100.0),))+ response: Final = _client(LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY, TelemetryStore(table, retention_days=30)).get(+ "/telemetry/reports", params={"limit": 2}+ )+ assert response.status_code == 200, response.text+ assert (response.json()["next_after"], response.json()["next_after_id"]) == (None, None)+ assert table.queried_with == (0.0, "", 2)++[email protected]("role", [LitellmUserRoles.INTERNAL_USER, LitellmUserRoles.ORG_ADMIN, LitellmUserRoles.TEAM])+def test_non_admin_roles_cannot_export_reports(role: LitellmUserRoles) -> None:+ table: Final = _ReportTable(rows=(_row("a", 100.0),))+ response: Final = _client(role, TelemetryStore(table, retention_days=30)).get("/telemetry/reports")+ assert response.status_code == 403, response.text+ assert table.queried_with is None+++def test_exporting_without_a_local_store_is_an_error() -> None:+ response: Final = _client(LitellmUserRoles.PROXY_ADMIN, None).get("/telemetry/reports")+ assert response.status_code == 500, response.text+++def test_the_proxy_app_serves_the_export_route_from_its_own_telemetry_runtime() -> None:+ from litellm.proxy.proxy_server import app, telemetry_runtime++ assert telemetry_runtime.store is None+ app.dependency_overrides[user_api_key_auth] = lambda: UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN)+ try:+ response: Final = TestClient(app).get("/telemetry/reports")+ finally:+ _ = app.dependency_overrides.pop(user_api_key_auth)+ assert response.status_code == 500, response.text+ assert response.json() == {"detail": CommonProxyErrors.db_not_connected_error.value}+++async def _settings_client(+ role: LitellmUserRoles, settings: TelemetrySettings, db: SettingsDatabase | None+) -> tuple[AsyncClient, TelemetryRuntime]:+ runtime: Final = TelemetryRuntime()+ await runtime.start(litellm_version="1.0.0", settings=settings, db=lambda: db, register=lambda _logger: None)+ app: Final = FastAPI()+ app.include_router(router)+ app.dependency_overrides[user_api_key_auth] = lambda: UserAPIKeyAuth(user_role=role, user_id="admin")+ app.dependency_overrides[telemetry_runtime_dependency] = lambda: runtime+ app.dependency_overrides[telemetry_store] = lambda: TelemetryStore(db, 30) if db is not None else None+ return AsyncClient(transport=ASGITransport(app=app), base_url="http://proxy"), runtime+++def _settings(response: Response) -> TelemetrySettingsResponse:+ assert response.status_code == 200, response.text+ return TelemetrySettingsResponse.model_validate_json(response.text)+++def _enabled(response: Response) -> tuple[str, ...]:+ return tuple(info.group.value for info in _settings(response).groups if info.enabled)+++async def test_an_admin_can_store_groups_and_reads_them_back_with_a_sample_report() -> None:+ db: Final = SettingsDatabase()+ client, runtime = await _settings_client(LitellmUserRoles.PROXY_ADMIN, TelemetrySettings(), db)+ async with client:+ saved: Final = await client.put(+ "/telemetry/settings", json={"groups": ["heartbeat", "request_success"], "destination": "local_table"}+ )+ read: Final = await client.get("/telemetry/settings")+ await runtime.stop()+ assert saved.status_code == 200, saved.text+ assert _enabled(read) == ("heartbeat", "request_success")+ body: Final = _settings(read)+ assert (body.editable, body.destination, body.stored_destination, body.report_is_sample) == (+ True,+ TelemetryDestination.LOCAL_TABLE,+ TelemetryDestination.LOCAL_TABLE,+ True,+ )+ assert body.report is not None and body.report["requests"]+++ ("groups", "status"),+ [(["token_info"], 400), (["heartbeat", "everything"], 400)],+)+async def test_invalid_groups_are_rejected_and_nothing_is_stored(groups: list[str], status: int) -> None:+ db: Final = SettingsDatabase()+ client, runtime = await _settings_client(LitellmUserRoles.PROXY_ADMIN, TelemetrySettings(), db)+ async with client:+ response: Final = await client.put("/telemetry/settings", json={"groups": groups})+ await runtime.stop()+ assert response.status_code == status, response.text+ assert db.stored_groups is None+++async def test_unknown_fields_in_the_update_are_rejected() -> None:+ client, runtime = await _settings_client(LitellmUserRoles.PROXY_ADMIN, TelemetrySettings(), SettingsDatabase())+ async with client:+ response: Final = await client.put("/telemetry/settings", json={"groups": [], "endpoint": "https://x"})+ await runtime.stop()+ assert response.status_code == 422, response.text+++async def test_a_view_only_admin_can_read_but_not_change_the_settings() -> None:+ db: Final = SettingsDatabase()+ client, runtime = await _settings_client(LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY, TelemetrySettings(), db)+ async with client:+ read: Final = await client.get("/telemetry/settings")+ write: Final = await client.put("/telemetry/settings", json={"groups": ["heartbeat"]})+ await runtime.stop()+ assert (read.status_code, write.status_code) == (200, 403)+ assert _settings(read).editable is False+ assert db.stored_groups is None+++async def test_internal_users_cannot_read_the_settings() -> None:+ client, runtime = await _settings_client(LitellmUserRoles.INTERNAL_USER, TelemetrySettings(), SettingsDatabase())+ async with client:+ response: Final = await client.get("/telemetry/settings")+ await runtime.stop()+ assert response.status_code == 403+++async def test_env_vars_lock_the_settings_and_are_listed_without_their_values(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("LITELLM_TELEMETRY_ENDPOINT", "https://user:[email protected]")+ db: Final = SettingsDatabase(stored_groups='{"groups": ["heartbeat"]}')+ client, runtime = await _settings_client(LitellmUserRoles.PROXY_ADMIN, TelemetrySettings(disabled=True), db)+ async with client:+ read: Final = await client.get("/telemetry/settings")+ write: Final = await client.put("/telemetry/settings", json={"groups": []})+ await runtime.stop()+ assert write.status_code == 409+ body: Final = _settings(read)+ assert (body.vetoed, body.editable, _enabled(read)) == (True, False, ())+ assert body.environment_variables == ("LITELLM_TELEMETRY_DISABLED", "LITELLM_TELEMETRY_ENDPOINT")+ assert "secret" not in read.text+++async def test_without_a_chosen_destination_the_settings_say_none_and_offer_only_what_is_configured() -> None:+ db: Final = SettingsDatabase(stored_groups='{"groups": ["heartbeat"]}')+ client, runtime = await _settings_client(LitellmUserRoles.PROXY_ADMIN, TelemetrySettings(), db)+ async with client:+ read: Final = await client.get("/telemetry/settings")+ await runtime.stop()+ body: Final = _settings(read)+ assert (body.destination, body.available_destinations) == (None, (TelemetryDestination.LOCAL_TABLE,))+ assert runtime.sink is None+++async def test_choosing_http_without_an_endpoint_is_rejected_and_nothing_is_stored() -> None:+ db: Final = SettingsDatabase()+ client, runtime = await _settings_client(LitellmUserRoles.PROXY_ADMIN, TelemetrySettings(), db)+ async with client:+ response: Final = await client.put("/telemetry/settings", json={"groups": ["heartbeat"], "destination": "http"})+ await runtime.stop()+ assert response.status_code == 400, response.text+ assert db.stored_groups is None+++async def test_an_env_destination_cannot_be_overridden_from_the_settings_page() -> None:+ db: Final = SettingsDatabase()+ settings: Final = TelemetrySettings(destination=TelemetryDestination.LOCAL_TABLE)+ client, runtime = await _settings_client(LitellmUserRoles.PROXY_ADMIN, settings, db)+ async with client:+ override: Final = await client.put(+ "/telemetry/settings", json={"groups": ["heartbeat"], "destination": "local_table"}+ )+ groups_only: Final = await client.put("/telemetry/settings", json={"groups": ["heartbeat"]})+ await runtime.stop()+ assert (override.status_code, groups_only.status_code) == (409, 200)+ assert _settings(groups_only).destination_set_by_environment is True+ assert _settings(groups_only).destination is TelemetryDestination.LOCAL_TABLE+++async def test_a_failing_settings_read_is_a_503_instead_of_a_crash() -> None:+ db: Final = SettingsDatabase(stored_groups='{"groups": ["heartbeat"]}')+ client, runtime = await _settings_client(LitellmUserRoles.PROXY_ADMIN, TelemetrySettings(), db)+ db.fail_reads = True+ async with client:+ response: Final = await client.get("/telemetry/settings")+ await runtime.stop()+ assert response.status_code == 503, response.text+ assert "db down" not in response.text+++async def test_the_settings_report_the_fixed_five_minute_window() -> None:+ client, runtime = await _settings_client(LitellmUserRoles.PROXY_ADMIN, TelemetrySettings(), SettingsDatabase())+ async with client:+ read: Final = await client.get("/telemetry/settings")+ await runtime.stop()+ assert _settings(read).flush_interval_seconds == 300diff --git a/tests/unit/proxy/telemetry/test_runtime.py b/tests/unit/proxy/telemetry/test_runtime.pyindex 5ba5aafb6f1..253b0997403 100644--- a/tests/unit/proxy/telemetry/test_runtime.py+++ b/tests/unit/proxy/telemetry/test_runtime.py@@ -7,9 +7,10 @@ from pydantic import HttpUrlfrom litellm.proxy.telemetry.attempt_logger import TelemetryAttemptLoggerfrom litellm.proxy.telemetry.runtime import TelemetryRuntime, deployment_hasher-from litellm.proxy.telemetry.settings import TelemetrySettings+from litellm.proxy.telemetry.settings import TelemetryDestination, TelemetrySettingsfrom litellm.telemetry.consent import ConsentGatedSink, TelemetryConsentfrom litellm.telemetry.records import AttemptRecord, InstanceInfo, RequestRecord, TelemetryGroup, UIEvent+from tests.unit.proxy.telemetry.fake_database import SettingsDatabase_ENDPOINT: Final = HttpUrl("http://telemetry.invalid/v1/reports")@@ -19,14 +20,15 @@ def _offline() -> httpx.AsyncClient:_HEARTBEAT: Final = TelemetryConsent(frozenset({TelemetryGroup.HEARTBEAT}))+_SUCCESS: Final = TelemetryConsent(frozenset({TelemetryGroup.HEARTBEAT, TelemetryGroup.REQUEST_SUCCESS}))-async def _stored_heartbeat() -> TelemetryConsent | None:- return _HEARTBEAT---async def _broken_store() -> TelemetryConsent | None:- raise ConnectionError("db down")+async def _started(settings: TelemetrySettings, db: SettingsDatabase | None) -> TelemetryRuntime:+ runtime: Final = TelemetryRuntime()+ await runtime.start(+ litellm_version="1.0.0", settings=settings, db=lambda: db, register=lambda _logger: None, http_client=_offline+ )+ return runtime@pytest.mark.parametrize(@@ -39,24 +41,41 @@ async def _broken_store() -> TelemetryConsent | None:],)@pytest.mark.asyncio-async def test_telemetry_stays_off_unless_valid_groups_and_an_endpoint_are_set_and_not_vetoed(+async def test_without_a_database_telemetry_needs_valid_pinned_groups_an_endpoint_and_no_veto(settings: TelemetrySettings,) -> None:registered: Final[list[TelemetryAttemptLogger]] = [] # mutable-ok: captures the register callbackruntime: Final = TelemetryRuntime()- await runtime.start(litellm_version="1.0.0", settings=settings, register=registered.append, http_client=_offline)+ await runtime.start(+ litellm_version="1.0.0", settings=settings, db=lambda: None, register=registered.append, http_client=_offline+ )assert runtime.sink is Noneassert registered == []+async def test_a_veto_never_opens_the_database() -> None:+ opened: Final[list[bool]] = [] # mutable-ok: records whether the db factory ran++ def _db() -> SettingsDatabase:+ opened.append(True)+ return SettingsDatabase(stored_groups='{"groups": ["heartbeat"]}')++ runtime: Final = TelemetryRuntime()+ await runtime.start(+ litellm_version="1.0.0", settings=TelemetrySettings(disabled=True), db=_db, register=lambda _logger: None+ )+ assert (runtime.sink, runtime.store, opened) == (None, None, [])++@pytest.mark.asyncioasync def test_pinned_groups_register_the_attempt_logger_and_stop_cleanly() -> None:registered: Final[list[TelemetryAttemptLogger]] = [] # mutable-ok: captures the register callbackruntime: Final = TelemetryRuntime()await runtime.start(litellm_version="1.0.0",- settings=TelemetrySettings(groups="HEARTBEAT", endpoint=_ENDPOINT),- flush_interval_s=3600,+ settings=TelemetrySettings(groups="HEARTBEAT", endpoint=_ENDPOINT, destination=TelemetryDestination.HTTP),+ db=lambda: None,register=registered.append,http_client=_offline,)@@ -67,74 +86,101 @@ async def test_pinned_groups_register_the_attempt_logger_and_stop_cleanly() -> N@pytest.mark.asyncio-async def test_stored_groups_apply_when_no_groups_are_pinned_and_a_veto_ignores_them() -> None:- enabled: Final = TelemetryRuntime()- await enabled.start(- litellm_version="1.0.0",- settings=TelemetrySettings(endpoint=_ENDPOINT),- flush_interval_s=3600,- register=lambda _logger: None,- http_client=_offline,- stored=_stored_heartbeat,- )- vetoed: Final = TelemetryRuntime()- await vetoed.start(- litellm_version="1.0.0",- settings=TelemetrySettings(endpoint=_ENDPOINT, disabled=True),- register=lambda _logger: None,- http_client=_offline,- stored=_stored_heartbeat,+async def test_pinned_groups_win_over_the_stored_groups() -> None:+ db: Final = SettingsDatabase(+ stored_groups='{"groups": ["heartbeat", "request_success"], "destination": "local_table"}')- assert enabled.sink is not None and enabled.sink.consent == _HEARTBEAT- assert vetoed.sink is None- await enabled.stop()+ runtime: Final = await _started(TelemetrySettings(groups="heartbeat"), db)+ assert runtime.sink is not None and runtime.sink.consent == _HEARTBEAT+ await runtime.stop()@pytest.mark.asyncio-async def test_a_failing_settings_store_leaves_telemetry_off_instead_of_crashing_startup() -> None:- runtime: Final = TelemetryRuntime()- await runtime.start(- litellm_version="1.0.0",- settings=TelemetrySettings(endpoint=_ENDPOINT),- flush_interval_s=3600,- register=lambda _logger: None,- http_client=_offline,- stored=_broken_store,- )+async def test_stored_groups_are_picked_up_at_the_next_window_without_a_restart() -> None:+ db: Final = SettingsDatabase()+ runtime: Final = await _started(TelemetrySettings(), db)+ assert runtime.sink is None+ db.stored_groups = '{"groups": ["heartbeat", "request_success"], "destination": "local_table"}'+ await runtime.refresh()+ assert runtime.sink is not None and runtime.sink.consent == _SUCCESS+ db.stored_groups = '{"groups": [], "destination": "local_table"}'+ await runtime.refresh()assert runtime.sink is Noneawait runtime.stop()@pytest.mark.asyncio-async def test_the_attempt_logger_is_registered_only_once_a_group_is_turned_on() -> None:+async def test_a_proxy_that_never_opts_in_registers_no_logger_and_writes_nothing() -> None:+ db: Final = SettingsDatabase()registered: Final[list[TelemetryAttemptLogger]] = [] # mutable-ok: captures the register callback- stored: list[TelemetryConsent | None] = [None] # mutable-ok: the stored groups the admin changes between windows-- async def _stored() -> TelemetryConsent | None:- return stored[0]-runtime: Final = TelemetryRuntime()await runtime.start(litellm_version="1.0.0",- settings=TelemetrySettings(endpoint=_ENDPOINT),- flush_interval_s=0.01,+ settings=TelemetrySettings(),+ db=lambda: db,register=registered.append,http_client=_offline,- stored=_stored,)- await asyncio.sleep(0.05)+ await runtime.refresh()+ assert (runtime.sink, registered, db.inserted) == (None, [], ())++ for stored in ('{"groups": ["heartbeat"], "destination": "local_table"}', '{"groups": []}'):+ db.stored_groups = stored+ await runtime.refresh()+ db.stored_groups = '{"groups": ["heartbeat"], "destination": "local_table"}'+ await runtime.refresh()+ assert runtime.sink is not None+ assert len(registered) == 1+ assert db.inserted.count("telemetry_deployment_hash_secret") == 1+ await runtime.stop()+++async def test_invalid_stored_groups_are_ignored_and_telemetry_stays_off() -> None:+ db: Final = SettingsDatabase(stored_groups='{"groups": ["token_info"]}')+ runtime: Final = await _started(TelemetrySettings(), db)assert runtime.sink is None- assert registered == []+ await runtime.stop()- for consent in (_HEARTBEAT, None, _HEARTBEAT):- stored[0] = consent- await asyncio.sleep(0.05)- assert (runtime.sink is not None) is (consent is not None)- assert len(registered) == 1++async def test_a_failing_settings_read_keeps_the_current_groups() -> None:+ db: Final = SettingsDatabase(stored_groups='{"groups": ["heartbeat"], "destination": "local_table"}')+ runtime: Final = await _started(TelemetrySettings(), db)+ db.fail_reads = True+ await runtime.refresh()+ assert runtime.sink is not None and runtime.sink.consent == _HEARTBEATawait runtime.stop()-def test_deployment_hashes_are_stable_per_install_and_differ_across_installs() -> None:+async def test_groups_without_a_chosen_destination_record_nothing_until_one_is_saved() -> None:+ db: Final = SettingsDatabase(stored_groups='{"groups": ["heartbeat"]}')+ runtime: Final = await _started(TelemetrySettings(groups="heartbeat"), db)+ assert (runtime.sink, runtime.destination) == (None, None)+ db.stored_groups = '{"groups": [], "destination": "local_table"}'+ await runtime.refresh()+ assert runtime.sink is not None and runtime.destination is TelemetryDestination.LOCAL_TABLE+ await runtime.stop()+++async def test_the_env_destination_wins_over_the_stored_one() -> None:+ db: Final = SettingsDatabase(stored_groups='{"groups": ["heartbeat"], "destination": "local_table"}')+ runtime: Final = await _started(TelemetrySettings(endpoint=_ENDPOINT, destination=TelemetryDestination.HTTP), db)+ assert runtime.sink is not None and runtime.destination is TelemetryDestination.HTTP+ await runtime.stop()+++async def test_a_stored_http_destination_without_an_endpoint_records_nothing() -> None:+ db: Final = SettingsDatabase(stored_groups='{"groups": ["heartbeat"], "destination": "http"}')+ runtime: Final = await _started(TelemetrySettings(), db)+ assert runtime.sink is None+ await runtime.stop()+++def test_deployment_hashes_are_stable_per_secret_and_differ_across_secrets() -> None:assert deployment_hasher(b"secret-a")("model-1") == deployment_hasher(b"secret-a")("model-1")assert deployment_hasher(b"secret-a")("model-1") != deployment_hasher(b"secret-b")("model-1")assert "model-1" not in deployment_hasher(b"secret-a")("model-1")@@ -142,13 +188,8 @@ def test_deployment_hashes_are_stable_per_install_and_differ_across_installs() -@pytest.mark.asyncioasync def test_stop_waits_for_in_flight_request_finalizers_before_the_last_flush() -> None:- runtime: Final = TelemetryRuntime()- await runtime.start(- litellm_version="1.0.0",- settings=TelemetrySettings(groups="heartbeat", endpoint=_ENDPOINT),- flush_interval_s=3600,- register=lambda _logger: None,- http_client=_offline,+ runtime: Final = await _started(+ TelemetrySettings(groups="heartbeat", endpoint=_ENDPOINT, destination=TelemetryDestination.HTTP), None)finished: Final[list[bool]] = [] # mutable-ok: records that the finalizer ran to completion@@ -193,8 +234,9 @@ async def test_stop_during_an_export_lets_that_export_finish() -> None:runtime: Final = TelemetryRuntime()await runtime.start(litellm_version="1.0.0",- settings=TelemetrySettings(groups="heartbeat", endpoint=_ENDPOINT),+ settings=TelemetrySettings(groups="heartbeat", endpoint=_ENDPOINT, destination=TelemetryDestination.HTTP),flush_interval_s=0.001,+ db=lambda: None,register=lambda _logger: None,http_client=_offline,)@@ -214,6 +256,7 @@ async def test_settle_timeout_reads_the_configured_value_after_start_and_the_defawait runtime.start(litellm_version="1.0.0",settings=TelemetrySettings(groups="heartbeat", endpoint=_ENDPOINT, settle_timeout_seconds=7.5),+ db=lambda: None,register=lambda _logger: None,http_client=_offline,)diff --git a/tests/unit/proxy/telemetry/test_settings.py b/tests/unit/proxy/telemetry/test_settings.pyindex cc219d2583e..0e9c180da4f 100644--- a/tests/unit/proxy/telemetry/test_settings.py+++ b/tests/unit/proxy/telemetry/test_settings.py@@ -1,3 +1,5 @@+from typing import Final+import pytestfrom pydantic import ValidationError@@ -90,6 +92,13 @@ def test_set_variables_lists_every_telemetry_env_var_present_but_never_its_valueassert policy.vetoed is True+def test_an_http_destination_without_an_endpoint_fails_settings_validation(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("LITELLM_TELEMETRY_DESTINATION", "http")+ error: Final = load_settings()+ assert isinstance(error, ValidationError)+ assert describe_errors(error).startswith("LITELLM_TELEMETRY_DESTINATION:")++def test_a_negative_settle_timeout_is_rejected(monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setenv("LITELLM_TELEMETRY_SETTLE_TIMEOUT_SECONDS", "-1")assert isinstance(load_settings(), ValidationError)diff --git a/tests/unit/proxy/telemetry/test_store.py b/tests/unit/proxy/telemetry/test_store.pynew file mode 100644index 00000000000..a8f826520f1--- /dev/null+++ b/tests/unit/proxy/telemetry/test_store.py@@ -0,0 +1,141 @@+from dataclasses import dataclass+from typing import Final++import pytest+from prisma.errors import PrismaError+from typing_extensions import LiteralString++from litellm.proxy.telemetry.attempt_logger import TelemetryAttemptLogger+from litellm.proxy.telemetry.runtime import TelemetryRuntime, deployment_hash_secret+from litellm.proxy.telemetry.settings import TelemetryDestination, TelemetrySettings+from litellm.proxy.telemetry.store import HASH_SECRET_PARAM, LocalTableExporter, TelemetryStore+from litellm.telemetry.records import AttemptRecord, InstanceInfo, StatusClass+from litellm.telemetry.report import Report+from litellm.telemetry.sink import ExportOutcome+++@dataclass+class _FakeDatabase:+ instance_id: str = "persisted-install"+ hash_secret: str = "persisted-secret"+ fail_reads: bool = False+ fail_writes: bool = False+ fail_prune: bool = False+ executed: tuple[tuple[str, tuple[object, ...]], ...] = ()++ async def query_raw(self, query: LiteralString, *args: object) -> object:+ if self.fail_reads:+ raise PrismaError("database is down")+ return ({"value": self.instance_id if args[0] == "telemetry_instance_id" else self.hash_secret},)++ failed_ids: tuple[object, ...] = ()++ async def execute_raw(self, query: LiteralString, *args: object) -> int:+ if self.fail_writes and query.lstrip().startswith("INSERT"):+ self.failed_ids = (*self.failed_ids, args[0])+ if self.fail_writes or (self.fail_prune and query.lstrip().startswith("DELETE")):+ raise PrismaError("database is down")+ self.executed = (*self.executed, (query, args))+ return 1+++def _report(*, dropped_records: int = 3) -> Report:+ return Report(+ instance=InstanceInfo(instance_id="i", litellm_version="1.0.0"),+ window_start=10.0,+ window_end=70.0,+ dropped_records=dropped_records,+ )+++async def test_a_stored_report_keeps_its_window_and_prunes_past_the_retention() -> None:+ db: Final = _FakeDatabase()+ assert await LocalTableExporter(TelemetryStore(db, retention_days=7)).export(_report()) is ExportOutcome.SENT+ (insert, insert_args), (prune, prune_args) = db.executed+ assert 'INSERT INTO "LiteLLM_TelemetryReport"' in insert+ assert insert_args[1:3] == (10.0, 70.0)+ assert '"instance_id": "i"' in str(insert_args[3])+ assert 'DELETE FROM "LiteLLM_TelemetryReport"' in prune+ assert prune_args == (7,)+++async def test_an_idle_window_is_not_stored() -> None:+ db: Final = _FakeDatabase()+ exporter: Final = LocalTableExporter(TelemetryStore(db, retention_days=7))+ assert await exporter.export(_report(dropped_records=0)) is ExportOutcome.SENT+ assert db.executed == ()+++async def test_a_database_failure_keeps_the_window_for_the_next_flush() -> None:+ exporter: Final = LocalTableExporter(TelemetryStore(_FakeDatabase(fail_writes=True), retention_days=7))+ assert await exporter.export(_report()) is ExportOutcome.RETRY+++async def test_retrying_a_window_whose_insert_may_have_committed_overwrites_it_instead_of_adding_a_copy() -> None:+ db: Final = _FakeDatabase(fail_writes=True)+ exporter: Final = LocalTableExporter(TelemetryStore(db, retention_days=7))+ assert await exporter.export(_report()) is ExportOutcome.RETRY+ db.fail_writes = False+ assert await exporter.export(_report()) is ExportOutcome.SENT+ assert await exporter.export(_report(dropped_records=5)) is ExportOutcome.SENT+ insert_ids: Final = [args[0] for query, args in db.executed if 'LiteLLM_TelemetryReport" (id' in query]+ retried, next_window = insert_ids+ assert retried == db.failed_ids[0] and next_window != retried+ assert "ON CONFLICT (id) DO UPDATE" in db.executed[0][0]+++async def test_a_failed_prune_does_not_resend_a_window_that_was_already_stored() -> None:+ db: Final = _FakeDatabase(fail_prune=True)+ assert await LocalTableExporter(TelemetryStore(db, retention_days=7)).export(_report()) is ExportOutcome.SENT+ assert len(db.executed) == 1+++async def test_the_local_table_destination_keeps_reports_under_the_persisted_instance_id() -> None:+ db: Final = _FakeDatabase()+ registered: Final[list[TelemetryAttemptLogger]] = [] # mutable-ok: captures the register callback+ runtime: Final = TelemetryRuntime()+ await runtime.start(+ litellm_version="1.0.0",+ settings=TelemetrySettings(+ groups="heartbeat,request_success,token_info,request_taxonomy",+ destination=TelemetryDestination.LOCAL_TABLE,+ ),+ db=lambda: db,+ register=registered.append,+ )+ assert runtime.store is not None+ assert runtime.sink is not None+ assert len(registered) == 1+ runtime.sink.record_attempt(AttemptRecord(provider="anthropic", provider_status=StatusClass.SUCCESS, stream=False))+ await runtime.stop()+ stored: Final = tuple(args for query, args in db.executed if 'INSERT INTO "LiteLLM_TelemetryReport"' in query)+ assert len(stored) == 1+ assert '"instance_id": "persisted-install"' in str(stored[0][3])+++async def test_deployments_are_hashed_with_the_secret_stored_in_the_database_not_the_salt_key() -> None:+ db: Final = _FakeDatabase()+ secret: Final = await deployment_hash_secret(TelemetryStore(db, retention_days=7), lambda: b"salt-key")+ ((_, (param, candidate)),) = db.executed+ assert secret == b"persisted-secret"+ assert param == HASH_SECRET_PARAM+ assert len(str(candidate)) == 64, "a fresh install stores a 32 byte random secret"+++ "store",+ [None, TelemetryStore(_FakeDatabase(fail_reads=True), retention_days=7)],+ ids=["no_database", "unreadable_database"],+)+async def test_without_a_readable_stored_secret_deployments_are_hashed_with_the_salt_key(+ store: TelemetryStore | None,+) -> None:+ assert await deployment_hash_secret(store, lambda: b"salt-key") == b"salt-key"diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.tsindex 06170f09504..9cebe788425 100644--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts@@ -17496,6 +17496,54 @@ export interface paths {patch?: never;trace?: never;};+ "/telemetry/reports": {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ /**+ * Export Telemetry Reports+ * @description Stored telemetry reports, oldest first, for installs that keep telemetry local instead of sending it.+ * Page with ``after=next_after&after_id=next_after_id`` until ``next_after`` is null. Another worker can commit a+ * report just after a newer one is exported, so resume a later export a few windows before the last cursor and skip+ * ids already seen+ */+ get: operations["export_telemetry_reports_telemetry_reports_get"];+ put?: never;+ post?: never;+ delete?: never;+ options?: never;+ head?: never;+ patch?: never;+ trace?: never;+ };+ "/telemetry/settings": {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ /**+ * Get Telemetry Settings+ * @description Which telemetry groups are on, whether env vars control them, where reports go and a last or sample report.+ * Nothing is recorded until a destination is chosen by ``LITELLM_TELEMETRY_DESTINATION`` or a saved setting+ */+ get: operations["get_telemetry_settings_telemetry_settings_get"];+ /**+ * Update Telemetry Settings+ * @description Store the telemetry groups and destination for every worker, applied from the next report window+ */+ put: operations["update_telemetry_settings_telemetry_settings_put"];+ post?: never;+ delete?: never;+ options?: never;+ head?: never;+ patch?: never;+ trace?: never;+ };"/test": {parameters: {query?: never;@@ -45314,6 +45362,16 @@ export interface components {*/user_ids: string[];};+ /** StoredReport */+ StoredReport: {+ /** Id */+ id: string;+ report: components["schemas"]["JsonValue"];+ /** Window End */+ window_end: number;+ /** Window Start */+ window_start: number;+ };/*** SuccessfulKeyUpdate* @description Successfully updated key with its updated information@@ -46133,6 +46191,71 @@ export interface components {/** User Id */user_id: string;};+ /**+ * TelemetryDestination+ * @enum {string}+ */+ TelemetryDestination: "local_table" | "http";+ /**+ * TelemetryGroup+ * @description A telemetry group describes a group of metrics that can be toggled on/off separately. One+ * group may have dependencies on another.+ * @enum {string}+ */+ TelemetryGroup: "heartbeat" | "request_success" | "token_info" | "request_taxonomy" | "event_details" | "instance_configuration" | "page_navigation";+ /** TelemetryGroupInfo */+ TelemetryGroupInfo: {+ /** Enabled */+ enabled: boolean;+ group: components["schemas"]["TelemetryGroup"];+ requires: components["schemas"]["TelemetryGroup"] | null;+ };+ /** TelemetryReportsResponse */+ TelemetryReportsResponse: {+ /** Next After */+ next_after: number | null;+ /** Next After Id */+ next_after_id: string | null;+ /** Reports */+ reports: components["schemas"]["StoredReport"][];+ };+ /** TelemetrySettingsResponse */+ TelemetrySettingsResponse: {+ /** Available Destinations */+ available_destinations: components["schemas"]["TelemetryDestination"][];+ destination: components["schemas"]["TelemetryDestination"] | null;+ /** Destination Set By Environment */+ destination_set_by_environment: boolean;+ /** Editable */+ editable: boolean;+ /** Environment Variables */+ environment_variables: string[];+ /** Flush Interval Seconds */+ flush_interval_seconds: number;+ /** Groups */+ groups: components["schemas"]["TelemetryGroupInfo"][];+ /** Report */+ report: {+ [key: string]: components["schemas"]["JsonValue"];+ } | null;+ /** Report Is Sample */+ report_is_sample: boolean;+ /** Retention Days */+ retention_days: number;+ /** Set By Environment */+ set_by_environment: boolean;+ stored_destination: components["schemas"]["TelemetryDestination"] | null;+ /** Stored Groups */+ stored_groups: components["schemas"]["TelemetryGroup"][] | null;+ /** Vetoed */+ vetoed: boolean;+ };+ /** TelemetrySettingsUpdate */+ TelemetrySettingsUpdate: {+ destination?: components["schemas"]["TelemetryDestination"] | null;+ /** Groups */+ groups: string[];+ };/*** TestCustomCodeGuardrailRequest* @description Request model for testing custom code guardrails.@@ -73301,6 +73424,94 @@ export interface operations {};};};+ export_telemetry_reports_telemetry_reports_get: {+ parameters: {+ query?: {+ /** @description window_end of the last report already exported */+ after?: number;+ /** @description id of the last report already exported */+ after_id?: string;+ limit?: number;+ };+ header?: never;+ path?: never;+ cookie?: never;+ };+ requestBody?: never;+ responses: {+ /** @description Successful Response */+ 200: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["TelemetryReportsResponse"];+ };+ };+ /** @description Validation Error */+ 422: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["HTTPValidationError"];+ };+ };+ };+ };+ get_telemetry_settings_telemetry_settings_get: {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ requestBody?: never;+ responses: {+ /** @description Successful Response */+ 200: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["TelemetrySettingsResponse"];+ };+ };+ };+ };+ update_telemetry_settings_telemetry_settings_put: {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ requestBody: {+ content: {+ "application/json": components["schemas"]["TelemetrySettingsUpdate"];+ };+ };+ responses: {+ /** @description Successful Response */+ 200: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["TelemetrySettingsResponse"];+ };+ };+ /** @description Validation Error */+ 422: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["HTTPValidationError"];+ };+ };+ };+ };test_endpoint_test_get: {parameters: {query?: never;