-
Notifications
You must be signed in to change notification settings - Fork 262
Expand file tree
/
Copy pathtest_batch_evaluation.py
More file actions
1103 lines (836 loc) · 35.2 KB
/
test_batch_evaluation.py
File metadata and controls
1103 lines (836 loc) · 35.2 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 batch evaluation functionality.
This test suite covers the run_batched_evaluation method which allows evaluating
traces, observations, and sessions fetched from Langfuse with mappers, evaluators,
and composite evaluators.
"""
import asyncio
import time
import pytest
from langfuse import get_client
from langfuse.batch_evaluation import (
BatchEvaluationResult,
BatchEvaluationResumeToken,
EvaluatorInputs,
EvaluatorStats,
)
from langfuse.experiment import Evaluation
from tests.utils import create_uuid
# ============================================================================
# FIXTURES & SETUP
# ============================================================================
# pytestmark = pytest.mark.skip(reason="Github CI runner overwhelmed by score volume")
@pytest.fixture
def langfuse_client():
"""Get a Langfuse client for testing."""
return get_client()
@pytest.fixture
def sample_trace_name():
"""Generate a unique trace name for filtering."""
return f"batch-eval-test-{create_uuid()}"
def simple_trace_mapper(*, item):
"""Simple mapper for traces."""
return EvaluatorInputs(
input=item.input if hasattr(item, "input") else None,
output=item.output if hasattr(item, "output") else None,
expected_output=None,
metadata={"trace_id": item.id},
)
def simple_evaluator(*, input, output, expected_output=None, metadata=None, **kwargs):
"""Simple evaluator that returns a score based on output length."""
if output is None:
return Evaluation(name="length_score", value=0.0, comment="No output")
return Evaluation(
name="length_score",
value=float(len(str(output))) / 10.0,
comment=f"Length: {len(str(output))}",
)
# ============================================================================
# BASIC FUNCTIONALITY TESTS
# ============================================================================
def test_run_batched_evaluation_on_observations_basic(langfuse_client):
"""Test basic batch evaluation on traces."""
result = langfuse_client.run_batched_evaluation(
scope="observations",
mapper=simple_trace_mapper,
evaluators=[simple_evaluator],
max_items=1,
verbose=True,
)
# Validate result structure
assert isinstance(result, BatchEvaluationResult)
assert result.total_items_fetched >= 0
assert result.total_items_processed >= 0
assert result.total_scores_created >= 0
assert result.completed is True
assert isinstance(result.duration_seconds, float)
assert result.duration_seconds > 0
# Verify evaluator stats
assert len(result.evaluator_stats) == 1
stats = result.evaluator_stats[0]
assert isinstance(stats, EvaluatorStats)
assert stats.name == "simple_evaluator"
def test_run_batched_evaluation_on_traces_basic(langfuse_client):
"""Test basic batch evaluation on traces."""
result = langfuse_client.run_batched_evaluation(
scope="traces",
mapper=simple_trace_mapper,
evaluators=[simple_evaluator],
max_items=5,
verbose=True,
)
# Validate result structure
assert isinstance(result, BatchEvaluationResult)
assert result.total_items_fetched >= 0
assert result.total_items_processed >= 0
assert result.total_scores_created >= 0
assert result.completed is True
assert isinstance(result.duration_seconds, float)
assert result.duration_seconds > 0
# Verify evaluator stats
assert len(result.evaluator_stats) == 1
stats = result.evaluator_stats[0]
assert isinstance(stats, EvaluatorStats)
assert stats.name == "simple_evaluator"
def test_batch_evaluation_with_filter(langfuse_client):
"""Test batch evaluation with JSON filter."""
# Create a trace with specific tag
unique_tag = f"test-filter-{create_uuid()}"
with langfuse_client.start_as_current_span(
name=f"filtered-trace-{create_uuid()}"
) as span:
span.update_trace(
input="Filtered test",
output="Filtered output",
tags=[unique_tag],
)
langfuse_client.flush()
time.sleep(3)
# Filter format: array of filter conditions
filter_json = f'[{{"type": "arrayOptions", "column": "tags", "operator": "any of", "value": ["{unique_tag}"]}}]'
result = langfuse_client.run_batched_evaluation(
scope="traces",
mapper=simple_trace_mapper,
evaluators=[simple_evaluator],
filter=filter_json,
verbose=True,
)
# Should only process the filtered trace
assert result.total_items_fetched >= 1
assert result.completed is True
def test_batch_evaluation_with_metadata(langfuse_client):
"""Test that additional metadata is added to all scores."""
def metadata_checking_evaluator(*, input, output, metadata=None, **kwargs):
return Evaluation(
name="test_score",
value=1.0,
metadata={"evaluator_data": "test"},
)
additional_metadata = {
"batch_run_id": "test-batch-123",
"evaluation_version": "v2.0",
}
result = langfuse_client.run_batched_evaluation(
scope="traces",
mapper=simple_trace_mapper,
evaluators=[metadata_checking_evaluator],
metadata=additional_metadata,
max_items=2,
)
assert result.total_scores_created > 0
# Verify scores were created with merged metadata
langfuse_client.flush()
time.sleep(3)
# Note: In a real test, you'd verify via API that metadata was merged
# For now, just verify the operation completed
assert result.completed is True
def test_result_structure_fields(langfuse_client):
"""Test that BatchEvaluationResult has all expected fields."""
result = langfuse_client.run_batched_evaluation(
scope="traces",
mapper=simple_trace_mapper,
evaluators=[simple_evaluator],
max_items=3,
)
# Check all result fields exist
assert hasattr(result, "total_items_fetched")
assert hasattr(result, "total_items_processed")
assert hasattr(result, "total_items_failed")
assert hasattr(result, "total_scores_created")
assert hasattr(result, "total_composite_scores_created")
assert hasattr(result, "total_evaluations_failed")
assert hasattr(result, "evaluator_stats")
assert hasattr(result, "resume_token")
assert hasattr(result, "completed")
assert hasattr(result, "duration_seconds")
assert hasattr(result, "failed_item_ids")
assert hasattr(result, "error_summary")
assert hasattr(result, "has_more_items")
assert hasattr(result, "item_evaluations")
# Check types
assert isinstance(result.evaluator_stats, list)
assert isinstance(result.failed_item_ids, list)
assert isinstance(result.error_summary, dict)
assert isinstance(result.completed, bool)
assert isinstance(result.has_more_items, bool)
assert isinstance(result.item_evaluations, dict)
# ============================================================================
# MAPPER FUNCTION TESTS
# ============================================================================
def test_simple_mapper(langfuse_client):
"""Test basic mapper functionality."""
def custom_mapper(*, item):
return EvaluatorInputs(
input=item.input if hasattr(item, "input") else "no input",
output=item.output if hasattr(item, "output") else "no output",
expected_output=None,
metadata={"custom_field": "test_value"},
)
result = langfuse_client.run_batched_evaluation(
scope="traces",
mapper=custom_mapper,
evaluators=[simple_evaluator],
max_items=2,
)
assert result.total_items_processed > 0
@pytest.mark.asyncio
async def test_async_mapper(langfuse_client):
"""Test that async mappers work correctly."""
async def async_mapper(*, item):
await asyncio.sleep(0.01) # Simulate async work
return EvaluatorInputs(
input=item.input if hasattr(item, "input") else None,
output=item.output if hasattr(item, "output") else None,
expected_output=None,
metadata={"async": True},
)
# Note: run_batched_evaluation is synchronous but handles async mappers
result = langfuse_client.run_batched_evaluation(
scope="traces",
mapper=async_mapper,
evaluators=[simple_evaluator],
max_items=2,
)
assert result.total_items_processed > 0
def test_mapper_failure_handling(langfuse_client):
"""Test that mapper failures cause items to be skipped."""
def failing_mapper(*, item):
raise ValueError("Intentional mapper failure")
result = langfuse_client.run_batched_evaluation(
scope="traces",
mapper=failing_mapper,
evaluators=[simple_evaluator],
max_items=3,
)
# All items should fail due to mapper failures
assert result.total_items_failed > 0
assert len(result.failed_item_ids) > 0
assert "ValueError" in result.error_summary or "Exception" in result.error_summary
def test_mapper_with_missing_fields(langfuse_client):
"""Test mapper handles traces with missing fields gracefully."""
def robust_mapper(*, item):
# Handle missing fields with defaults
input_val = getattr(item, "input", None) or "default_input"
output_val = getattr(item, "output", None) or "default_output"
return EvaluatorInputs(
input=input_val,
output=output_val,
expected_output=None,
metadata={},
)
result = langfuse_client.run_batched_evaluation(
scope="traces",
mapper=robust_mapper,
evaluators=[simple_evaluator],
max_items=2,
)
assert result.total_items_processed > 0
# ============================================================================
# EVALUATOR TESTS
# ============================================================================
def test_single_evaluator(langfuse_client):
"""Test with a single evaluator."""
def quality_evaluator(*, input, output, **kwargs):
return Evaluation(name="quality", value=0.85, comment="High quality")
result = langfuse_client.run_batched_evaluation(
scope="traces",
mapper=simple_trace_mapper,
evaluators=[quality_evaluator],
max_items=2,
)
assert result.total_scores_created > 0
assert len(result.evaluator_stats) == 1
assert result.evaluator_stats[0].name == "quality_evaluator"
def test_multiple_evaluators(langfuse_client):
"""Test with multiple evaluators running in parallel."""
def accuracy_evaluator(*, input, output, **kwargs):
return Evaluation(name="accuracy", value=0.9)
def relevance_evaluator(*, input, output, **kwargs):
return Evaluation(name="relevance", value=0.8)
def safety_evaluator(*, input, output, **kwargs):
return Evaluation(name="safety", value=1.0)
result = langfuse_client.run_batched_evaluation(
scope="traces",
mapper=simple_trace_mapper,
evaluators=[accuracy_evaluator, relevance_evaluator, safety_evaluator],
max_items=2,
)
# Should have 3 evaluators
assert len(result.evaluator_stats) == 3
assert result.total_scores_created >= result.total_items_processed * 3
@pytest.mark.asyncio
async def test_async_evaluator(langfuse_client):
"""Test that async evaluators work correctly."""
async def async_evaluator(*, input, output, **kwargs):
await asyncio.sleep(0.01) # Simulate async work
return Evaluation(name="async_score", value=0.75)
result = langfuse_client.run_batched_evaluation(
scope="traces",
mapper=simple_trace_mapper,
evaluators=[async_evaluator],
max_items=2,
)
assert result.total_scores_created > 0
def test_evaluator_returning_list(langfuse_client):
"""Test evaluator that returns multiple Evaluations."""
def multi_score_evaluator(*, input, output, **kwargs):
return [
Evaluation(name="score_1", value=0.8),
Evaluation(name="score_2", value=0.9),
Evaluation(name="score_3", value=0.7),
]
result = langfuse_client.run_batched_evaluation(
scope="traces",
mapper=simple_trace_mapper,
evaluators=[multi_score_evaluator],
max_items=2,
)
# Should create 3 scores per item
assert result.total_scores_created >= result.total_items_processed * 3
def test_evaluator_failure_statistics(langfuse_client):
"""Test that evaluator failures are tracked in statistics."""
def working_evaluator(*, input, output, **kwargs):
return Evaluation(name="working", value=1.0)
def failing_evaluator(*, input, output, **kwargs):
raise RuntimeError("Intentional evaluator failure")
result = langfuse_client.run_batched_evaluation(
scope="traces",
mapper=simple_trace_mapper,
evaluators=[working_evaluator, failing_evaluator],
max_items=3,
)
# Verify evaluator stats
assert len(result.evaluator_stats) == 2
working_stats = next(
s for s in result.evaluator_stats if s.name == "working_evaluator"
)
assert working_stats.successful_runs > 0
assert working_stats.failed_runs == 0
failing_stats = next(
s for s in result.evaluator_stats if s.name == "failing_evaluator"
)
assert failing_stats.failed_runs > 0
assert failing_stats.successful_runs == 0
# Total evaluations failed should be tracked
assert result.total_evaluations_failed > 0
def test_mixed_sync_async_evaluators(langfuse_client):
"""Test mixing synchronous and asynchronous evaluators."""
def sync_evaluator(*, input, output, **kwargs):
return Evaluation(name="sync_score", value=0.8)
async def async_evaluator(*, input, output, **kwargs):
await asyncio.sleep(0.01)
return Evaluation(name="async_score", value=0.9)
result = langfuse_client.run_batched_evaluation(
scope="traces",
mapper=simple_trace_mapper,
evaluators=[sync_evaluator, async_evaluator],
max_items=2,
)
assert len(result.evaluator_stats) == 2
assert result.total_scores_created >= result.total_items_processed * 2
# ============================================================================
# COMPOSITE EVALUATOR TESTS
# ============================================================================
def test_composite_evaluator_weighted_average(langfuse_client):
"""Test composite evaluator that computes weighted average."""
def accuracy_evaluator(*, input, output, **kwargs):
return Evaluation(name="accuracy", value=0.8)
def relevance_evaluator(*, input, output, **kwargs):
return Evaluation(name="relevance", value=0.9)
def composite_evaluator(*, input, output, expected_output, metadata, evaluations):
weights = {"accuracy": 0.6, "relevance": 0.4}
total = sum(
e.value * weights.get(e.name, 0)
for e in evaluations
if isinstance(e.value, (int, float))
)
return Evaluation(
name="composite_score",
value=total,
comment=f"Weighted average of {len(evaluations)} metrics",
)
result = langfuse_client.run_batched_evaluation(
scope="traces",
mapper=simple_trace_mapper,
evaluators=[accuracy_evaluator, relevance_evaluator],
composite_evaluator=composite_evaluator,
max_items=2,
)
# Should have both regular and composite scores
assert result.total_scores_created > 0
assert result.total_composite_scores_created > 0
assert result.total_scores_created > result.total_composite_scores_created
def test_composite_evaluator_pass_fail(langfuse_client):
"""Test composite evaluator that implements pass/fail logic."""
def metric1_evaluator(*, input, output, **kwargs):
return Evaluation(name="metric1", value=0.9)
def metric2_evaluator(*, input, output, **kwargs):
return Evaluation(name="metric2", value=0.7)
def pass_fail_composite(*, input, output, expected_output, metadata, evaluations):
thresholds = {"metric1": 0.8, "metric2": 0.6}
passes = all(
e.value >= thresholds.get(e.name, 0)
for e in evaluations
if isinstance(e.value, (int, float))
)
return Evaluation(
name="passes_all_checks",
value=1.0 if passes else 0.0,
comment="All checks passed" if passes else "Some checks failed",
)
result = langfuse_client.run_batched_evaluation(
scope="traces",
mapper=simple_trace_mapper,
evaluators=[metric1_evaluator, metric2_evaluator],
composite_evaluator=pass_fail_composite,
max_items=2,
)
assert result.total_composite_scores_created > 0
@pytest.mark.asyncio
async def test_async_composite_evaluator(langfuse_client):
"""Test async composite evaluator."""
def evaluator1(*, input, output, **kwargs):
return Evaluation(name="eval1", value=0.8)
async def async_composite(*, input, output, expected_output, metadata, evaluations):
await asyncio.sleep(0.01) # Simulate async processing
avg = sum(
e.value for e in evaluations if isinstance(e.value, (int, float))
) / len(evaluations)
return Evaluation(name="async_composite", value=avg)
result = langfuse_client.run_batched_evaluation(
scope="traces",
mapper=simple_trace_mapper,
evaluators=[evaluator1],
composite_evaluator=async_composite,
max_items=2,
)
assert result.total_composite_scores_created > 0
def test_composite_evaluator_with_no_evaluations(langfuse_client):
"""Test composite evaluator when no evaluations are present."""
def always_failing_evaluator(*, input, output, **kwargs):
raise Exception("Always fails")
def composite_evaluator(*, input, output, expected_output, metadata, evaluations):
# Should not be called if no evaluations succeed
return Evaluation(name="composite", value=0.0)
result = langfuse_client.run_batched_evaluation(
scope="traces",
mapper=simple_trace_mapper,
evaluators=[always_failing_evaluator],
composite_evaluator=composite_evaluator,
max_items=2,
)
# Composite evaluator should not create scores if no evaluations
assert result.total_composite_scores_created == 0
def test_composite_evaluator_failure_handling(langfuse_client):
"""Test that composite evaluator failures are handled gracefully."""
def evaluator1(*, input, output, **kwargs):
return Evaluation(name="eval1", value=0.8)
def failing_composite(*, input, output, expected_output, metadata, evaluations):
raise ValueError("Composite evaluator failed")
result = langfuse_client.run_batched_evaluation(
scope="traces",
mapper=simple_trace_mapper,
evaluators=[evaluator1],
composite_evaluator=failing_composite,
max_items=2,
)
# Regular scores should still be created
assert result.total_scores_created > 0
# But no composite scores
assert result.total_composite_scores_created == 0
# ============================================================================
# ERROR HANDLING TESTS
# ============================================================================
def test_mapper_failure_skips_item(langfuse_client):
"""Test that mapper failure causes item to be skipped."""
call_count = {"count": 0}
def sometimes_failing_mapper(*, item):
call_count["count"] += 1
if call_count["count"] % 2 == 0:
raise Exception("Mapper failed")
return simple_trace_mapper(item=item)
result = langfuse_client.run_batched_evaluation(
scope="traces",
mapper=sometimes_failing_mapper,
evaluators=[simple_evaluator],
max_items=4,
)
# Some items should fail, some should succeed
assert result.total_items_failed > 0
assert result.total_items_processed > 0
def test_evaluator_failure_continues(langfuse_client):
"""Test that one evaluator failing doesn't stop others."""
def working_evaluator1(*, input, output, **kwargs):
return Evaluation(name="working1", value=0.8)
def failing_evaluator(*, input, output, **kwargs):
raise Exception("Evaluator failed")
def working_evaluator2(*, input, output, **kwargs):
return Evaluation(name="working2", value=0.9)
result = langfuse_client.run_batched_evaluation(
scope="traces",
mapper=simple_trace_mapper,
evaluators=[working_evaluator1, failing_evaluator, working_evaluator2],
max_items=2,
)
# Working evaluators should still create scores
assert result.total_scores_created >= result.total_items_processed * 2
# Failing evaluator should be tracked
failing_stats = next(
s for s in result.evaluator_stats if s.name == "failing_evaluator"
)
assert failing_stats.failed_runs > 0
def test_all_evaluators_fail(langfuse_client):
"""Test when all evaluators fail but item is still processed."""
def failing_evaluator1(*, input, output, **kwargs):
raise Exception("Failed 1")
def failing_evaluator2(*, input, output, **kwargs):
raise Exception("Failed 2")
result = langfuse_client.run_batched_evaluation(
scope="traces",
mapper=simple_trace_mapper,
evaluators=[failing_evaluator1, failing_evaluator2],
max_items=2,
)
# Items should be processed even if all evaluators fail
assert result.total_items_processed > 0
# But no scores created
assert result.total_scores_created == 0
# All evaluations failed
assert result.total_evaluations_failed > 0
# ============================================================================
# EDGE CASES TESTS
# ============================================================================
def test_empty_results_handling(langfuse_client):
"""Test batch evaluation when filter returns no items."""
nonexistent_name = f"nonexistent-trace-{create_uuid()}"
nonexistent_filter = f'[{{"type": "string", "column": "name", "operator": "=", "value": "{nonexistent_name}"}}]'
result = langfuse_client.run_batched_evaluation(
scope="traces",
mapper=simple_trace_mapper,
evaluators=[simple_evaluator],
filter=nonexistent_filter,
)
assert result.total_items_fetched == 0
assert result.total_items_processed == 0
assert result.total_scores_created == 0
assert result.completed is True
assert result.has_more_items is False
def test_max_items_zero(langfuse_client):
"""Test with max_items=0 (should process no items)."""
result = langfuse_client.run_batched_evaluation(
scope="traces",
mapper=simple_trace_mapper,
evaluators=[simple_evaluator],
max_items=0,
)
assert result.total_items_fetched == 0
assert result.total_items_processed == 0
def test_evaluation_value_type_conversions(langfuse_client):
"""Test that different evaluation value types are handled correctly."""
def multi_type_evaluator(*, input, output, **kwargs):
return [
Evaluation(name="int_score", value=5), # int
Evaluation(name="float_score", value=0.85), # float
Evaluation(name="bool_score", value=True), # bool
Evaluation(name="none_score", value=None), # None
]
result = langfuse_client.run_batched_evaluation(
scope="traces",
mapper=simple_trace_mapper,
evaluators=[multi_type_evaluator],
max_items=1,
)
# All value types should be converted and scores created
assert result.total_scores_created >= 4
# ============================================================================
# PAGINATION TESTS
# ============================================================================
def test_pagination_with_max_items(langfuse_client):
"""Test that max_items limit is respected."""
# Create more traces to ensure we have enough data
for i in range(10):
with langfuse_client.start_as_current_span(
name=f"pagination-test-{create_uuid()}"
) as span:
span.update_trace(
input=f"Input {i}",
output=f"Output {i}",
tags=["pagination_test"],
)
langfuse_client.flush()
time.sleep(3)
filter_json = '[{"type": "arrayOptions", "column": "tags", "operator": "any of", "value": ["pagination_test"]}]'
result = langfuse_client.run_batched_evaluation(
scope="traces",
mapper=simple_trace_mapper,
evaluators=[simple_evaluator],
filter=filter_json,
max_items=5,
fetch_batch_size=2,
)
# Should not exceed max_items
assert result.total_items_processed <= 5
def test_has_more_items_flag(langfuse_client):
"""Test that has_more_items flag is set correctly when max_items is reached."""
# Create enough traces to exceed max_items
batch_tag = f"batch-test-{create_uuid()}"
for i in range(15):
with langfuse_client.start_as_current_span(name=f"more-items-test-{i}") as span:
span.update_trace(
input=f"Input {i}",
output=f"Output {i}",
tags=[batch_tag],
)
langfuse_client.flush()
time.sleep(3)
filter_json = f'[{{"type": "arrayOptions", "column": "tags", "operator": "any of", "value": ["{batch_tag}"]}}]'
result = langfuse_client.run_batched_evaluation(
scope="traces",
mapper=simple_trace_mapper,
evaluators=[simple_evaluator],
filter=filter_json,
max_items=5,
fetch_batch_size=2,
)
# has_more_items should be True if we hit the limit
if result.total_items_fetched >= 5:
assert result.has_more_items is True
def test_fetch_batch_size_parameter(langfuse_client):
"""Test that different fetch_batch_size values work correctly."""
for batch_size in [1, 5, 10]:
result = langfuse_client.run_batched_evaluation(
scope="traces",
mapper=simple_trace_mapper,
evaluators=[simple_evaluator],
max_items=3,
fetch_batch_size=batch_size,
)
# Should complete regardless of batch size
assert result.completed is True or result.total_items_processed > 0
# ============================================================================
# RESUME FUNCTIONALITY TESTS
# ============================================================================
def test_resume_token_structure(langfuse_client):
"""Test that BatchEvaluationResumeToken has correct structure."""
resume_token = BatchEvaluationResumeToken(
scope="traces",
filter='{"test": "filter"}',
last_processed_timestamp="2024-01-01T00:00:00Z",
last_processed_id="trace-123",
items_processed=10,
)
assert resume_token.scope == "traces"
assert resume_token.filter == '{"test": "filter"}'
assert resume_token.last_processed_timestamp == "2024-01-01T00:00:00Z"
assert resume_token.last_processed_id == "trace-123"
assert resume_token.items_processed == 10
# ============================================================================
# CONCURRENCY TESTS
# ============================================================================
def test_max_concurrency_parameter(langfuse_client):
"""Test that max_concurrency parameter works correctly."""
for concurrency in [1, 5, 10]:
result = langfuse_client.run_batched_evaluation(
scope="traces",
mapper=simple_trace_mapper,
evaluators=[simple_evaluator],
max_items=3,
max_concurrency=concurrency,
)
# Should complete regardless of concurrency
assert result.completed is True or result.total_items_processed > 0
# ============================================================================
# STATISTICS TESTS
# ============================================================================
def test_evaluator_stats_structure(langfuse_client):
"""Test that EvaluatorStats has correct structure."""
def test_evaluator(*, input, output, **kwargs):
return Evaluation(name="test", value=1.0)
result = langfuse_client.run_batched_evaluation(
scope="traces",
mapper=simple_trace_mapper,
evaluators=[test_evaluator],
max_items=2,
)
assert len(result.evaluator_stats) == 1
stats = result.evaluator_stats[0]
# Check all fields exist
assert hasattr(stats, "name")
assert hasattr(stats, "total_runs")
assert hasattr(stats, "successful_runs")
assert hasattr(stats, "failed_runs")
assert hasattr(stats, "total_scores_created")
# Check values
assert stats.name == "test_evaluator"
assert stats.total_runs == result.total_items_processed
assert stats.successful_runs == result.total_items_processed
assert stats.failed_runs == 0
def test_evaluator_stats_tracking(langfuse_client):
"""Test that evaluator statistics are tracked correctly."""
call_count = {"count": 0}
def sometimes_failing_evaluator(*, input, output, **kwargs):
call_count["count"] += 1
if call_count["count"] % 2 == 0:
raise Exception("Failed")
return Evaluation(name="test", value=1.0)
result = langfuse_client.run_batched_evaluation(
scope="traces",
mapper=simple_trace_mapper,
evaluators=[sometimes_failing_evaluator],
max_items=4,
)
stats = result.evaluator_stats[0]
assert stats.total_runs == result.total_items_processed
assert stats.successful_runs > 0
assert stats.failed_runs > 0
assert stats.successful_runs + stats.failed_runs == stats.total_runs
def test_error_summary_aggregation(langfuse_client):
"""Test that error types are aggregated correctly in error_summary."""
def failing_mapper(*, item):
raise ValueError("Mapper error")
result = langfuse_client.run_batched_evaluation(
scope="traces",
mapper=failing_mapper,
evaluators=[simple_evaluator],
max_items=3,
)
# Error summary should contain the error type
assert len(result.error_summary) > 0
assert any("Error" in key for key in result.error_summary.keys())
def test_failed_item_ids_collected(langfuse_client):
"""Test that failed item IDs are collected."""
def failing_mapper(*, item):
raise Exception("Failed")
result = langfuse_client.run_batched_evaluation(
scope="traces",
mapper=failing_mapper,
evaluators=[simple_evaluator],
max_items=3,
)
assert len(result.failed_item_ids) > 0
# Each failed ID should be a string
assert all(isinstance(item_id, str) for item_id in result.failed_item_ids)
# ============================================================================
# PERFORMANCE TESTS
# ============================================================================
def test_duration_tracking(langfuse_client):
"""Test that duration is tracked correctly."""
result = langfuse_client.run_batched_evaluation(
scope="traces",
mapper=simple_trace_mapper,
evaluators=[simple_evaluator],
max_items=2,
)
assert result.duration_seconds > 0
assert result.duration_seconds < 60 # Should complete quickly for small batch
def test_verbose_logging(langfuse_client):
"""Test that verbose=True doesn't cause errors."""
result = langfuse_client.run_batched_evaluation(
scope="traces",
mapper=simple_trace_mapper,
evaluators=[simple_evaluator],
max_items=2,
verbose=True, # Should log progress
)
assert result.completed is True
# ============================================================================
# ITEM EVALUATIONS TESTS
# ============================================================================