Skip to content

Commit d210b49

Browse files
committed
chore: update test cases and cleanup
1 parent 8b09a9b commit d210b49

File tree

4 files changed

+55
-58
lines changed

4 files changed

+55
-58
lines changed

langfuse/_client/client.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,9 @@
4848
ObservationTypeLiteralNoEvent,
4949
ObservationTypeSpanLike,
5050
get_observation_types_list,
51+
LANGFUSE_CTX_USER_ID,
52+
LANGFUSE_CTX_SESSION_ID,
53+
LANGFUSE_CTX_METADATA,
5154
)
5255
from langfuse._client.datasets import DatasetClient, DatasetItemClient
5356
from langfuse._client.environment_variables import (
@@ -116,12 +119,6 @@
116119
from langfuse.types import MaskFunction, ScoreDataType, SpanLevel, TraceContext
117120

118121

119-
# Context key constants for Langfuse context propagation
120-
LANGFUSE_CTX_USER_ID = "langfuse.ctx.user.id"
121-
LANGFUSE_CTX_SESSION_ID = "langfuse.ctx.session.id"
122-
LANGFUSE_CTX_METADATA = "langfuse.ctx.metadata"
123-
124-
125122
class Langfuse:
126123
"""Main client for Langfuse tracing and platform features.
127124

langfuse/_client/constants.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,11 @@
88

99
LANGFUSE_TRACER_NAME = "langfuse-sdk"
1010

11+
# Context key constants for Langfuse context propagation
12+
LANGFUSE_CTX_USER_ID = "langfuse.ctx.user.id"
13+
LANGFUSE_CTX_SESSION_ID = "langfuse.ctx.session.id"
14+
LANGFUSE_CTX_METADATA = "langfuse.ctx.metadata"
15+
1116

1217
"""Note: this type is used with .__args__ / get_args in some cases and therefore must remain flat"""
1318
ObservationTypeGenerationLike: TypeAlias = Literal[

langfuse/_client/span_processor.py

Lines changed: 25 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,12 @@
2222
from opentelemetry.sdk.trace import ReadableSpan, Span
2323
from opentelemetry.sdk.trace.export import BatchSpanProcessor
2424

25-
from langfuse._client.constants import LANGFUSE_TRACER_NAME
25+
from langfuse._client.constants import (
26+
LANGFUSE_TRACER_NAME,
27+
LANGFUSE_CTX_USER_ID,
28+
LANGFUSE_CTX_SESSION_ID,
29+
LANGFUSE_CTX_METADATA,
30+
)
2631
from langfuse._client.environment_variables import (
2732
LANGFUSE_FLUSH_AT,
2833
LANGFUSE_FLUSH_INTERVAL,
@@ -31,11 +36,6 @@
3136
from langfuse._client.utils import span_formatter
3237
from langfuse.logger import langfuse_logger
3338
from langfuse.version import __version__ as langfuse_version
34-
from langfuse._client.client import (
35-
LANGFUSE_CTX_USER_ID,
36-
LANGFUSE_CTX_SESSION_ID,
37-
LANGFUSE_CTX_METADATA,
38-
)
3939

4040

4141
class LangfuseSpanProcessor(BatchSpanProcessor):
@@ -143,10 +143,11 @@ def on_start(self, span: Span, parent_context: Optional[Context] = None) -> None
143143
# 1. Propagate all baggage keys as span attributes
144144
baggage_entries = baggage.get_all(context=current_context)
145145
for key, value in baggage_entries.items():
146-
# Check if this baggage entry is already present as a span attribute
147-
if not hasattr(span.attributes, key) or (
148-
span.attributes is not None and span.attributes.get(key) != value
149-
):
146+
# Only propagate user.id, session.id and langfuse.metadata.* as those are set by us on the baggage
147+
if key.startswith("langfuse.metadata.") or key in [
148+
"user.id",
149+
"session.id",
150+
]:
150151
propagated_attributes[key] = value
151152
langfuse_logger.debug(
152153
f"Propagated baggage key '{key}' = '{value}' to span '{span.name}'"
@@ -160,16 +161,10 @@ def on_start(self, span: Span, parent_context: Optional[Context] = None) -> None
160161
if value is not None:
161162
# Convert context key to span attribute name (remove langfuse.ctx. prefix)
162163
attr_key = ctx_key.replace("langfuse.ctx.", "")
163-
164-
# Only propagate if not already set on span
165-
if not hasattr(span.attributes, attr_key) or (
166-
span.attributes is not None
167-
and span.attributes.get(attr_key) != value
168-
):
169-
propagated_attributes[attr_key] = value
170-
langfuse_logger.debug(
171-
f"Propagated context key '{ctx_key}' = '{value}' to span '{span.name}'"
172-
)
164+
propagated_attributes[attr_key] = value
165+
langfuse_logger.debug(
166+
f"Propagated context key '{ctx_key}' = '{value}' to span '{span.name}'"
167+
)
173168
except Exception as e:
174169
langfuse_logger.debug(f"Could not read context key '{ctx_key}': {e}")
175170

@@ -184,24 +179,17 @@ def on_start(self, span: Span, parent_context: Optional[Context] = None) -> None
184179
for key, value in metadata_dict.items():
185180
attr_key = f"langfuse.metadata.{key}"
186181

187-
# Convert value to appropriate type for span attribute
188-
if isinstance(value, (str, int, float, bool)):
189-
attr_value = value
190-
else:
191-
# For complex types, convert to JSON string
192-
attr_value = json.dumps(value)
193-
194-
# Only propagate if not already set or different
195-
existing_value = (
196-
span.attributes.get(attr_key)
197-
if hasattr(span, "attributes") and span.attributes is not None
198-
else None
182+
# Convert value to appropriate type for span attribute (naive or json stringify)
183+
attr_value = (
184+
value
185+
if isinstance(value, (str, int, float, bool))
186+
else json.dumps(value)
187+
)
188+
189+
propagated_attributes[attr_key] = attr_value
190+
langfuse_logger.debug(
191+
f"Propagated metadata key '{key}' = '{attr_value}' to span '{span.name}'"
199192
)
200-
if existing_value != attr_value:
201-
propagated_attributes[attr_key] = attr_value
202-
langfuse_logger.debug(
203-
f"Propagated metadata key '{key}' = '{attr_value}' to span '{span.name}'"
204-
)
205193
except Exception as e:
206194
langfuse_logger.debug(f"Could not read metadata from context: {e}")
207195

tests/test_core_sdk.py

Lines changed: 22 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2071,7 +2071,7 @@ def test_context_manager_user_propagation():
20712071
user_id = "test_user_123"
20722072

20732073
with langfuse.start_as_current_span(name="parent-span") as parent_span:
2074-
with langfuse.user(id=user_id):
2074+
with langfuse.with_attributes(user_id=user_id):
20752075
trace_id = parent_span.trace_id
20762076

20772077
# Create child spans that should inherit user_id
@@ -2107,7 +2107,7 @@ def test_context_manager_session_propagation():
21072107
session_id = "test_session_456"
21082108

21092109
with langfuse.start_as_current_span(name="parent-span") as parent_span:
2110-
with langfuse.session(id=session_id):
2110+
with langfuse.with_attributes(session_id=session_id):
21112111
trace_id = parent_span.trace_id
21122112

21132113
# Create child spans that should inherit session_id
@@ -2142,8 +2142,12 @@ def test_context_manager_metadata_propagation():
21422142
langfuse = Langfuse()
21432143

21442144
with langfuse.start_as_current_span(name="parent-span") as parent_span:
2145-
with langfuse.metadata(
2146-
experiment="A/B", version="1.2.3", feature_flag="enabled"
2145+
with langfuse.with_attributes(
2146+
metadata={
2147+
"experiment": "A/B",
2148+
"version": "1.2.3",
2149+
"feature_flag": "enabled",
2150+
}
21472151
):
21482152
trace_id = parent_span.trace_id
21492153

@@ -2185,17 +2189,18 @@ def test_context_manager_nested_contexts():
21852189
langfuse = Langfuse()
21862190

21872191
with langfuse.start_as_current_span(name="outer-span") as outer_span:
2188-
with langfuse.user(id="user_1"):
2189-
with langfuse.session(id="session_1"):
2190-
with langfuse.metadata(env="prod", region="us-east"):
2191-
outer_trace_id = outer_span.trace_id
2192+
with langfuse.with_attributes(user_id="user_1", session_id="session_1"):
2193+
with langfuse.with_attributes(
2194+
metadata={"env": "prod", "region": "us-east"}
2195+
):
2196+
outer_trace_id = outer_span.trace_id
21922197

2193-
# Create span in outer context
2194-
outer_child = langfuse.start_span(name="outer-child")
2195-
outer_child.end()
2198+
# Create span in outer context
2199+
outer_child = langfuse.start_span(name="outer-child")
2200+
outer_child.end()
21962201

2197-
nested_span = langfuse.start_span(name="nested-span")
2198-
nested_span.end()
2202+
nested_span = langfuse.start_span(name="nested-span")
2203+
nested_span.end()
21992204

22002205
langfuse.flush()
22012206
sleep(2)
@@ -2229,8 +2234,10 @@ def test_context_manager_baggage_propagation():
22292234

22302235
# Test with baggage enabled (careful with sensitive data)
22312236
with langfuse.start_as_current_span(name="service-span") as span:
2232-
with langfuse.session(id="public_session_789", as_baggage=True):
2233-
with langfuse.metadata(as_baggage=True, service="api", version="v1.0"):
2237+
with langfuse.with_attributes(session_id="public_session_789", as_baggage=True):
2238+
with langfuse.with_attributes(
2239+
as_baggage=True, metadata={"service": "api", "version": "v1.0"}
2240+
):
22342241
trace_id = span.trace_id
22352242

22362243
# Create child spans that inherit baggage context

0 commit comments

Comments
 (0)