litellm/tests/integration/observability/test_langfuse_otel_metadata_identity.py
devin-ai-integration[bot] 1171273511
fix(langfuse otel): emit request metadata under langfuse.observation.metadata and langfuse.trace.metadata on the OTEL v2 Langfuse mapper (#42697)
* fix(langfuse_otel): emit request metadata under langfuse.observation.metadata and langfuse.trace.metadata keys

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* fix(langfuse_otel): name trace metadata identity keys after their request metadata fields

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* fix(langfuse_otel): type metadata helper and drop null fields so they cannot clobber caller trace metadata

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test(langfuse_otel): annotate new request metadata tests

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test(langfuse_otel): build rig config and wire batches immutably

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* fix(langfuse_otel): skip empty trace identity values so teamless requests cannot erase attribution

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test(langfuse_otel): drain wire batches per poll instead of accumulating

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test(langfuse_otel): cover null stripping and empty trace identities

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test(langfuse_otel): set redaction flag directly instead of monkeypatching

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test(langfuse_otel): add integration audit matrix for langfuse metadata keys

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test(langfuse_otel): tighten audit chaos and unauthenticated cells

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test(langfuse_otel): restore contracts.json formatting

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test(langfuse_otel): close SDK clients, pin worker identity, and normalize response id matching

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test(langfuse_otel): gate the slow sink reply instead of sleeping

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* fix(otel v2): emit request metadata and identity under langfuse.observation.metadata and langfuse.trace.metadata

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* fix(otel v2): satisfy type discipline gate for metadata export

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test: drop prohibited covers markers from langfuse otel integration tests

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* fix(otel): put the mutable-ok suppression on the dict construction line the type-discipline gate reports

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* fix(langfuse otel): share request metadata export across callbacks

* fix(langfuse otel): drop prompt variables, MCP tool I/O and vector store queries from exported request metadata

* fix(langfuse_otel): keep span export alive when nested request metadata has non-string keys

The content strip validated prompt_management_metadata, mcp_tool_call_metadata
and vector_store_request_metadata items as str-keyed mappings, so an SDK
caller passing one with a non-string key raised inside
exported_request_metadata: OTEL v2 dropped the LLM span for every vendor and
v1 langfuse_otel lost the request metadata and every attribute after it.
Validate those nested mappings with object keys instead. Also hoists the
langfuse_otel imports.

* fix(langfuse_otel): send the request metadata blob to Langfuse destinations only

- A requester_metadata that is not a mapping no longer raises. The v2 LLM span
  (every vendor) and the v1 Langfuse attributes survive it again.
- Prompt-quoting routing_decision fields stay out of langfuse.observation.metadata.
- An exporter or key/team destination for any other backend drops
  langfuse.observation.metadata and langfuse.trace.metadata.user_api_key_*, as on
  main. This covers a collector folded into the Langfuse logger.
- The v2 Langfuse key-set pin in the arize family test gains the two new keys.

* fix(langfuse_otel): export only caller identity under the Langfuse metadata keys

- The Langfuse metadata keys carried the whole request metadata. On OTel v2 that
  sent request headers, caller metadata, user email, user agent and auth metadata
  to a Langfuse destination that never received them on main; on v1 it doubled
  each span's metadata payload, so big caller metadata doubled the export size
- Both paths now export only the key alias, user, end user, team, team alias and
  org. On v2 that is the team plus the identity among the operator's
  `baggage_metadata_keys`, which v2 spans already carry as `litellm.metadata.*`.
  Everything else stays in the bare `metadata` attribute, as on main
- `output_messages` returns a list again, and the arize v2 b3 key pin is back to
  main's set

* fix(langfuse_otel): drop the caller identity first when a span hits its attribute limit

v1 wrote the identity attributes after the OpenInference ones, so a span near the
128-attribute limit (about 33+ tools) evicted openinference.span.kind, metadata
and llm.model_name instead. The identity now goes first on a fresh span, so the
SDK evicts it before anything else, and a caller's active span that already
carries attributes does not get it.

v2 sheds the Langfuse identity keys before any indexed message attribute when a
span is over budget, so a span keeps every attribute it carried without them.

* fix(langfuse_otel): keep other spans and dropped counts as main exports them

- v1 writes the caller identity only into the room the span's attribute
  limit leaves next to the error attributes a failed call adds, so the
  exported dropped-attribute count matches main
- v2 strips the Langfuse request metadata only from LiteLLM's own spans;
  application, instrumentation and server spans keep every key they set
- a stripped v2 span keeps the dropped attribute, event and link counts
- a config that lists the Langfuse mapper without the langfuse_otel
  exporter also keeps the request metadata away from other exporters

* fix(langfuse_otel): keep the caller identity off the caller's active span

v1 writes LiteLLM's attributes onto the caller's active span when one is
current instead of starting its own span. That span goes to the caller's
own exporter, so the identity keys reached a non-Langfuse collector and
could take attribute slots the caller fills later. The identity keys now
go only on the span LiteLLM starts, whatever the caller's span carries.

* fix(langfuse otel): keep the identity keys on the OTEL v2 Langfuse mapper only

The v1 langfuse_otel callback goes back to main: it sends no
langfuse.observation.metadata or langfuse.trace.metadata.user_api_key_*
keys. The OTEL v2 Langfuse mapper keeps them. The integration cells now
run every endpoint, client, redaction, failure and chaos case on v2.

* test(langfuse otel): count only accepted batches in the sink outage cell

The wire also records the batches the sink answered 503, so an exporter
retry made a span look exported twice. The chaos cells now also check the
spans that landed carry the caller identity.

* test(langfuse otel): split stacked span comprehensions and drop constant comments

* test(langfuse otel): split the metadata integration module into focused files

* fix(langfuse otel): send the org id in trace metadata too

The trace metadata keys now reuse IDENTITY_METADATA_FIELDS, so a key in an org gets langfuse.trace.metadata.user_api_key_org_id next to the generation's org id.

---------

Co-authored-by: yucheng <yucheng@berri.ai>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-27 18:54:10 -07:00

416 lines
17 KiB
Python

import json
import uuid
from collections.abc import Callable, Mapping, Sequence
from pathlib import Path
from typing import Final
import pytest
from _langfuse_otel_metadata_support import (
EXPORTED_FIELDS,
IDENTITIES,
assert_identity,
chat_identity_fields,
decoded_response_id,
exported_llm_span,
langfuse_rig,
scenario_identity,
span_response_id,
watched_spans,
)
from integration._support.client import Gateway, eventually
def test_langfuse_otel_failure_span_carries_request_metadata(gateway: Gateway, tmp_path: Path) -> None:
marker: Final = "lf-fail-" + uuid.uuid4().hex
with (
langfuse_rig(gateway, tmp_path, {}, marker) as rig,
rig.candidate.scenario() as scenario,
):
key, identity = scenario_identity(scenario, rig.provider)
response: Final = rig.candidate.request(
"POST",
"/v1/chat/completions",
{
"model": identity["model"],
"messages": [{"role": "user", "content": f"{marker} scripted -fail- upstream"}],
"user": identity["end_user"],
"cache": {"no-cache": True},
},
key=key,
)
assert response.status_code >= 500, response.text
def failed_calls(spans: Sequence[Mapping[str, object]]) -> tuple[Mapping[str, object], ...]:
return tuple(
span
for span in spans
if span.get("langfuse.trace.metadata.team_id") == identity["team_id"] and "error.type" in span
)
failed: Final = failed_calls(
eventually(watched_spans(rig.collector), lambda spans: bool(failed_calls(spans)), seconds=25)
)
for attrs in failed:
assert_identity(attrs, chat_identity_fields(identity))
def test_langfuse_otel_oversized_caller_metadata_is_not_copied_into_the_langfuse_keys(
gateway: Gateway, tmp_path: Path
) -> None:
marker: Final = "lf-bigmeta-" + uuid.uuid4().hex
spend_logs_metadata: Final = {
"blob": "x" * 5000,
"count": 7,
"steps": ["a", "b"],
"nested": {"inner": {"leaf": True}},
}
caller_note: Final = "y" * 50000
with (
langfuse_rig(gateway, tmp_path, {}, marker) as rig,
rig.candidate.scenario() as scenario,
):
key, identity = scenario_identity(scenario, rig.provider, spend_logs_metadata=spend_logs_metadata)
response: Final = rig.candidate.request(
"POST",
"/v1/chat/completions",
{
"model": identity["model"],
"messages": [{"role": "user", "content": marker}],
"user": identity["end_user"],
"metadata": {"caller_note": caller_note},
"cache": {"no-cache": True},
},
key=key,
)
assert response.status_code == 200, response.text
attrs: Final = exported_llm_span(rig.collector, response.json()["id"])
assert_identity(attrs, chat_identity_fields(identity))
assert len(str(attrs["langfuse.observation.metadata"])) < 1000, len(str(attrs["langfuse.observation.metadata"]))
langfuse_metadata: Final = json.dumps(
{
name: value
for name, value in attrs.items()
if name == "langfuse.observation.metadata" or name.startswith("langfuse.trace.metadata.")
}
)
assert caller_note not in langfuse_metadata, len(langfuse_metadata)
assert spend_logs_metadata["blob"] not in langfuse_metadata, len(langfuse_metadata)
def test_langfuse_otel_unauthenticated_request_leaks_no_identity(gateway: Gateway, tmp_path: Path) -> None:
marker: Final = "lf-unauth-" + uuid.uuid4().hex
with (
langfuse_rig(gateway, tmp_path, {}, marker) as rig,
rig.candidate.scenario() as scenario,
):
key, identity = scenario_identity(scenario, rig.provider)
denied: Final = rig.candidate.client.post(
"/v1/chat/completions",
json={
"model": identity["model"],
"messages": [{"role": "user", "content": f"{marker}-denied"}],
},
headers={},
)
assert denied.status_code == 401, denied.text
watch: Final = watched_spans(rig.collector)
first: Final = rig.candidate.request(
"POST",
"/v1/chat/completions",
{
"model": identity["model"],
"messages": [{"role": "user", "content": marker}],
"cache": {"no-cache": True},
},
key=key,
)
assert first.status_code == 200, first.text
first_id: Final = first.json()["id"]
eventually(watch, lambda spans: sum(span_response_id(s) == first_id for s in spans) == 1, seconds=25)
second: Final = rig.candidate.request(
"POST",
"/v1/chat/completions",
{
"model": identity["model"],
"messages": [{"role": "user", "content": marker + "-settle"}],
"cache": {"no-cache": True},
},
key=key,
)
assert second.status_code == 200, second.text
second_id: Final = second.json()["id"]
settled: Final = eventually(
watch, lambda spans: sum(span_response_id(s) == second_id for s in spans) == 1, seconds=25
)
carriers: Final = tuple(
span_response_id(span)
for span in settled
if "langfuse.observation.metadata" in span
or any(name.startswith("langfuse.trace.metadata.user_api_key_") for name in span)
)
assert sorted(carriers, key=str) == sorted((first_id, second_id)), carriers
def test_langfuse_otel_v2_mapper_emits_request_metadata_and_identity(gateway: Gateway, tmp_path: Path) -> None:
marker: Final = "lf-v2-" + uuid.uuid4().hex
with (
langfuse_rig(
gateway,
tmp_path,
{},
marker,
) as rig,
rig.candidate.scenario() as scenario,
):
key, identity = scenario_identity(scenario, rig.provider)
response: Final = rig.candidate.request(
"POST",
"/v1/chat/completions",
{
"model": identity["model"],
"messages": [{"role": "user", "content": marker}],
"user": identity["end_user"],
"cache": {"no-cache": True},
},
key=key,
)
assert response.status_code == 200, response.text
watch: Final = watched_spans(rig.collector)
observed: Final = eventually(
watch,
lambda spans: sum(s.get("gen_ai.response.id") == response.json()["id"] for s in spans) == 1,
seconds=25,
)
attrs: Final = next(s for s in observed if s.get("gen_ai.response.id") == response.json()["id"])
assert attrs.get("langfuse.trace.metadata.team_id") == identity["team_id"], attrs
assert attrs.get("langfuse.trace.metadata.team_alias") == identity["team_alias"], attrs
assert "langfuse.observation.metadata" in attrs, sorted(attrs)
observation: Final = json.loads(str(attrs["langfuse.observation.metadata"]))
expected: Final = chat_identity_fields(identity)
assert {key: observation.get(key) for key in expected} == dict(expected), observation
assert set(observation) <= EXPORTED_FIELDS, observation
flattened: Final = {
attribute: attrs.get(attribute)
for attribute in (f"langfuse.trace.metadata.{field}" for field in IDENTITIES)
if attribute in attrs
}
assert flattened == {f"langfuse.trace.metadata.{field}": value for field, value in expected.items()}, attrs
def test_langfuse_otel_v2_mapper_redacts_user_api_key_fields(gateway: Gateway, tmp_path: Path) -> None:
marker: Final = "lf-v2-redact-" + uuid.uuid4().hex
with (
langfuse_rig(
gateway,
tmp_path,
{"redact_user_api_key_info": True},
marker,
) as rig,
rig.candidate.scenario() as scenario,
):
key: Final = scenario.key(
key_alias="lf-v2-redact-" + uuid.uuid4().hex,
metadata={"spend_logs_metadata": {"ticket": "LIT-8283"}},
)
model: Final = scenario.model(api_base=rig.provider.url + "/v1")
response: Final = rig.candidate.request(
"POST",
"/v1/chat/completions",
{
"model": model,
"messages": [{"role": "user", "content": marker}],
"cache": {"no-cache": True},
},
key=key,
)
assert response.status_code == 200, response.text
watch: Final = watched_spans(rig.collector)
observed: Final = eventually(
watch,
lambda spans: sum(s.get("gen_ai.response.id") == response.json()["id"] for s in spans) == 1,
seconds=25,
)
attrs: Final = next(s for s in observed if s.get("gen_ai.response.id") == response.json()["id"])
assert "langfuse.observation.metadata" not in attrs, attrs["langfuse.observation.metadata"]
assert not [name for name in attrs if name.startswith("langfuse.trace.metadata.user_api_key_")], sorted(attrs)
def test_langfuse_otel_v2_mapper_teamless_key_emits_no_team_identity(gateway: Gateway, tmp_path: Path) -> None:
marker: Final = "lf-v2-noteam-" + uuid.uuid4().hex
with (
langfuse_rig(
gateway,
tmp_path,
{},
marker,
) as rig,
rig.candidate.scenario() as scenario,
):
key, identity = scenario_identity(scenario, rig.provider, team=False)
response: Final = rig.candidate.request(
"POST",
"/v1/chat/completions",
{
"model": identity["model"],
"messages": [{"role": "user", "content": marker}],
"cache": {"no-cache": True},
},
key=key,
)
assert response.status_code == 200, response.text
watch: Final = watched_spans(rig.collector)
observed: Final = eventually(
watch,
lambda spans: sum(s.get("gen_ai.response.id") == response.json()["id"] for s in spans) == 1,
seconds=25,
)
attrs: Final = next(s for s in observed if s.get("gen_ai.response.id") == response.json()["id"])
assert "langfuse.observation.metadata" in attrs, sorted(attrs)
observation: Final = json.loads(str(attrs["langfuse.observation.metadata"]))
for field in ("user_api_key_team_id", "user_api_key_team_alias", "user_api_key_end_user_id"):
assert field not in observation, observation
assert set(observation) <= EXPORTED_FIELDS, observation
assert {
attribute: attrs.get(attribute)
for attribute in (f"langfuse.trace.metadata.{field}" for field in IDENTITIES)
if attribute in attrs
} == {"langfuse.trace.metadata.user_api_key_alias": identity["key_alias"]}, attrs
@pytest.mark.parametrize("route", ["/v1/chat/completions", "/v1/messages", "/v1/responses"])
def test_otel_v2_langfuse_gets_no_request_headers_or_caller_metadata(
route: str, gateway: Gateway, tmp_path: Path
) -> None:
marker: Final = "lf-v2-probe-" + uuid.uuid4().hex
probe: Final = "lf-probe-" + uuid.uuid4().hex
with (
langfuse_rig(gateway, tmp_path, {}, marker) as rig,
rig.candidate.scenario() as scenario,
):
key, identity = scenario_identity(scenario, rig.provider)
model: Final = (
scenario.model(model="anthropic/claude-sonnet-4-6", api_base=rig.provider.url)
if route == "/v1/messages"
else identity["model"]
)
body: Final = {
"/v1/chat/completions": {
"model": model,
"messages": [{"role": "user", "content": marker}],
"metadata": {"caller_note": probe},
"cache": {"no-cache": True},
},
"/v1/messages": {
"model": model,
"max_tokens": 16,
"messages": [{"role": "user", "content": marker}],
"litellm_metadata": {"caller_note": probe},
},
"/v1/responses": {"model": model, "input": marker, "litellm_metadata": {"caller_note": probe}},
}[route]
watch: Final = watched_spans(rig.collector)
response: Final = rig.candidate.request("POST", route, body, key=key, headers={"x-lit8283-probe": probe})
assert response.status_code == 200, response.text
settle: Final = rig.candidate.request(
"POST",
"/v1/chat/completions",
{
"model": identity["model"],
"messages": [{"role": "user", "content": marker}],
"cache": {"no-cache": True},
},
key=key,
)
assert settle.status_code == 200, settle.text
def llm_span(spans: Sequence[Mapping[str, object]], response_id: str) -> Mapping[str, object] | None:
return next(
(
span
for span in spans
if decoded_response_id(span.get("gen_ai.response.id")) == decoded_response_id(response_id)
),
None,
)
exported: Final = eventually(
watch,
lambda spans: (
llm_span(spans, response.json()["id"]) is not None and llm_span(spans, settle.json()["id"]) is not None
),
seconds=25,
)
attrs: Final = llm_span(exported, response.json()["id"])
assert attrs is not None
observation: Final = json.loads(str(attrs["langfuse.observation.metadata"]))
assert observation["user_api_key_alias"] == identity["key_alias"], observation
assert set(observation) <= EXPORTED_FIELDS, observation
assert not [span for span in exported if probe in json.dumps(span, default=str)], exported
def _keyword_router(router: str, keyword: str) -> Callable[[str], Sequence[Mapping[str, object]]]:
def models(provider_url: str) -> Sequence[Mapping[str, object]]:
tier: Final = f"{router}-tier"
return (
{
"model_name": tier,
"litellm_params": {
"model": "openai/gpt-4o-mini",
"api_key": "integration-provider-key",
"api_base": provider_url + "/v1",
},
},
{
"model_name": router,
"litellm_params": {
"model": "auto_router/complexity_router",
"complexity_router_config": {
"classifier_type": "heuristic",
"keyword_tier_rules": [{"keywords": [keyword], "tier": "REASONING"}],
"tiers": {"SIMPLE": tier, "MEDIUM": tier, "COMPLEX": tier, "REASONING": tier},
},
},
},
)
return models
def test_langfuse_otel_metadata_omits_prompt_quoting_routing_fields(gateway: Gateway, tmp_path: Path) -> None:
marker: Final = "lf-route-" + uuid.uuid4().hex
router: Final = "lf-router-" + uuid.uuid4().hex[:8]
keyword: Final = "acquire-globex-" + uuid.uuid4().hex[:8]
with (
langfuse_rig(
gateway,
tmp_path,
{},
marker,
overrides={"OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT": "no_content"},
model_list=_keyword_router(router, keyword),
) as rig,
rig.candidate.scenario() as scenario,
):
key: Final = scenario.key(key_alias="lf-route-" + uuid.uuid4().hex)
response: Final = rig.candidate.request(
"POST",
"/v1/chat/completions",
{
"model": router,
"messages": [{"role": "user", "content": f"{marker} please {keyword} now"}],
"cache": {"no-cache": True},
},
key=key,
)
assert response.status_code == 200, response.text
attrs: Final = exported_llm_span(rig.collector, response.json()["id"])
observation: Final = json.loads(str(attrs["langfuse.observation.metadata"]))
assert set(observation) <= EXPORTED_FIELDS, observation
langfuse_metadata: Final = {
name: value
for name, value in attrs.items()
if name == "langfuse.observation.metadata" or name.startswith("langfuse.trace.metadata.")
}
assert keyword not in json.dumps(langfuse_metadata, default=str), langfuse_metadata
assert keyword not in json.dumps(attrs, default=str), attrs