-
Notifications
You must be signed in to change notification settings - Fork 262
Expand file tree
/
Copy pathtest_propagate_attributes.py
More file actions
3058 lines (2605 loc) · 124 KB
/
test_propagate_attributes.py
File metadata and controls
3058 lines (2605 loc) · 124 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Comprehensive tests for propagate_attributes functionality.
This module tests the propagate_attributes context manager that allows setting
trace-level attributes (user_id, session_id, metadata) that automatically propagate
to all child spans within the context.
"""
import concurrent.futures
import time
from datetime import datetime
import pytest
from opentelemetry.instrumentation.threading import ThreadingInstrumentor
from langfuse import propagate_attributes
from langfuse._client.attributes import LangfuseOtelSpanAttributes, _serialize
from langfuse._client.constants import LANGFUSE_SDK_EXPERIMENT_ENVIRONMENT
from langfuse._client.datasets import DatasetClient
from langfuse.api import Dataset, DatasetItem, DatasetStatus
from tests.test_otel import TestOTelBase
class TestPropagateAttributesBase(TestOTelBase):
"""Base class for propagate_attributes tests with shared helper methods."""
@pytest.fixture
def langfuse_client(self, monkeypatch, tracer_provider, mock_processor_init):
"""Create a mocked Langfuse client with explicit tracer_provider for testing."""
from langfuse import Langfuse
# Set environment variables
monkeypatch.setenv("LANGFUSE_PUBLIC_KEY", "test-public-key")
monkeypatch.setenv("LANGFUSE_SECRET_KEY", "test-secret-key")
# Create test client with explicit tracer_provider
client = Langfuse(
public_key="test-public-key",
secret_key="test-secret-key",
host="http://test-host",
tracing_enabled=True,
tracer_provider=tracer_provider, # Pass the test provider explicitly
)
yield client
def get_span_by_name(self, memory_exporter, name: str) -> dict:
"""Get single span by name (assert exactly one exists).
Args:
memory_exporter: The in-memory span exporter fixture
name: The name of the span to retrieve
Returns:
dict: The span data as a dictionary
Raises:
AssertionError: If zero or more than one span with the name exists
"""
spans = self.get_spans_by_name(memory_exporter, name)
assert len(spans) > 0, f"Expected at least 1 span named '{name}'"
return spans[0]
def verify_missing_attribute(self, span_data: dict, attr_key: str):
"""Verify that a span does NOT have a specific attribute.
Args:
span_data: The span data dictionary
attr_key: The attribute key to check for absence
Raises:
AssertionError: If the attribute exists on the span
"""
attributes = span_data["attributes"]
assert attr_key not in attributes, (
f"Attribute '{attr_key}' should NOT be on span '{span_data['name']}'"
)
class TestPropagateAttributesBasic(TestPropagateAttributesBase):
"""Tests for basic propagate_attributes functionality."""
def test_user_id_propagates_to_child_spans(self, langfuse_client, memory_exporter):
"""Verify user_id propagates to all child spans within context."""
with langfuse_client.start_as_current_observation(name="parent-span"):
with propagate_attributes(user_id="test_user_123"):
child1 = langfuse_client.start_observation(name="child-span-1")
child1.end()
child2 = langfuse_client.start_observation(name="child-span-2")
child2.end()
# Verify both children have user_id
child1_span = self.get_span_by_name(memory_exporter, "child-span-1")
self.verify_span_attribute(
child1_span,
LangfuseOtelSpanAttributes.TRACE_USER_ID,
"test_user_123",
)
child2_span = self.get_span_by_name(memory_exporter, "child-span-2")
self.verify_span_attribute(
child2_span,
LangfuseOtelSpanAttributes.TRACE_USER_ID,
"test_user_123",
)
def test_session_id_propagates_to_child_spans(
self, langfuse_client, memory_exporter
):
"""Verify session_id propagates to all child spans within context."""
with langfuse_client.start_as_current_observation(name="parent-span"):
with propagate_attributes(session_id="session_abc"):
child1 = langfuse_client.start_observation(name="child-span-1")
child1.end()
child2 = langfuse_client.start_observation(name="child-span-2")
child2.end()
# Verify both children have session_id
child1_span = self.get_span_by_name(memory_exporter, "child-span-1")
self.verify_span_attribute(
child1_span,
LangfuseOtelSpanAttributes.TRACE_SESSION_ID,
"session_abc",
)
child2_span = self.get_span_by_name(memory_exporter, "child-span-2")
self.verify_span_attribute(
child2_span,
LangfuseOtelSpanAttributes.TRACE_SESSION_ID,
"session_abc",
)
def test_metadata_propagates_to_child_spans(self, langfuse_client, memory_exporter):
"""Verify metadata propagates to all child spans within context."""
with langfuse_client.start_as_current_observation(name="parent-span"):
with propagate_attributes(
metadata={"experiment": "variant_a", "version": "1.0"}
):
child1 = langfuse_client.start_observation(name="child-span-1")
child1.end()
child2 = langfuse_client.start_observation(name="child-span-2")
child2.end()
# Verify both children have metadata
child1_span = self.get_span_by_name(memory_exporter, "child-span-1")
self.verify_span_attribute(
child1_span,
f"{LangfuseOtelSpanAttributes.TRACE_METADATA}.experiment",
"variant_a",
)
self.verify_span_attribute(
child1_span,
f"{LangfuseOtelSpanAttributes.TRACE_METADATA}.version",
"1.0",
)
child2_span = self.get_span_by_name(memory_exporter, "child-span-2")
self.verify_span_attribute(
child2_span,
f"{LangfuseOtelSpanAttributes.TRACE_METADATA}.experiment",
"variant_a",
)
self.verify_span_attribute(
child2_span,
f"{LangfuseOtelSpanAttributes.TRACE_METADATA}.version",
"1.0",
)
def test_all_attributes_propagate_together(self, langfuse_client, memory_exporter):
"""Verify user_id, session_id, and metadata all propagate together."""
with langfuse_client.start_as_current_observation(name="parent-span"):
with propagate_attributes(
user_id="user_123",
session_id="session_abc",
metadata={"experiment": "test", "env": "prod"},
):
child = langfuse_client.start_observation(name="child-span")
child.end()
# Verify child has all attributes
child_span = self.get_span_by_name(memory_exporter, "child-span")
self.verify_span_attribute(
child_span, LangfuseOtelSpanAttributes.TRACE_USER_ID, "user_123"
)
self.verify_span_attribute(
child_span, LangfuseOtelSpanAttributes.TRACE_SESSION_ID, "session_abc"
)
self.verify_span_attribute(
child_span,
f"{LangfuseOtelSpanAttributes.TRACE_METADATA}.experiment",
"test",
)
self.verify_span_attribute(
child_span,
f"{LangfuseOtelSpanAttributes.TRACE_METADATA}.env",
"prod",
)
class TestPropagateAttributesHierarchy(TestPropagateAttributesBase):
"""Tests for propagation across span hierarchies."""
def test_propagation_to_direct_children(self, langfuse_client, memory_exporter):
"""Verify attributes propagate to all direct children."""
with langfuse_client.start_as_current_observation(name="parent-span"):
with propagate_attributes(user_id="user_123"):
child1 = langfuse_client.start_observation(name="child-1")
child1.end()
child2 = langfuse_client.start_observation(name="child-2")
child2.end()
child3 = langfuse_client.start_observation(name="child-3")
child3.end()
# Verify all three children have user_id
for i in range(1, 4):
child_span = self.get_span_by_name(memory_exporter, f"child-{i}")
self.verify_span_attribute(
child_span, LangfuseOtelSpanAttributes.TRACE_USER_ID, "user_123"
)
def test_propagation_to_grandchildren(self, langfuse_client, memory_exporter):
"""Verify attributes propagate through multiple levels of nesting."""
with langfuse_client.start_as_current_observation(name="parent-span"):
with propagate_attributes(user_id="user_123", session_id="session_abc"):
with langfuse_client.start_as_current_observation(name="child-span"):
grandchild = langfuse_client.start_observation(
name="grandchild-span"
)
grandchild.end()
# Verify all three levels have attributes
parent_span = self.get_span_by_name(memory_exporter, "parent-span")
child_span = self.get_span_by_name(memory_exporter, "child-span")
grandchild_span = self.get_span_by_name(memory_exporter, "grandchild-span")
for span in [parent_span, child_span, grandchild_span]:
self.verify_span_attribute(
span, LangfuseOtelSpanAttributes.TRACE_USER_ID, "user_123"
)
self.verify_span_attribute(
span, LangfuseOtelSpanAttributes.TRACE_SESSION_ID, "session_abc"
)
def test_propagation_across_observation_types(
self, langfuse_client, memory_exporter
):
"""Verify attributes propagate to different observation types."""
with langfuse_client.start_as_current_observation(name="parent-span"):
with propagate_attributes(user_id="user_123"):
# Create span
span = langfuse_client.start_observation(name="test-span")
span.end()
# Create generation
generation = langfuse_client.start_observation(
as_type="generation", name="test-generation"
)
generation.end()
# Verify both observation types have user_id
span_data = self.get_span_by_name(memory_exporter, "test-span")
self.verify_span_attribute(
span_data, LangfuseOtelSpanAttributes.TRACE_USER_ID, "user_123"
)
generation_data = self.get_span_by_name(memory_exporter, "test-generation")
self.verify_span_attribute(
generation_data, LangfuseOtelSpanAttributes.TRACE_USER_ID, "user_123"
)
class TestPropagateAttributesTiming(TestPropagateAttributesBase):
"""Critical tests for early vs late propagation timing."""
def test_early_propagation_all_spans_covered(
self, langfuse_client, memory_exporter
):
"""Verify setting attributes early covers all child spans."""
with langfuse_client.start_as_current_observation(name="parent-span"):
# Set attributes BEFORE creating any children
with propagate_attributes(user_id="user_123"):
child1 = langfuse_client.start_observation(name="child-1")
child1.end()
child2 = langfuse_client.start_observation(name="child-2")
child2.end()
child3 = langfuse_client.start_observation(name="child-3")
child3.end()
# Verify ALL children have user_id
for i in range(1, 4):
child_span = self.get_span_by_name(memory_exporter, f"child-{i}")
self.verify_span_attribute(
child_span, LangfuseOtelSpanAttributes.TRACE_USER_ID, "user_123"
)
def test_late_propagation_only_future_spans_covered(
self, langfuse_client, memory_exporter
):
"""Verify late propagation only affects spans created after context entry."""
with langfuse_client.start_as_current_observation(name="parent-span"):
# Create child1 BEFORE propagate_attributes
child1 = langfuse_client.start_observation(name="child-1")
child1.end()
# NOW set attributes
with propagate_attributes(user_id="user_123"):
# Create child2 AFTER propagate_attributes
child2 = langfuse_client.start_observation(name="child-2")
child2.end()
# Verify: child1 does NOT have user_id, child2 DOES
child1_span = self.get_span_by_name(memory_exporter, "child-1")
self.verify_missing_attribute(
child1_span, LangfuseOtelSpanAttributes.TRACE_USER_ID
)
child2_span = self.get_span_by_name(memory_exporter, "child-2")
self.verify_span_attribute(
child2_span, LangfuseOtelSpanAttributes.TRACE_USER_ID, "user_123"
)
def test_current_span_gets_attributes(self, langfuse_client, memory_exporter):
"""Verify the currently active span gets attributes when propagate_attributes is called."""
with langfuse_client.start_as_current_observation(name="parent-span"):
# Call propagate_attributes while parent-span is active
with propagate_attributes(user_id="user_123"):
pass
# Verify parent span itself has the attribute
parent_span = self.get_span_by_name(memory_exporter, "parent-span")
self.verify_span_attribute(
parent_span, LangfuseOtelSpanAttributes.TRACE_USER_ID, "user_123"
)
def test_spans_outside_context_unaffected(self, langfuse_client, memory_exporter):
"""Verify spans created outside context don't get attributes."""
with langfuse_client.start_as_current_observation(name="parent-span"):
# Span before context
span1 = langfuse_client.start_observation(name="span-1")
span1.end()
# Span inside context
with propagate_attributes(user_id="user_123"):
span2 = langfuse_client.start_observation(name="span-2")
span2.end()
# Span after context
span3 = langfuse_client.start_observation(name="span-3")
span3.end()
# Verify: only span2 has user_id
span1_data = self.get_span_by_name(memory_exporter, "span-1")
self.verify_missing_attribute(
span1_data, LangfuseOtelSpanAttributes.TRACE_USER_ID
)
span2_data = self.get_span_by_name(memory_exporter, "span-2")
self.verify_span_attribute(
span2_data, LangfuseOtelSpanAttributes.TRACE_USER_ID, "user_123"
)
span3_data = self.get_span_by_name(memory_exporter, "span-3")
self.verify_missing_attribute(
span3_data, LangfuseOtelSpanAttributes.TRACE_USER_ID
)
class TestPropagateAttributesValidation(TestPropagateAttributesBase):
"""Tests for validation of propagated attribute values."""
def test_user_id_over_200_chars_dropped(self, langfuse_client, memory_exporter):
"""Verify user_id over 200 characters is dropped with warning."""
long_user_id = "x" * 201
with langfuse_client.start_as_current_observation(name="parent-span"):
with propagate_attributes(user_id=long_user_id):
child = langfuse_client.start_observation(name="child-span")
child.end()
# Verify child does NOT have user_id
child_span = self.get_span_by_name(memory_exporter, "child-span")
self.verify_missing_attribute(
child_span, LangfuseOtelSpanAttributes.TRACE_USER_ID
)
def test_session_id_over_200_chars_dropped(self, langfuse_client, memory_exporter):
"""Verify session_id over 200 characters is dropped with warning."""
long_session_id = "y" * 201
with langfuse_client.start_as_current_observation(name="parent-span"):
with propagate_attributes(session_id=long_session_id):
child = langfuse_client.start_observation(name="child-span")
child.end()
# Verify child does NOT have session_id
child_span = self.get_span_by_name(memory_exporter, "child-span")
self.verify_missing_attribute(
child_span, LangfuseOtelSpanAttributes.TRACE_SESSION_ID
)
def test_metadata_value_over_200_chars_dropped(
self, langfuse_client, memory_exporter
):
"""Verify metadata values over 200 characters are dropped with warning."""
with langfuse_client.start_as_current_observation(name="parent-span"):
with propagate_attributes(metadata={"key": "z" * 201}):
child = langfuse_client.start_observation(name="child-span")
child.end()
# Verify child does NOT have metadata.key
child_span = self.get_span_by_name(memory_exporter, "child-span")
self.verify_missing_attribute(
child_span, f"{LangfuseOtelSpanAttributes.TRACE_METADATA}.key"
)
def test_exactly_200_chars_accepted(self, langfuse_client, memory_exporter):
"""Verify exactly 200 characters is accepted (boundary test)."""
user_id_200 = "x" * 200
with langfuse_client.start_as_current_observation(name="parent-span"):
with propagate_attributes(user_id=user_id_200):
child = langfuse_client.start_observation(name="child-span")
child.end()
# Verify child HAS user_id
child_span = self.get_span_by_name(memory_exporter, "child-span")
self.verify_span_attribute(
child_span, LangfuseOtelSpanAttributes.TRACE_USER_ID, user_id_200
)
def test_201_chars_rejected(self, langfuse_client, memory_exporter):
"""Verify 201 characters is rejected (boundary test)."""
user_id_201 = "x" * 201
with langfuse_client.start_as_current_observation(name="parent-span"):
with propagate_attributes(user_id=user_id_201):
child = langfuse_client.start_observation(name="child-span")
child.end()
# Verify child does NOT have user_id
child_span = self.get_span_by_name(memory_exporter, "child-span")
self.verify_missing_attribute(
child_span, LangfuseOtelSpanAttributes.TRACE_USER_ID
)
def test_non_string_user_id_dropped(self, langfuse_client, memory_exporter):
"""Verify non-string user_id is dropped with warning."""
with langfuse_client.start_as_current_observation(name="parent-span"):
with propagate_attributes(user_id=12345): # type: ignore
child = langfuse_client.start_observation(name="child-span")
child.end()
# Verify child does NOT have user_id
child_span = self.get_span_by_name(memory_exporter, "child-span")
self.verify_missing_attribute(
child_span, LangfuseOtelSpanAttributes.TRACE_USER_ID
)
def test_mixed_valid_invalid_metadata(self, langfuse_client, memory_exporter):
"""Verify mixed valid/invalid metadata - valid entries kept, invalid dropped."""
with langfuse_client.start_as_current_observation(name="parent-span"):
with propagate_attributes(
metadata={
"valid_key": "valid_value",
"invalid_key": "x" * 201, # Too long
"another_valid": "ok",
}
):
child = langfuse_client.start_observation(name="child-span")
child.end()
# Verify: valid keys present, invalid key absent
child_span = self.get_span_by_name(memory_exporter, "child-span")
self.verify_span_attribute(
child_span,
f"{LangfuseOtelSpanAttributes.TRACE_METADATA}.valid_key",
"valid_value",
)
self.verify_span_attribute(
child_span,
f"{LangfuseOtelSpanAttributes.TRACE_METADATA}.another_valid",
"ok",
)
self.verify_missing_attribute(
child_span, f"{LangfuseOtelSpanAttributes.TRACE_METADATA}.invalid_key"
)
class TestPropagateAttributesNesting(TestPropagateAttributesBase):
"""Tests for nested propagate_attributes contexts."""
def test_nested_contexts_inner_overwrites(self, langfuse_client, memory_exporter):
"""Verify inner context overwrites outer context values."""
with langfuse_client.start_as_current_observation(name="parent-span"):
with propagate_attributes(user_id="user1"):
# Create span in outer context
span1 = langfuse_client.start_observation(name="span-1")
span1.end()
# Inner context with different user_id
with propagate_attributes(user_id="user2"):
span2 = langfuse_client.start_observation(name="span-2")
span2.end()
# Verify: span1 has user1, span2 has user2
span1_data = self.get_span_by_name(memory_exporter, "span-1")
self.verify_span_attribute(
span1_data, LangfuseOtelSpanAttributes.TRACE_USER_ID, "user1"
)
span2_data = self.get_span_by_name(memory_exporter, "span-2")
self.verify_span_attribute(
span2_data, LangfuseOtelSpanAttributes.TRACE_USER_ID, "user2"
)
def test_after_inner_context_outer_restored(self, langfuse_client, memory_exporter):
"""Verify outer context is restored after exiting inner context."""
with langfuse_client.start_as_current_observation(name="parent-span"):
with propagate_attributes(user_id="user1"):
# Span in outer context
span1 = langfuse_client.start_observation(name="span-1")
span1.end()
# Inner context
with propagate_attributes(user_id="user2"):
span2 = langfuse_client.start_observation(name="span-2")
span2.end()
# Back to outer context
span3 = langfuse_client.start_observation(name="span-3")
span3.end()
# Verify: span1 and span3 have user1, span2 has user2
span1_data = self.get_span_by_name(memory_exporter, "span-1")
self.verify_span_attribute(
span1_data, LangfuseOtelSpanAttributes.TRACE_USER_ID, "user1"
)
span2_data = self.get_span_by_name(memory_exporter, "span-2")
self.verify_span_attribute(
span2_data, LangfuseOtelSpanAttributes.TRACE_USER_ID, "user2"
)
span3_data = self.get_span_by_name(memory_exporter, "span-3")
self.verify_span_attribute(
span3_data, LangfuseOtelSpanAttributes.TRACE_USER_ID, "user1"
)
def test_nested_different_attributes(self, langfuse_client, memory_exporter):
"""Verify nested contexts with different attributes merge correctly."""
with langfuse_client.start_as_current_observation(name="parent-span"):
with propagate_attributes(user_id="user1"):
# Inner context adds session_id
with propagate_attributes(session_id="session1"):
span = langfuse_client.start_observation(name="span-1")
span.end()
# Verify: span has BOTH user_id and session_id
span_data = self.get_span_by_name(memory_exporter, "span-1")
self.verify_span_attribute(
span_data, LangfuseOtelSpanAttributes.TRACE_USER_ID, "user1"
)
self.verify_span_attribute(
span_data, LangfuseOtelSpanAttributes.TRACE_SESSION_ID, "session1"
)
def test_nested_metadata_merges_additively(self, langfuse_client, memory_exporter):
"""Verify nested contexts merge metadata keys additively."""
with langfuse_client.start_as_current_observation(name="parent-span"):
with propagate_attributes(metadata={"env": "prod", "region": "us-east"}):
# Outer span should have outer metadata
outer_span = langfuse_client.start_observation(name="outer-span")
outer_span.end()
# Inner context adds more metadata
with propagate_attributes(
metadata={"experiment": "A", "version": "2.0"}
):
inner_span = langfuse_client.start_observation(name="inner-span")
inner_span.end()
# Back to outer context
after_span = langfuse_client.start_observation(name="after-span")
after_span.end()
# Verify: outer span has only outer metadata
outer_span_data = self.get_span_by_name(memory_exporter, "outer-span")
self.verify_span_attribute(
outer_span_data,
f"{LangfuseOtelSpanAttributes.TRACE_METADATA}.env",
"prod",
)
self.verify_span_attribute(
outer_span_data,
f"{LangfuseOtelSpanAttributes.TRACE_METADATA}.region",
"us-east",
)
self.verify_missing_attribute(
outer_span_data, f"{LangfuseOtelSpanAttributes.TRACE_METADATA}.experiment"
)
# Verify: inner span has ALL metadata (merged)
inner_span_data = self.get_span_by_name(memory_exporter, "inner-span")
self.verify_span_attribute(
inner_span_data,
f"{LangfuseOtelSpanAttributes.TRACE_METADATA}.env",
"prod",
)
self.verify_span_attribute(
inner_span_data,
f"{LangfuseOtelSpanAttributes.TRACE_METADATA}.region",
"us-east",
)
self.verify_span_attribute(
inner_span_data,
f"{LangfuseOtelSpanAttributes.TRACE_METADATA}.experiment",
"A",
)
self.verify_span_attribute(
inner_span_data,
f"{LangfuseOtelSpanAttributes.TRACE_METADATA}.version",
"2.0",
)
# Verify: after span has only outer metadata (inner context exited)
after_span_data = self.get_span_by_name(memory_exporter, "after-span")
self.verify_span_attribute(
after_span_data,
f"{LangfuseOtelSpanAttributes.TRACE_METADATA}.env",
"prod",
)
self.verify_span_attribute(
after_span_data,
f"{LangfuseOtelSpanAttributes.TRACE_METADATA}.region",
"us-east",
)
self.verify_missing_attribute(
after_span_data, f"{LangfuseOtelSpanAttributes.TRACE_METADATA}.experiment"
)
def test_nested_metadata_inner_overwrites_conflicting_keys(
self, langfuse_client, memory_exporter
):
"""Verify nested contexts: inner metadata overwrites outer for same keys."""
with langfuse_client.start_as_current_observation(name="parent-span"):
with propagate_attributes(
metadata={"env": "staging", "version": "1.0", "region": "us-west"}
):
# Inner context overwrites some keys
with propagate_attributes(
metadata={"env": "production", "experiment": "B"}
):
span = langfuse_client.start_observation(name="span-1")
span.end()
# Verify: inner values overwrite outer for conflicting keys
span_data = self.get_span_by_name(memory_exporter, "span-1")
# Overwritten key
self.verify_span_attribute(
span_data,
f"{LangfuseOtelSpanAttributes.TRACE_METADATA}.env",
"production", # Inner value wins
)
# Preserved keys from outer
self.verify_span_attribute(
span_data,
f"{LangfuseOtelSpanAttributes.TRACE_METADATA}.version",
"1.0", # From outer
)
self.verify_span_attribute(
span_data,
f"{LangfuseOtelSpanAttributes.TRACE_METADATA}.region",
"us-west", # From outer
)
# New key from inner
self.verify_span_attribute(
span_data,
f"{LangfuseOtelSpanAttributes.TRACE_METADATA}.experiment",
"B", # From inner
)
def test_triple_nested_metadata_accumulates(self, langfuse_client, memory_exporter):
"""Verify metadata accumulates across three levels of nesting."""
with langfuse_client.start_as_current_observation(name="parent-span"):
with propagate_attributes(metadata={"level": "1", "a": "outer"}):
with propagate_attributes(metadata={"level": "2", "b": "middle"}):
with propagate_attributes(metadata={"level": "3", "c": "inner"}):
span = langfuse_client.start_observation(name="deep-span")
span.end()
# Verify: deepest span has all metadata with innermost level winning
span_data = self.get_span_by_name(memory_exporter, "deep-span")
# Conflicting key: innermost wins
self.verify_span_attribute(
span_data,
f"{LangfuseOtelSpanAttributes.TRACE_METADATA}.level",
"3",
)
# Unique keys from each level
self.verify_span_attribute(
span_data,
f"{LangfuseOtelSpanAttributes.TRACE_METADATA}.a",
"outer",
)
self.verify_span_attribute(
span_data,
f"{LangfuseOtelSpanAttributes.TRACE_METADATA}.b",
"middle",
)
self.verify_span_attribute(
span_data,
f"{LangfuseOtelSpanAttributes.TRACE_METADATA}.c",
"inner",
)
def test_metadata_merge_with_empty_inner(self, langfuse_client, memory_exporter):
"""Verify empty inner metadata dict doesn't clear outer metadata."""
with langfuse_client.start_as_current_observation(name="parent-span"):
with propagate_attributes(metadata={"key1": "value1", "key2": "value2"}):
# Inner context with empty metadata
with propagate_attributes(metadata={}):
span = langfuse_client.start_observation(name="span-1")
span.end()
# Verify: outer metadata is preserved
span_data = self.get_span_by_name(memory_exporter, "span-1")
self.verify_span_attribute(
span_data,
f"{LangfuseOtelSpanAttributes.TRACE_METADATA}.key1",
"value1",
)
self.verify_span_attribute(
span_data,
f"{LangfuseOtelSpanAttributes.TRACE_METADATA}.key2",
"value2",
)
def test_metadata_merge_preserves_user_session(
self, langfuse_client, memory_exporter
):
"""Verify metadata merging doesn't affect user_id/session_id."""
with langfuse_client.start_as_current_observation(name="parent-span"):
with propagate_attributes(
user_id="user1",
session_id="session1",
metadata={"outer": "value"},
):
with propagate_attributes(metadata={"inner": "value"}):
span = langfuse_client.start_observation(name="span-1")
span.end()
# Verify: user_id and session_id are preserved, metadata merged
span_data = self.get_span_by_name(memory_exporter, "span-1")
self.verify_span_attribute(
span_data, LangfuseOtelSpanAttributes.TRACE_USER_ID, "user1"
)
self.verify_span_attribute(
span_data, LangfuseOtelSpanAttributes.TRACE_SESSION_ID, "session1"
)
self.verify_span_attribute(
span_data,
f"{LangfuseOtelSpanAttributes.TRACE_METADATA}.outer",
"value",
)
self.verify_span_attribute(
span_data,
f"{LangfuseOtelSpanAttributes.TRACE_METADATA}.inner",
"value",
)
class TestPropagateAttributesEdgeCases(TestPropagateAttributesBase):
"""Tests for edge cases and unusual scenarios."""
def test_propagate_attributes_with_no_args(self, langfuse_client, memory_exporter):
"""Verify calling propagate_attributes() with no args doesn't error."""
with langfuse_client.start_as_current_observation(name="parent-span"):
with propagate_attributes():
child = langfuse_client.start_observation(name="child-span")
child.end()
# Should not crash, spans created normally
child_span = self.get_span_by_name(memory_exporter, "child-span")
assert child_span is not None
def test_none_values_ignored(self, langfuse_client, memory_exporter):
"""Verify None values are ignored without error."""
with langfuse_client.start_as_current_observation(name="parent-span"):
with propagate_attributes(user_id=None, session_id=None, metadata=None):
child = langfuse_client.start_observation(name="child-span")
child.end()
# Should not crash, no attributes set
child_span = self.get_span_by_name(memory_exporter, "child-span")
self.verify_missing_attribute(
child_span, LangfuseOtelSpanAttributes.TRACE_USER_ID
)
self.verify_missing_attribute(
child_span, LangfuseOtelSpanAttributes.TRACE_SESSION_ID
)
def test_empty_metadata_dict(self, langfuse_client, memory_exporter):
"""Verify empty metadata dict doesn't cause errors."""
with langfuse_client.start_as_current_observation(name="parent-span"):
with propagate_attributes(metadata={}):
child = langfuse_client.start_observation(name="child-span")
child.end()
# Should not crash, no metadata attributes set
child_span = self.get_span_by_name(memory_exporter, "child-span")
assert child_span is not None
def test_all_invalid_metadata_values(self, langfuse_client, memory_exporter):
"""Verify all invalid metadata values results in no metadata attributes."""
with langfuse_client.start_as_current_observation(name="parent-span"):
with propagate_attributes(
metadata={
"key1": "x" * 201, # Too long
"key2": "y" * 201, # Too long
}
):
child = langfuse_client.start_observation(name="child-span")
child.end()
# No metadata attributes should be set
child_span = self.get_span_by_name(memory_exporter, "child-span")
self.verify_missing_attribute(
child_span, f"{LangfuseOtelSpanAttributes.TRACE_METADATA}.key1"
)
self.verify_missing_attribute(
child_span, f"{LangfuseOtelSpanAttributes.TRACE_METADATA}.key2"
)
def test_non_string_metadata_values_coerced(
self, langfuse_client, memory_exporter
):
"""Verify non-string metadata values are coerced to strings, not dropped.
LangGraph injects int/list/tuple metadata (langgraph_step, langgraph_triggers,
langgraph_path) which should be coerced per the v3->v4 migration guide.
See: https://github.com/langfuse/langfuse-python/issues/1571
"""
with langfuse_client.start_as_current_observation(name="parent-span"):
with propagate_attributes(
metadata={
"langgraph_step": 3,
"langgraph_triggers": ["start:__start__"],
"langgraph_path": ("__pregel_pull", "agent"),
"string_key": "normal_value",
}
):
child = langfuse_client.start_observation(name="child-span")
child.end()
child_span = self.get_span_by_name(memory_exporter, "child-span")
# Non-string values should be coerced to strings
self.verify_span_attribute(
child_span,
f"{LangfuseOtelSpanAttributes.TRACE_METADATA}.langgraph_step",
"3",
)
self.verify_span_attribute(
child_span,
f"{LangfuseOtelSpanAttributes.TRACE_METADATA}.langgraph_triggers",
"['start:__start__']",
)
self.verify_span_attribute(
child_span,
f"{LangfuseOtelSpanAttributes.TRACE_METADATA}.langgraph_path",
"('__pregel_pull', 'agent')",
)
# String values should pass through unchanged
self.verify_span_attribute(
child_span,
f"{LangfuseOtelSpanAttributes.TRACE_METADATA}.string_key",
"normal_value",
)
def test_propagate_with_no_active_span(self, langfuse_client, memory_exporter):
"""Verify propagate_attributes works even with no active span."""
# Call propagate_attributes without creating a parent span first
with propagate_attributes(user_id="user_123"):
# Now create a span
with langfuse_client.start_as_current_observation(name="span-1"):
pass
# Should not crash, span should have user_id
span_data = self.get_span_by_name(memory_exporter, "span-1")
self.verify_span_attribute(
span_data, LangfuseOtelSpanAttributes.TRACE_USER_ID, "user_123"
)
class TestPropagateAttributesFormat(TestPropagateAttributesBase):
"""Tests for correct attribute formatting and naming."""
def test_user_id_uses_correct_attribute_name(
self, langfuse_client, memory_exporter
):
"""Verify user_id uses the correct OTel attribute name."""
with langfuse_client.start_as_current_observation(name="parent-span"):
with propagate_attributes(user_id="user_123"):
child = langfuse_client.start_observation(name="child-span")
child.end()
child_span = self.get_span_by_name(memory_exporter, "child-span")
# Verify the exact attribute key is used
assert LangfuseOtelSpanAttributes.TRACE_USER_ID in child_span["attributes"]
assert (
child_span["attributes"][LangfuseOtelSpanAttributes.TRACE_USER_ID]
== "user_123"
)
def test_session_id_uses_correct_attribute_name(
self, langfuse_client, memory_exporter
):
"""Verify session_id uses the correct OTel attribute name."""
with langfuse_client.start_as_current_observation(name="parent-span"):
with propagate_attributes(session_id="session_abc"):
child = langfuse_client.start_observation(name="child-span")
child.end()
child_span = self.get_span_by_name(memory_exporter, "child-span")
# Verify the exact attribute key is used
assert LangfuseOtelSpanAttributes.TRACE_SESSION_ID in child_span["attributes"]
assert (
child_span["attributes"][LangfuseOtelSpanAttributes.TRACE_SESSION_ID]
== "session_abc"
)
def test_metadata_keys_properly_prefixed(self, langfuse_client, memory_exporter):
"""Verify metadata keys are properly prefixed with TRACE_METADATA."""
with langfuse_client.start_as_current_observation(name="parent-span"):
with propagate_attributes(
metadata={"experiment": "A", "version": "1.0", "env": "prod"}
):
child = langfuse_client.start_observation(name="child-span")
child.end()
child_span = self.get_span_by_name(memory_exporter, "child-span")
attributes = child_span["attributes"]
# Verify each metadata key is properly prefixed
expected_keys = [
f"{LangfuseOtelSpanAttributes.TRACE_METADATA}.experiment",
f"{LangfuseOtelSpanAttributes.TRACE_METADATA}.version",
f"{LangfuseOtelSpanAttributes.TRACE_METADATA}.env",
]
for key in expected_keys:
assert key in attributes, f"Expected key '{key}' not found in attributes"
def test_multiple_metadata_keys_independent(self, langfuse_client, memory_exporter):
"""Verify multiple metadata keys are stored as independent attributes."""
with langfuse_client.start_as_current_observation(name="parent-span"):
with propagate_attributes(metadata={"k1": "v1", "k2": "v2", "k3": "v3"}):
child = langfuse_client.start_observation(name="child-span")
child.end()
child_span = self.get_span_by_name(memory_exporter, "child-span")
attributes = child_span["attributes"]
# Verify all three are separate attributes with correct values
assert attributes[f"{LangfuseOtelSpanAttributes.TRACE_METADATA}.k1"] == "v1"
assert attributes[f"{LangfuseOtelSpanAttributes.TRACE_METADATA}.k2"] == "v2"
assert attributes[f"{LangfuseOtelSpanAttributes.TRACE_METADATA}.k3"] == "v3"
class TestPropagateAttributesThreading(TestPropagateAttributesBase):
"""Tests for propagate_attributes with ThreadPoolExecutor."""
@pytest.fixture(autouse=True)
def instrument_threading(self):
"""Auto-instrument threading for all tests in this class."""
instrumentor = ThreadingInstrumentor()
instrumentor.instrument()
yield
instrumentor.uninstrument()
def test_propagation_with_threadpoolexecutor(
self, langfuse_client, memory_exporter
):
"""Verify attributes propagate from main thread to worker threads."""
def worker_function(span_name: str):
"""Worker creates a span in thread pool."""
span = langfuse_client.start_observation(name=span_name)
span.end()