Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(llm-gateway): join events to access logs; own the span id (#91919)

Brandon57a3cc568fa9
diff --git a/services/llm-gateway/src/llm_gateway/callbacks/posthog.py b/services/llm-gateway/src/llm_gateway/callbacks/posthog.py
index 631c42299422..98a6bc909087 100644
--- a/services/llm-gateway/src/llm_gateway/callbacks/posthog.py
+++ b/services/llm-gateway/src/llm_gateway/callbacks/posthog.py
@@ -19,6 +19,7 @@ from llm_gateway.request_context import (
get_posthog_flags,
get_posthog_properties,
get_product,
+ get_request_id,
get_time_to_first_token,
get_traceparent_trace_id,
)
@@ -79,13 +80,25 @@ def _apply_owned_event_properties(
) -> None:
"""Enforce gateway-owned event properties, run after caller `x-posthog-property-*` headers are merged.
- `ai_product`, `$ai_billable`, and `$ai_effort` are gateway-derived (effort via
+ `ai_product`, `$ai_billable`, `$ai_effort`, and `$ai_span_id` are gateway-derived (effort via
`ProviderConfig.extract_effort`) and must not be spoofable via headers, so we re-assert them
- here and drop `$ai_effort` when the gateway found none. OAuth requests use the authenticated
- project as `team_id`; trusted server callers can attribute usage to a customer team.
+ here and drop `$ai_effort` when the gateway found none. `llm_gateway_request_id` is re-asserted
+ too, but its value is not unique: the caller's `x-request-id` when sent, a truncated uuid
+ otherwise. OAuth requests use the authenticated project as `team_id`; trusted server callers
+ can attribute usage to a customer team.
"""
properties["ai_product"] = product
properties["$ai_billable"] = _is_product_billable(product)
+ # Unique per event: one request can emit several (a provider fallback, a retry) and
+ # consumers key on this, so a shared value collapses them.
+ properties["$ai_span_id"] = str(uuid4())
+ # Joins an event to its gateway access log line. Named apart from capture's signed
+ # `$ai_gateway_request_id`, which carries a different trust model.
+ request_id = get_request_id()
+ if request_id:
+ properties["llm_gateway_request_id"] = request_id
+ else:
+ properties.pop("llm_gateway_request_id", None)
effort = get_effort()
if effort is not None:
properties["$ai_effort"] = effort
@@ -235,7 +248,6 @@ class PostHogCallback(InstrumentedCallback):
"$ai_latency": standard_logging_object.get("response_time", 0.0),
"$ai_stream": is_streaming,
"$ai_trace_id": trace_id,
- "$ai_span_id": str(uuid4()),
# Stamped explicitly to bypass the SDK's group_type_index lookup.
# The AI usage report hardcodes `$group_1` (posthog/tasks/usage_report.py)
# so the gateway must guarantee that slot regardless of how the
diff --git a/services/llm-gateway/tests/callbacks/test_posthog.py b/services/llm-gateway/tests/callbacks/test_posthog.py
index e77c52f82817..a57e3c085585 100644
--- a/services/llm-gateway/tests/callbacks/test_posthog.py
+++ b/services/llm-gateway/tests/callbacks/test_posthog.py
@@ -13,6 +13,7 @@ from llm_gateway.callbacks.posthog import (
_replace_binary_content,
_truncate_for_capture,
)
+from llm_gateway.request_context import RequestContext, set_request_context
def _is_uuid(value: str) -> bool:
@@ -233,6 +234,114 @@ class TestPostHogCallback:
expected_groups["project"] = team_id
assert call_kwargs["groups"] == expected_groups
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("event_method", ["_on_success", "_on_failure"])
+ async def test_llm_gateway_request_id_joins_events_to_the_access_log(
+ self,
+ callback: PostHogCallback,
+ standard_logging_object: dict,
+ mock_posthog_client: tuple,
+ auth_user: AuthenticatedUser,
+ event_method: str,
+ ) -> None:
+ """Both paths carry the join key, read from a real request context rather than a stub."""
+ _, mock_client = mock_posthog_client
+ kwargs = {"standard_logging_object": standard_logging_object, "litellm_params": {}}
+ set_request_context(RequestContext(request_id="req-abc-123"))
+
+ with patch("llm_gateway.callbacks.posthog.get_auth_user", return_value=auth_user):
+ await getattr(callback, event_method)(kwargs, None, 0.0, 1.0, end_user_id=None)
+
+ assert mock_client.capture.call_args.kwargs["properties"]["llm_gateway_request_id"] == "req-abc-123"
+
+ @pytest.mark.asyncio
+ async def test_span_id_is_unique_per_event_within_one_request(
+ self,
+ callback: PostHogCallback,
+ standard_logging_object: dict,
+ mock_posthog_client: tuple,
+ auth_user: AuthenticatedUser,
+ ) -> None:
+ """A provider fallback or a retry emits two events under one request context.
+
+ Span ids must still differ: the trace view keys on `$ai_span_id`, so a shared
+ value collapses one event into the other. The request id here is UUID-shaped
+ because callers send `x-request-id` that way, which leaves the inequality
+ rather than the shape check as the assertion carrying the invariant.
+ """
+ _, mock_client = mock_posthog_client
+ kwargs = {"standard_logging_object": standard_logging_object, "litellm_params": {}}
+ request_id = "bdf42359-9364-4db7-8958-c001f28c9255"
+ set_request_context(RequestContext(request_id=request_id))
+
+ with patch("llm_gateway.callbacks.posthog.get_auth_user", return_value=auth_user):
+ await callback._on_failure(kwargs, None, 0.0, 1.0, end_user_id=None)
+ await callback._on_success(kwargs, None, 0.0, 1.0, end_user_id=None)
+
+ captured = [call.kwargs["properties"] for call in mock_client.capture.call_args_list]
+ assert len(captured) == 2
+ assert all(_is_uuid(p["$ai_span_id"]) for p in captured)
+ assert captured[0]["$ai_span_id"] != captured[1]["$ai_span_id"]
+ assert all(p["$ai_span_id"] != request_id for p in captured)
+ assert [p["llm_gateway_request_id"] for p in captured] == [request_id, request_id]
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("event_method", ["_on_success", "_on_failure"])
+ async def test_request_id_is_dropped_without_a_request_context(
+ self,
+ callback: PostHogCallback,
+ standard_logging_object: dict,
+ mock_posthog_client: tuple,
+ auth_user: AuthenticatedUser,
+ event_method: str,
+ ) -> None:
+ """No request context means no join key, and a caller cannot supply one instead."""
+ _, mock_client = mock_posthog_client
+ kwargs = {"standard_logging_object": standard_logging_object, "litellm_params": {}}
+ set_request_context(RequestContext(request_id=""))
+
+ with (
+ patch("llm_gateway.callbacks.posthog.get_auth_user", return_value=auth_user),
+ patch(
+ "llm_gateway.callbacks.posthog.get_posthog_properties",
+ return_value={"llm_gateway_request_id": "caller-supplied"},
+ ),
+ ):
+ await getattr(callback, event_method)(kwargs, None, 0.0, 1.0, end_user_id=None)
+
+ properties = mock_client.capture.call_args.kwargs["properties"]
+ assert "llm_gateway_request_id" not in properties
+ assert _is_uuid(properties["$ai_span_id"])
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("event_method", ["_on_success", "_on_failure"])
+ async def test_caller_cannot_override_the_gateway_owned_ids(
+ self,
+ callback: PostHogCallback,
+ standard_logging_object: dict,
+ mock_posthog_client: tuple,
+ auth_user: AuthenticatedUser,
+ event_method: str,
+ ) -> None:
+ """`x-posthog-property-*` merges before the owned properties are re-asserted."""
+ _, mock_client = mock_posthog_client
+ kwargs = {"standard_logging_object": standard_logging_object, "litellm_params": {}}
+ set_request_context(RequestContext(request_id="req-abc-123"))
+
+ with (
+ patch("llm_gateway.callbacks.posthog.get_auth_user", return_value=auth_user),
+ patch(
+ "llm_gateway.callbacks.posthog.get_posthog_properties",
+ return_value={"llm_gateway_request_id": "spoofed", "$ai_span_id": "collapsed"},
+ ),
+ ):
+ await getattr(callback, event_method)(kwargs, None, 0.0, 1.0, end_user_id=None)
+
+ properties = mock_client.capture.call_args.kwargs["properties"]
+ assert properties["llm_gateway_request_id"] == "req-abc-123"
+ assert properties["$ai_span_id"] != "collapsed"
+ assert _is_uuid(properties["$ai_span_id"])
+
@pytest.mark.asyncio
async def test_on_success_invalid_header_team_id_falls_back_to_auth_team(
self,