Skip to content

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]

test(e2e): datadog log delivery for streamed routes, read back from the real datadog api (#33566)

yucheng-berri0223383d94c0
diff --git a/tests/e2e/coverage_registry/logging.yaml b/tests/e2e/coverage_registry/logging.yaml
index 5528fce64c3..0f703632805 100644
--- a/tests/e2e/coverage_registry/logging.yaml
+++ b/tests/e2e/coverage_registry/logging.yaml
@@ -3,6 +3,7 @@
- {id: logging.s3.failure.writes_object, module: logging, tier: P0, event: failure, assertions: [writes_object], exercised_on: [chat_completions, messages], source: "integrations/s3_v2.py", rationale: "Failed calls persisted for compliance"}
- {id: logging.gcs_bucket.success.writes_object, module: logging, tier: P0, event: success, assertions: [writes_object], exercised_on: [chat_completions, messages, embeddings], source: "integrations/gcs_bucket/gcs_bucket.py", rationale: "GCS parallel to S3"}
- {id: logging.datadog.success.exports_metric, module: logging, tier: P0, event: success, assertions: [exports_metric], exercised_on: [chat_completions, messages, responses, embeddings], source: "integrations/datadog/datadog.py", rationale: "Powers dashboards/alerts; cardinality regressions common"}
+- {id: logging.datadog.stream.exports_metric, module: logging, tier: P0, event: stream, assertions: [exports_metric], exercised_on: [chat_completions, messages, responses], source: "integrations/datadog/datadog.py", rationale: "Streaming aggregates usage after the last chunk; delivery and cost must survive that path"}
- {id: logging.datadog.failure.exports_metric, module: logging, tier: P0, event: failure, assertions: [exports_metric], exercised_on: [chat_completions], source: "integrations/datadog/datadog.py", rationale: "Failure metrics for alerting/SLO"}
- {id: logging.prometheus.success.exports_metric, module: logging, tier: P0, event: success, assertions: [exports_metric], exercised_on: [chat_completions, messages, embeddings], source: "integrations/prometheus.py", rationale: "Standard OSS metrics; per-key cardinality (existing e2e)"}
- {id: logging.otel.success.exports_metric, module: logging, tier: P0, event: success, assertions: [exports_metric], exercised_on: [chat_completions, messages, responses, embeddings], source: "integrations/otel/logger.py", rationale: "OTEL spans on every call path"}
diff --git a/tests/e2e/e2e_config.py b/tests/e2e/e2e_config.py
index 798dadd1343..529744d5a2c 100644
--- a/tests/e2e/e2e_config.py
+++ b/tests/e2e/e2e_config.py
@@ -49,6 +49,11 @@ DD_SETTLE_SECONDS = float(os.environ.get("E2E_DD_SETTLE_SECONDS", "30"))
# DataDog Logs Search `from` window (relative to now). Wide enough for a suite
# run plus ingestion lag; override if a long CI queue needs a wider lookback.
DD_SEARCH_FROM = os.environ.get("E2E_DD_SEARCH_FROM", "now-30m").strip() or "now-30m"
+# The Logs Search API budget is tight - 2 requests per 10s org-wide
+# (x-ratelimit-name logs_public_search_api) - so read-backs pace their search
+# calls at this interval instead of POLL_INTERVAL, and back off when a 429
+# still slips through (the budget is shared with anything else searching).
+DD_SEARCH_INTERVAL = float(os.environ.get("E2E_DD_SEARCH_INTERVAL", "10"))
# Writes on the proxy are eventually consistent (e.g. spend rows flush on
# proxy_batch_write_at, ~60s). Read-backs poll to this deadline, never sleep-once.
diff --git a/tests/e2e/logging/datadog_reader.py b/tests/e2e/logging/datadog_reader.py
index b973557ebfa..7d882a7fa81 100644
--- a/tests/e2e/logging/datadog_reader.py
+++ b/tests/e2e/logging/datadog_reader.py
@@ -22,12 +22,17 @@ from e2e_config import (
DD_API_KEY,
DD_APP_KEY,
DD_SEARCH_FROM,
+ DD_SEARCH_INTERVAL,
DD_SETTLE_SECONDS,
DD_SITE,
- POLL_INTERVAL,
POLL_TIMEOUT,
)
-from e2e_http import URL, Headers, Success, post
+from e2e_http import URL, Headers, RateLimitedError, Success, post
+
+#: How many rate-limited responses in a row one search tolerates before the
+#: hard fail; each retry sleeps a full search interval, so this rides out a
+#: burst from a concurrent consumer of the org-wide search budget.
+_RATE_LIMIT_RETRIES = 5
class _DdAuthHeaders(Headers):
@@ -87,41 +92,56 @@ class DdLogsReader:
app_key: str
def events_for_marker(self, marker: str) -> list[DdLogEvent]:
- """Every ingested event matching the marker (full-text, exact phrase).
- More than one hit for one call IS the duplicate-delivery bug, so this
- never collapses to a single event."""
- result = post(
- URL(f"https://api.{self.site}/api/v2/logs/events/search"),
- headers=_DdAuthHeaders(api_key=self.api_key, app_key=self.app_key),
- json=_SearchRequest(filter=_SearchFilter(query=f'"{marker}"')),
- response_type=_SearchResponse,
- timeout=30.0,
+ """Every ingested event whose attributes carry the marker. DataDog
+ consumes the shipped JSON message into ``attributes`` and leaves the
+ indexed ``message`` empty, so a plain full-text query matches nothing;
+ ``*:`` extends the scan to every attribute (the marker sits in the
+ prompt, e.g. ``messages.content``, wherever the route's payload puts
+ it). More than one hit for one call IS the duplicate-delivery bug, so
+ this never collapses to a single event. A 429 backs off and retries -
+ the search budget is org-wide, so another consumer can empty it under
+ us - while any other failure stays a hard fail."""
+ for _ in range(_RATE_LIMIT_RETRIES):
+ result = post(
+ URL(f"https://api.{self.site}/api/v2/logs/events/search"),
+ headers=_DdAuthHeaders(api_key=self.api_key, app_key=self.app_key),
+ json=_SearchRequest(filter=_SearchFilter(query=f"*:*{marker}*")),
+ response_type=_SearchResponse,
+ timeout=30.0,
+ )
+ match result:
+ case Success(data=page):
+ return [event.attributes for event in page.data]
+ case RateLimitedError(retry_after_seconds=retry_after):
+ time.sleep(retry_after if retry_after else DD_SEARCH_INTERVAL)
+ case failure:
+ pytest.fail(f"DataDog Logs Search API at api.{self.site} failed: {failure}")
+ pytest.fail(
+ f"DataDog Logs Search API at api.{self.site} still rate-limited after "
+ f"{_RATE_LIMIT_RETRIES} retries {DD_SEARCH_INTERVAL}s apart - the org-wide "
+ "logs_public_search_api budget (2 requests per 10s) is exhausted by another consumer"
)
- match result:
- case Success(data=page):
- return [event.attributes for event in page.data]
- case failure:
- pytest.fail(f"DataDog Logs Search API at api.{self.site} failed: {failure}")
def poll_events_for_marker(self, marker: str) -> list[DdLogEvent]:
"""Poll until at least one matching event is searchable (the callback
flushes in periodic batches and DataDog ingestion adds seconds of lag),
then keep re-reading for DD_SETTLE_SECONDS so a late duplicate cannot
hide from the exactly-one assertion - real-DataDog jitter can surface
- one call's two events tens of seconds apart. At the deadline the last
- result is returned as-is."""
+ one call's two events tens of seconds apart. Searches pace at
+ DD_SEARCH_INTERVAL, not POLL_INTERVAL, to respect the search API's
+ request budget. At the deadline the last result is returned as-is."""
deadline = time.monotonic() + POLL_TIMEOUT
while time.monotonic() < deadline:
events = self.events_for_marker(marker)
if events:
return self._settled_events_for_marker(marker, events)
- time.sleep(POLL_INTERVAL)
+ time.sleep(DD_SEARCH_INTERVAL)
return self.events_for_marker(marker)
def _settled_events_for_marker(
self, marker: str, events: list[DdLogEvent]
) -> list[DdLogEvent]:
- """Re-read at every poll interval until the settle window closes; a
+ """Re-read at every search interval until the settle window closes; a
duplicate ends the watch early because more waiting cannot clear it.
Keep the last non-empty result: a transient empty search (index lag)
@@ -130,7 +150,7 @@ class DdLogsReader:
settle_deadline = time.monotonic() + DD_SETTLE_SECONDS
last_nonempty = events
while time.monotonic() < settle_deadline:
- time.sleep(POLL_INTERVAL)
+ time.sleep(DD_SEARCH_INTERVAL)
latest = self.events_for_marker(marker)
if not latest:
continue
diff --git a/tests/e2e/logging/test_datadog_log_e2e.py b/tests/e2e/logging/test_datadog_log_e2e.py
index 1c2cd09916b..48c111b6467 100644
--- a/tests/e2e/logging/test_datadog_log_e2e.py
+++ b/tests/e2e/logging/test_datadog_log_e2e.py
@@ -25,7 +25,7 @@ from pydantic import BaseModel, ConfigDict
from datadog_reader import DdLogEvent, DdLogsReader
from e2e_config import CHEAP_ANTHROPIC_MODEL, CHEAP_OPENAI_MODEL, unique_marker
-from e2e_http import NoBody, StreamingResponse
+from e2e_http import NoBody
from lifecycle import ResourceManager
from logging_client import LoggingClient, first_ok
@@ -45,6 +45,7 @@ class _DdMessagePayload(BaseModel):
response_cost: float
status: str
call_type: str
+ stream: bool | None = None
def _assert_datadog_configured(client: LoggingClient) -> None:
@@ -62,22 +63,35 @@ def _assert_datadog_configured(client: LoggingClient) -> None:
def _assert_exactly_one_event(
- events: list[DdLogEvent], *, model_group: str, call_type: str, outcome: StreamingResponse
-) -> None:
+ events: list[DdLogEvent],
+ *,
+ model_group: str,
+ call_type: str,
+ cost_anchor: float,
+ expect_stream: bool = False,
+) -> _DdMessagePayload:
"""The enforced behavior: the intake holds exactly one event for the call,
sourced from litellm, whose payload names the model group and call type,
- counts real tokens, and carries the same cost the response header reported."""
+ counts real tokens, and carries the same cost as ``cost_anchor`` - the
+ x-litellm-response-cost header for non-streaming calls, or the /spend/logs
+ row for streamed calls (headers ship before a stream's cost exists)."""
assert events, "no DataDog log event for this call reached the intake within the deadline"
assert len(events) == 1, (
f"expected exactly ONE DataDog log event for the call, got {len(events)} - "
"more than one event for one call is the duplicate-delivery bug (see LIT-4447 "
- "for the currently known /v1/messages instance)"
+ "for the currently known non-streaming /v1/messages instance)"
)
event = events[0]
assert "source:litellm" in event.tags, (
f"the ingested event must carry the litellm source (shipped as ddsource), got tags {event.tags!r}"
)
- assert event.status == "info", f"success events ship at status info, got {event.status!r}"
+ # The proxy ships the envelope at status "info", but DataDog re-derives the
+ # indexed event status from the parsed payload's status attribute
+ # ("success") and normalizes it to its OK severity - so "ok" is what a
+ # successfully ingested success event looks like on the search API.
+ assert event.status == "ok", (
+ f"success events must index at DataDog's ok severity, got {event.status!r}"
+ )
payload = _DdMessagePayload.model_validate(event.attributes)
assert payload.status == "success", f"payload status must be success, got {payload.status!r}"
@@ -88,16 +102,17 @@ def _assert_exactly_one_event(
f"payload call_type must be {call_type!r}, got {payload.call_type!r}"
)
assert payload.total_tokens > 0, f"payload must count real tokens, got {payload.total_tokens}"
- assert outcome.response_cost is not None and outcome.response_cost > 0, (
- f"the response must report x-litellm-response-cost, got {outcome.response_cost!r}"
- )
# Relative tolerance, not bit-equality: the cost round-trips through
# DataDog's attribute indexing, whose float serialization may drift in the
# last bits; 9 significant digits still catches any real cost discrepancy.
- assert math.isclose(payload.response_cost, outcome.response_cost, rel_tol=1e-9), (
- f"payload response_cost {payload.response_cost} must equal the response header "
- f"cost {outcome.response_cost}"
+ assert math.isclose(payload.response_cost, cost_anchor, rel_tol=1e-9), (
+ f"payload response_cost {payload.response_cost} must equal the anchor cost {cost_anchor}"
)
+ if expect_stream:
+ assert payload.stream is True, (
+ f"a streamed call's payload must record stream=true, got {payload.stream!r}"
+ )
+ return payload
class TestDataDogLogDelivery:
@@ -118,9 +133,12 @@ class TestDataDogLogDelivery:
client,
lambda: client.chat_raw(key, CHEAP_ANTHROPIC_MODEL, f"reply with one word {marker}", max_tokens=16),
)
+ assert outcome.response_cost is not None and outcome.response_cost > 0, (
+ f"the response must report x-litellm-response-cost, got {outcome.response_cost!r}"
+ )
events = dd_logs.poll_events_for_marker(marker)
_assert_exactly_one_event(
- events, model_group=CHEAP_ANTHROPIC_MODEL, call_type="acompletion", outcome=outcome
+ events, model_group=CHEAP_ANTHROPIC_MODEL, call_type="acompletion", cost_anchor=outcome.response_cost
)
@pytest.mark.covers("logging.datadog.success.exports_metric", exercised_on=["messages"])
@@ -142,9 +160,12 @@ class TestDataDogLogDelivery:
client,
lambda: client.messages_raw(key, CHEAP_ANTHROPIC_MODEL, f"reply with one word {marker}", max_tokens=16),
)
+ assert outcome.response_cost is not None and outcome.response_cost > 0, (
+ f"the response must report x-litellm-response-cost, got {outcome.response_cost!r}"
+ )
events = dd_logs.poll_events_for_marker(marker)
_assert_exactly_one_event(
- events, model_group=CHEAP_ANTHROPIC_MODEL, call_type="anthropic_messages", outcome=outcome
+ events, model_group=CHEAP_ANTHROPIC_MODEL, call_type="anthropic_messages", cost_anchor=outcome.response_cost
)
@pytest.mark.covers("logging.datadog.success.exports_metric", exercised_on=["responses"])
@@ -164,7 +185,144 @@ class TestDataDogLogDelivery:
client,
lambda: client.responses_raw(key, CHEAP_OPENAI_MODEL, f"reply with one word {marker}"),
)
+ assert outcome.response_cost is not None and outcome.response_cost > 0, (
+ f"the response must report x-litellm-response-cost, got {outcome.response_cost!r}"
+ )
events = dd_logs.poll_events_for_marker(marker)
_assert_exactly_one_event(
- events, model_group=CHEAP_OPENAI_MODEL, call_type="aresponses", outcome=outcome
+ events, model_group=CHEAP_OPENAI_MODEL, call_type="aresponses", cost_anchor=outcome.response_cost
+ )
+
+ @pytest.mark.covers("logging.datadog.stream.exports_metric", exercised_on=["chat_completions"])
+ def test_chat_completions_stream_emits_one_log_event(
+ self, client: LoggingClient, dd_logs: DdLogsReader, resources: ResourceManager
+ ) -> None:
+ """One successful STREAMED /chat/completions call must reach real
+ DataDog as exactly one log event whose payload carries the model, the
+ token counts aggregated across the stream, stream=true, and a response
+ cost equal to the /spend/logs row for the same call (a stream's
+ headers ship before its cost exists, so the spend row is the
+ cross-check anchor)."""
+ _assert_datadog_configured(client)
+
+ key = client.key_with_alias(f"dd-stream-chat-{unique_marker()}", models=[CHEAP_ANTHROPIC_MODEL])
+ resources.defer(lambda: client.delete_key(key))
+
+ marker = unique_marker()
+ outcome = first_ok(
+ client,
+ lambda: client.chat_raw(key, CHEAP_ANTHROPIC_MODEL, f"reply with one word {marker}", stream=True, max_tokens=16),
+ )
+ assert outcome.is_streaming, f"response must be an event stream, got content-type {outcome.content_type!r}"
+ assert outcome.chunks > 0, "the stream must deliver at least one event"
+ assert outcome.stream_error is None, (
+ f"the stream carried an upstream error event despite the 200: {outcome.stream_error}"
+ )
+
+ spend_row = client.poll_proxy_spend_for_key(key)
+ assert spend_row is not None and spend_row.spend is not None and spend_row.spend > 0, (
+ f"the streamed call must record a positive-spend row, got {spend_row!r}"
+ )
+ events = dd_logs.poll_events_for_marker(marker)
+ payload = _assert_exactly_one_event(
+ events,
+ model_group=CHEAP_ANTHROPIC_MODEL,
+ call_type="acompletion",
+ cost_anchor=spend_row.spend,
+ expect_stream=True,
+ )
+ assert spend_row.total_tokens is not None, (
+ "the spend row must record total_tokens for the token cross-check"
+ )
+ assert spend_row.total_tokens == payload.total_tokens, (
+ f"the spend row and the DataDog event must agree on tokens: "
+ f"{spend_row.total_tokens} vs {payload.total_tokens}"
+ )
+
+ @pytest.mark.covers("logging.datadog.stream.exports_metric", exercised_on=["messages"])
+ def test_messages_stream_emits_one_log_event(
+ self, client: LoggingClient, dd_logs: DdLogsReader, resources: ResourceManager
+ ) -> None:
+ """One successful STREAMED /v1/messages call must reach real DataDog
+ as exactly one log event whose payload carries the model, the token
+ counts aggregated across the stream, stream=true, and a response cost
+ equal to the /spend/logs row for the same call."""
+ _assert_datadog_configured(client)
+
+ key = client.key_with_alias(f"dd-stream-messages-{unique_marker()}", models=[CHEAP_ANTHROPIC_MODEL])
+ resources.defer(lambda: client.delete_key(key))
+
+ marker = unique_marker()
+ outcome = first_ok(
+ client,
+ lambda: client.messages_raw(key, CHEAP_ANTHROPIC_MODEL, f"reply with one word {marker}", max_tokens=16, stream=True),
+ )
+ assert outcome.is_streaming, f"response must be an event stream, got content-type {outcome.content_type!r}"
+ assert outcome.chunks > 0, "the stream must deliver at least one event"
+ assert outcome.stream_error is None, (
+ f"the stream carried an upstream error event despite the 200: {outcome.stream_error}"
+ )
+
+ spend_row = client.poll_proxy_spend_for_key(key)
+ assert spend_row is not None and spend_row.spend is not None and spend_row.spend > 0, (
+ f"the streamed call must record a positive-spend row, got {spend_row!r}"
+ )
+ events = dd_logs.poll_events_for_marker(marker)
+ payload = _assert_exactly_one_event(
+ events,
+ model_group=CHEAP_ANTHROPIC_MODEL,
+ call_type="anthropic_messages",
+ cost_anchor=spend_row.spend,
+ expect_stream=True,
+ )
+ assert spend_row.total_tokens is not None, (
+ "the spend row must record total_tokens for the token cross-check"
+ )
+ assert spend_row.total_tokens == payload.total_tokens, (
+ f"the spend row and the DataDog event must agree on tokens: "
+ f"{spend_row.total_tokens} vs {payload.total_tokens}"
+ )
+
+ @pytest.mark.covers("logging.datadog.stream.exports_metric", exercised_on=["responses"])
+ def test_responses_stream_emits_one_log_event(
+ self, client: LoggingClient, dd_logs: DdLogsReader, resources: ResourceManager
+ ) -> None:
+ """One successful STREAMED /v1/responses call must reach real DataDog
+ as exactly one log event whose payload carries the model, the token
+ counts aggregated across the stream, stream=true, and a response cost
+ equal to the /spend/logs row for the same call."""
+ _assert_datadog_configured(client)
+
+ key = client.key_with_alias(f"dd-stream-responses-{unique_marker()}", models=[CHEAP_OPENAI_MODEL])
+ resources.defer(lambda: client.delete_key(key))
+
+ marker = unique_marker()
+ outcome = first_ok(
+ client,
+ lambda: client.responses_raw(key, CHEAP_OPENAI_MODEL, f"reply with one word {marker}", stream=True),
+ )
+ assert outcome.is_streaming, f"response must be an event stream, got content-type {outcome.content_type!r}"
+ assert outcome.chunks > 0, "the stream must deliver at least one event"
+ assert outcome.stream_error is None, (
+ f"the stream carried an upstream error event despite the 200: {outcome.stream_error}"
+ )
+
+ spend_row = client.poll_proxy_spend_for_key(key)
+ assert spend_row is not None and spend_row.spend is not None and spend_row.spend > 0, (
+ f"the streamed call must record a positive-spend row, got {spend_row!r}"
+ )
+ events = dd_logs.poll_events_for_marker(marker)
+ payload = _assert_exactly_one_event(
+ events,
+ model_group=CHEAP_OPENAI_MODEL,
+ call_type="aresponses",
+ cost_anchor=spend_row.spend,
+ expect_stream=True,
+ )
+ assert spend_row.total_tokens is not None, (
+ "the spend row must record total_tokens for the token cross-check"
+ )
+ assert spend_row.total_tokens == payload.total_tokens, (
+ f"the spend row and the DataDog event must agree on tokens: "
+ f"{spend_row.total_tokens} vs {payload.total_tokens}"
)