-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_benchmark_utils.py
More file actions
4031 lines (3238 loc) · 179 KB
/
test_benchmark_utils.py
File metadata and controls
4031 lines (3238 loc) · 179 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
#!/usr/bin/env python3
"""
Test suite for benchmark_utils.py module.
Tests benchmark parsing, baseline generation, and performance comparison functionality,
with special focus on the new average regression calculation logic.
Note: This test file accesses private methods (prefixed with _) which is expected
and necessary for comprehensive unit testing of internal functionality.
"""
import json
import logging
import math
import os
import re
import subprocess
import sys
import tempfile
import time
from io import StringIO
from pathlib import Path
from typing import Any
from unittest.mock import Mock, patch
import pytest
from benchmark_models import (
BenchmarkData,
CircumspherePerformanceData,
CircumsphereTestCase,
)
from benchmark_utils import (
_CI_PERFORMANCE_SUITE_MANIFEST_IDS_FILE,
DEFAULT_REGRESSION_THRESHOLD,
DEV_MODE_BENCH_ARGS,
TRUSTED_BENCH_PROFILE,
BaselineGenerator,
BenchmarkRegressionHelper,
CriterionParser,
PerformanceComparator,
PerformanceSummaryGenerator,
ProjectRootNotFoundError,
WorkflowHelper,
_expand_ci_benchmark_id_pattern,
configure_logging,
create_argument_parser,
find_project_root,
main,
)
THRESHOLD_PERCENT = f"{DEFAULT_REGRESSION_THRESHOLD:.1f}%"
CI_MANIFEST_STDOUT = (
"api_benchmark group=boundary_facets public_api=DelaunayTriangulation::boundary_facets "
"dimensions=3 benchmark_ids=boundary_facets/boundary_facets_3d/50 note=test\n"
)
PUBLIC_API_TITLE = "### Public API Performance Contract (`ci_performance_suite`)"
CIRCUMSPHERE_TITLE = "## Circumsphere Predicate Analysis"
PERFORMANCE_RANKING_TITLE = "### Performance Ranking"
RECOMMENDATIONS_TITLE = "### Recommendations"
PERFORMANCE_UPDATES_TITLE = "## Performance Data Updates"
def completed_process(
stdout: str = "",
*,
returncode: int = 0,
stderr: str = "",
args: list[str] | None = None,
) -> subprocess.CompletedProcess[str]:
"""Return a typed subprocess result for command-wrapper mocks."""
return subprocess.CompletedProcess(args=args or [], returncode=returncode, stdout=stdout, stderr=stderr)
def write_estimate(target_dir: Path, path_parts, mean_ns) -> None:
"""Write a minimal Criterion estimates.json fixture."""
estimates_dir = target_dir / "criterion" / Path(*path_parts) / "base"
estimates_dir.mkdir(parents=True)
estimates = {
"mean": {
"point_estimate": mean_ns,
"confidence_interval": {
"lower_bound": mean_ns * 0.9,
"upper_bound": mean_ns * 1.1,
},
},
}
(estimates_dir / "estimates.json").write_text(json.dumps(estimates), encoding="utf-8")
def write_ci_performance_manifest(target_dir: Path, benchmark_ids: list[str]) -> None:
"""Write the ci_performance_suite runtime manifest sidecar."""
criterion_dir = target_dir / "criterion"
criterion_dir.mkdir(parents=True, exist_ok=True)
(criterion_dir / _CI_PERFORMANCE_SUITE_MANIFEST_IDS_FILE).write_text(
"\n".join(benchmark_ids) + "\n",
encoding="utf-8",
)
def compute_average_time_change(current_results, baseline_results) -> float:
"""Replicate PerformanceComparator's geometric mean logic for tests."""
time_changes = []
for current in current_results:
key = f"{current.points}_{current.dimension}"
baseline = baseline_results.get(key)
if not baseline or baseline.time_mean <= 0:
continue
time_change = ((current.time_mean - baseline.time_mean) / baseline.time_mean) * 100.0
time_changes.append(time_change)
if not time_changes:
return 0.0
ratios = [1.0 + (tc / 100.0) for tc in time_changes if (1.0 + (tc / 100.0)) > 0.0]
if not ratios:
return 0.0
avg_log = sum(math.log(ratio) for ratio in ratios) / len(ratios)
avg_ratio = math.exp(avg_log)
return (avg_ratio - 1.0) * 100.0
@pytest.fixture
def sample_estimates_data() -> dict[str, object]:
"""Fixture for common estimates.json test data."""
return {
"mean": {
"point_estimate": 110000.0, # 110 microseconds in nanoseconds
"confidence_interval": {"lower_bound": 100000.0, "upper_bound": 120000.0},
},
}
@pytest.fixture
def sample_benchmark_data() -> dict[str, BenchmarkData]:
"""Fixture for common BenchmarkData test objects."""
return {
"2d_1000": BenchmarkData(1000, "2D").with_timing(100.0, 110.0, 120.0, "µs"),
"2d_2000": BenchmarkData(2000, "2D").with_timing(190.0, 200.0, 210.0, "µs"),
"3d_1000": BenchmarkData(1000, "3D").with_timing(200.0, 220.0, 240.0, "µs"),
}
class TestCriterionParser:
"""Test cases for CriterionParser class."""
def test_parse_estimates_json_valid_data(self, sample_estimates_data) -> None:
"""Test parsing valid estimates.json data."""
with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
json.dump(sample_estimates_data, f)
f.flush()
estimates_path = Path(f.name)
try:
result = CriterionParser.parse_estimates_json(estimates_path, 1000, "2D")
assert result is not None
assert result.points == 1000
assert result.dimension == "2D"
assert result.time_mean == 110.0 # Converted to microseconds
assert result.time_low == 100.0
assert result.time_high == 120.0
assert result.time_unit == "µs"
assert result.throughput_mean is not None
assert result.throughput_mean == pytest.approx(9090.909, abs=0.001) # 1000 * 1000 / 110
finally:
estimates_path.unlink()
def test_benchmark_data_positional_timing_compatibility(self) -> None:
"""Test legacy positional construction still maps the third argument to time_low."""
benchmark = BenchmarkData(1000, "2D", 1.0, 2.0, 3.0, "µs")
assert benchmark.time_low == 1.0
assert benchmark.time_mean == 2.0
assert benchmark.time_high == 3.0
assert benchmark.time_unit == "µs"
assert benchmark.benchmark_id == ""
def test_parse_estimates_json_preserves_unsized_workload(self, sample_estimates_data) -> None:
"""Test Criterion estimates without numeric input size do not get fake throughput."""
with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
json.dump(sample_estimates_data, f)
f.flush()
estimates_path = Path(f.name)
try:
result = CriterionParser.parse_estimates_json(estimates_path, None, "4D")
assert result is not None
assert result.points is None
assert result.dimension == "4D"
assert result.throughput_mean is None
assert "0 Points" not in result.to_baseline_format()
finally:
estimates_path.unlink()
def test_parse_estimates_json_zero_mean(self) -> None:
"""Test parsing estimates.json with zero mean time."""
estimates_data = {"mean": {"point_estimate": 0.0, "confidence_interval": {"lower_bound": 0.0, "upper_bound": 0.0}}}
with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
json.dump(estimates_data, f)
f.flush()
estimates_path = Path(f.name)
try:
result = CriterionParser.parse_estimates_json(estimates_path, 1000, "2D")
assert result is None
finally:
estimates_path.unlink()
@pytest.mark.parametrize(
"estimates_data",
[
{"mean": {"point_estimate": float("nan"), "confidence_interval": {"lower_bound": 100000.0, "upper_bound": 120000.0}}},
{"mean": {"point_estimate": float("inf"), "confidence_interval": {"lower_bound": 100000.0, "upper_bound": 120000.0}}},
{"mean": {"point_estimate": 110000.0, "confidence_interval": {"lower_bound": 120000.0, "upper_bound": 130000.0}}},
],
)
def test_parse_estimates_json_rejects_invalid_estimates(self, estimates_data) -> None:
"""Test parsing rejects non-finite or unordered Criterion estimates."""
with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
json.dump(estimates_data, f)
f.flush()
estimates_path = Path(f.name)
try:
result = CriterionParser.parse_estimates_json(estimates_path, 1000, "2D")
assert result is None
finally:
estimates_path.unlink()
def test_summary_estimate_loader_rejects_nonfinite_values(self) -> None:
"""Test performance summary loader rejects non-finite Criterion estimates."""
estimates_data = {
"mean": {
"point_estimate": float("nan"),
"confidence_interval": {"lower_bound": 100000.0, "upper_bound": 120000.0},
},
}
with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
json.dump(estimates_data, f)
f.flush()
estimates_path = Path(f.name)
try:
assert PerformanceSummaryGenerator._load_criterion_estimate(estimates_path) is None
finally:
estimates_path.unlink()
@pytest.mark.parametrize(
"estimates_data",
[
[],
{"mean": []},
{"mean": {"point_estimate": 100000.0, "confidence_interval": []}},
],
)
def test_summary_estimate_loader_rejects_structurally_invalid_mean_data(self, estimates_data) -> None:
"""Test performance summary loader rejects structurally malformed Criterion estimates."""
with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
json.dump(estimates_data, f)
f.flush()
estimates_path = Path(f.name)
try:
assert PerformanceSummaryGenerator._load_criterion_estimate(estimates_path) is None
finally:
estimates_path.unlink()
def test_parse_estimates_json_very_fast_benchmark_division_by_zero_protection(self) -> None:
"""Test division by zero protection for very fast benchmarks with near-zero confidence intervals."""
estimates_data = {
"mean": {
"point_estimate": 1000.0, # 1 microsecond in nanoseconds
"confidence_interval": {
"lower_bound": 0.0, # Could cause division by zero without protection
"upper_bound": 2000.0,
},
},
}
with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
json.dump(estimates_data, f)
f.flush()
estimates_path = Path(f.name)
try:
result = CriterionParser.parse_estimates_json(estimates_path, 1000, "2D")
# Should not crash and should return valid data with protected throughput calculation
assert result is not None
assert result.points == 1000
assert result.dimension == "2D"
assert result.time_mean == 1.0 # 1 microsecond
assert result.time_low == 0.0 # Lower bound of confidence interval
assert result.time_high == 2.0 # Upper bound
# Throughput should be calculated with epsilon protection
# thrpt_high = points * 1000 / max(low_us, eps) = 1000 * 1000 / max(0.0, 1e-9) = 1000 * 1000 / 1e-9
assert result.throughput_high is not None
assert result.throughput_high > 1e12 # Should be very large due to epsilon protection
assert result.throughput_mean is not None
assert result.throughput_low is not None
finally:
estimates_path.unlink()
def test_parse_estimates_json_invalid_file(self) -> None:
"""Test parsing non-existent estimates.json file."""
result = CriterionParser.parse_estimates_json(Path("nonexistent.json"), 1000, "2D")
assert result is None
def test_parse_estimates_json_malformed_json(self) -> None:
"""Test parsing malformed JSON file."""
with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
f.write("{ invalid json")
f.flush()
estimates_path = Path(f.name)
try:
result = CriterionParser.parse_estimates_json(estimates_path, 1000, "2D")
assert result is None
finally:
estimates_path.unlink()
@patch("benchmark_utils.Path.exists")
@patch("benchmark_utils.Path.iterdir")
def test_find_criterion_results_no_criterion_dir(self, mock_iterdir, mock_exists) -> None: # noqa: ARG002
"""Test finding criterion results when criterion directory doesn't exist."""
mock_exists.return_value = False
target_dir = Path("/fake/target")
results = CriterionParser.find_criterion_results(target_dir)
assert results == []
def test_find_criterion_results_sorting(self) -> None:
"""Test that results are sorted by dimension and points."""
# Create test data that would be unsorted initially
test_results = [
BenchmarkData(5000, "3D").with_timing(200.0, 220.0, 240.0, "µs"),
BenchmarkData(1000, "2D").with_timing(100.0, 110.0, 120.0, "µs"),
BenchmarkData(1000, "4D").with_timing(300.0, 320.0, 340.0, "µs"),
BenchmarkData(2000, "2D").with_timing(150.0, 160.0, 170.0, "µs"),
]
# Sort using the same logic as the actual function
test_results.sort(key=lambda x: (int(x.dimension.rstrip("D")), x.points))
# Verify sorting order
assert test_results[0].dimension == "2D"
assert test_results[0].points == 1000
assert test_results[1].dimension == "2D"
assert test_results[1].points == 2000
assert test_results[2].dimension == "3D"
assert test_results[2].points == 5000
assert test_results[3].dimension == "4D"
assert test_results[3].points == 1000
def test_ci_performance_suite_patterns(self) -> None:
"""Test CI performance suite benchmark patterns (2D, 3D, 4D, 5D with 10, 25, 50 points)."""
# Test data representing CI performance suite dimensions and point counts
ci_suite_results = [
BenchmarkData(10, "2D").with_timing(18.0, 20.0, 22.0, "µs"),
BenchmarkData(25, "2D").with_timing(38.0, 40.0, 42.0, "µs"),
BenchmarkData(50, "2D").with_timing(78.0, 80.0, 82.0, "µs"),
BenchmarkData(10, "3D").with_timing(48.0, 50.0, 52.0, "µs"),
BenchmarkData(25, "3D").with_timing(118.0, 125.0, 132.0, "µs"),
BenchmarkData(50, "3D").with_timing(245.0, 250.0, 255.0, "µs"),
BenchmarkData(10, "4D").with_timing(58.0, 60.0, 62.0, "µs"),
BenchmarkData(25, "4D").with_timing(118.0, 120.0, 122.0, "µs"),
BenchmarkData(50, "4D").with_timing(290.0, 300.0, 310.0, "µs"),
BenchmarkData(10, "5D").with_timing(78.0, 80.0, 82.0, "µs"),
BenchmarkData(25, "5D").with_timing(145.0, 150.0, 155.0, "µs"),
BenchmarkData(50, "5D").with_timing(290.0, 300.0, 310.0, "µs"),
]
# Sort using the same logic as the actual function (by dimension, then points)
ci_suite_results.sort(key=lambda x: (int(x.dimension.rstrip("D")), x.points))
# Verify sorting order: 2D..5D, then 10,25,50 within each dimension
expected_order = [(d, p) for d in ("2D", "3D", "4D", "5D") for p in (10, 25, 50)]
actual_order = [(b.dimension, b.points) for b in ci_suite_results]
assert actual_order == expected_order
def test_ci_benchmark_id_pattern_expands_braced_segments(self) -> None:
"""Test ci_performance_suite manifest brace patterns expand to concrete IDs."""
result = _expand_ci_benchmark_id_pattern("tds_new_2d/{tds_new,tds_new_adversarial}/{10,25}")
assert result == {
"tds_new_2d/tds_new/10",
"tds_new_2d/tds_new/25",
"tds_new_2d/tds_new_adversarial/10",
"tds_new_2d/tds_new_adversarial/25",
}
def test_find_criterion_results_preserves_ci_suite_ids(self) -> None:
"""Test ci_performance_suite results keep expanded Criterion benchmark IDs."""
with tempfile.TemporaryDirectory() as temp_dir:
target_dir = Path(temp_dir) / "target"
write_estimate(target_dir, ("boundary_facets", "boundary_facets_3d", "50"), 10_000.0)
write_estimate(target_dir, ("validation", "validate_3d", "50"), 20_000.0)
write_estimate(target_dir, ("boundary_facets", "boundary_facets_3d_adversarial", "50"), 30_000.0)
write_estimate(target_dir, ("bistellar_flips_4d", "k2_roundtrip"), 40_000.0)
results = CriterionParser.find_criterion_results(target_dir)
assert [result.comparison_key for result in results] == [
"boundary_facets/boundary_facets_3d/50",
"boundary_facets/boundary_facets_3d_adversarial/50",
"validation/validate_3d/50",
"bistellar_flips_4d/k2_roundtrip",
]
sized_results = [result for result in results if result.comparison_key != "bistellar_flips_4d/k2_roundtrip"]
assert {(result.points, result.dimension) for result in sized_results} == {(50, "3D")}
roundtrip = next(result for result in results if result.comparison_key == "bistellar_flips_4d/k2_roundtrip")
assert roundtrip.points is None
assert roundtrip.dimension == "4D"
assert roundtrip.throughput_mean is None
def test_find_criterion_results_filters_stale_ci_suite_ids_with_manifest(self) -> None:
"""Test ci_performance_suite parsing ignores stale Criterion files outside the manifest."""
with tempfile.TemporaryDirectory() as temp_dir:
target_dir = Path(temp_dir) / "target"
write_estimate(target_dir, ("boundary_facets", "boundary_facets_3d", "50"), 10_000.0)
write_estimate(target_dir, ("validation", "validate_3d", "50"), 20_000.0)
write_estimate(target_dir, ("boundary_facets", "old_boundary_facets_3d", "50"), 30_000.0)
write_ci_performance_manifest(
target_dir,
[
"boundary_facets/boundary_facets_3d/50",
"validation/validate_3d/50",
],
)
results = CriterionParser.find_criterion_results(target_dir)
assert [result.comparison_key for result in results] == [
"boundary_facets/boundary_facets_3d/50",
"validation/validate_3d/50",
]
class TestPerformanceComparator:
"""Test cases for PerformanceComparator class."""
@pytest.fixture
def comparator(self) -> PerformanceComparator:
"""Fixture for PerformanceComparator instance."""
project_root = Path("/fake/project")
return PerformanceComparator(project_root)
@pytest.fixture
def sample_baseline_content(self) -> str:
"""Fixture for sample baseline content."""
return """Date: 2023-06-15 10:30:00 PDT
Git commit: abc123def456
Hardware Information:
OS: macOS
CPU: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
CPU Cores: 6
CPU Threads: 12
Memory: 16.0 GB
Rust: rustc 1.70.0 (90c541806 2023-05-31)
Target: x86_64-apple-darwin
=== 1000 Points (2D) ===
Time: [100.0, 110.0, 120.0] µs
Throughput: [8.333, 9.091, 10.0] Kelem/s
=== 2000 Points (2D) ===
Time: [190.0, 200.0, 210.0] µs
Throughput: [9.524, 10.0, 10.526] Kelem/s
=== 1000 Points (3D) ===
Time: [200.0, 220.0, 240.0] µs
Throughput: [4.167, 4.545, 5.0] Kelem/s
"""
def test_parse_baseline_file(self, comparator, sample_baseline_content) -> None:
"""Test parsing baseline file content."""
results = comparator._parse_baseline_file(sample_baseline_content)
assert len(results) == 3
assert "1000_2D" in results
assert "2000_2D" in results
assert "1000_3D" in results
# Test first benchmark
bench_2d_1000 = results["1000_2D"]
assert bench_2d_1000.points == 1000
assert bench_2d_1000.dimension == "2D"
assert bench_2d_1000.time_mean == 110.0
assert bench_2d_1000.throughput_mean == 9.091
def test_parse_baseline_file_with_benchmark_ids(self, comparator) -> None:
"""Test parsing expanded ci_performance_suite baseline identifiers."""
baseline_content = """Date: 2023-06-15 10:30:00 PDT
Git commit: abc123def456
=== 50 Points (3D) ===
Benchmark ID: boundary_facets/boundary_facets_3d/50
Time: [9.0, 10.0, 11.0] µs
Throughput: [4.545, 5.0, 5.556] Kelem/s
=== 50 Points (3D) ===
Benchmark ID: validation/validate_3d/50
Time: [19.0, 20.0, 21.0] µs
Throughput: [2.381, 2.5, 2.632] Kelem/s
"""
results = comparator._parse_baseline_file(baseline_content)
assert set(results) == {
"boundary_facets/boundary_facets_3d/50",
"validation/validate_3d/50",
}
assert results["boundary_facets/boundary_facets_3d/50"].time_mean == 10.0
assert results["validation/validate_3d/50"].time_mean == 20.0
def test_parse_baseline_file_with_scientific_notation(self, comparator) -> None:
"""Test baseline parsing accepts the full float domain written by Python."""
baseline_content = """Date: 2023-06-15 10:30:00 PDT
Git commit: abc123def456
=== 1000 Points (2D) ===
Time: [1.0e-6, 1.1e-6, 1.2e-6] µs
Throughput: [8.333e3, 9.091e3, 1.0e4] Kelem/s
"""
results = comparator._parse_baseline_file(baseline_content)
benchmark = results["1000_2D"]
assert benchmark.time_low == pytest.approx(1.0e-6)
assert benchmark.time_mean == pytest.approx(1.1e-6)
assert benchmark.time_high == pytest.approx(1.2e-6)
assert benchmark.throughput_mean == pytest.approx(9.091e3)
def test_parse_baseline_file_skips_sections_without_timing(self, comparator) -> None:
"""Test malformed baseline sections without timing data are not compared."""
baseline_content = """Date: 2023-06-15 10:30:00 PDT
Git commit: abc123def456
=== 1000 Points (2D) ===
Benchmark ID: malformed/no_timing
=== 2000 Points (2D) ===
Time: [190.0, 200.0, 210.0] µs
Throughput: [9.524, 10.0, 10.526] Kelem/s
"""
results = comparator._parse_baseline_file(baseline_content)
assert set(results) == {"2000_2D"}
def test_parse_baseline_file_with_unsized_benchmark_id(self, comparator) -> None:
"""Test parsing expanded CI benchmarks without numeric input sizes."""
baseline_content = """Date: 2023-06-15 10:30:00 PDT
Git commit: abc123def456
=== Unsized Workload (4D) ===
Benchmark ID: bistellar_flips_4d/k2_roundtrip
Time: [0.8, 0.95, 1.1] µs
"""
results = comparator._parse_baseline_file(baseline_content)
benchmark = results["bistellar_flips_4d/k2_roundtrip"]
assert benchmark.points is None
assert benchmark.dimension == "4D"
assert benchmark.throughput_mean is None
def test_write_performance_comparison_matches_benchmark_ids(self, comparator) -> None:
"""Test comparison uses expanded benchmark IDs instead of point/dimension collisions."""
current_results = [
BenchmarkData(50, "3D", benchmark_id="boundary_facets/boundary_facets_3d/50").with_timing(9.0, 10.0, 11.0, "µs"),
BenchmarkData(50, "3D", benchmark_id="validation/validate_3d/50").with_timing(19.0, 20.0, 21.0, "µs"),
]
baseline_results = {
"boundary_facets/boundary_facets_3d/50": BenchmarkData(
50,
"3D",
benchmark_id="boundary_facets/boundary_facets_3d/50",
).with_timing(9.0, 10.0, 11.0, "µs"),
"validation/validate_3d/50": BenchmarkData(
50,
"3D",
benchmark_id="validation/validate_3d/50",
).with_timing(38.0, 40.0, 42.0, "µs"),
}
output = StringIO()
comparator._write_performance_comparison(output, current_results, baseline_results)
content = output.getvalue()
assert "Benchmark ID: boundary_facets/boundary_facets_3d/50" in content
assert "Benchmark ID: validation/validate_3d/50" in content
assert "OK: Time change +0.0%" in content
assert "IMPROVEMENT: Time decreased by 50.0%" in content
def test_write_performance_comparison_no_legacy_fallback_for_benchmark_id(self, comparator) -> None:
"""Test expanded IDs do not compare against unrelated collapsed legacy baselines."""
current_results = [
BenchmarkData(50, "3D", benchmark_id="validation/validate_3d/50").with_timing(
19.0,
20.0,
21.0,
"µs",
),
]
baseline_results = {
"50_3D": BenchmarkData(50, "3D").with_timing(38.0, 40.0, 42.0, "µs"),
}
output = StringIO()
comparator._write_performance_comparison(output, current_results, baseline_results)
content = output.getvalue()
assert "Baseline: N/A (no matching entry)" in content
assert "IMPROVEMENT: Time decreased by 50.0%" not in content
def test_write_time_comparison_no_regression(self, comparator) -> None:
"""Test time comparison writing with no regression."""
current = BenchmarkData(1000, "2D").with_timing(100.0, 110.0, 120.0, "µs")
baseline = BenchmarkData(1000, "2D").with_timing(95.0, 105.0, 115.0, "µs")
output = StringIO()
time_change, is_regression = comparator._write_time_comparison(output, current, baseline)
# Change is (110 - 105) / 105 * 100 = 4.76%
assert time_change == pytest.approx(4.76, abs=0.01)
assert not is_regression # Less than DEFAULT_REGRESSION_THRESHOLD
result = output.getvalue()
assert "4.8%" in result
assert "✅ OK: Time change +4.8% within acceptable range" in result
def test_write_time_comparison_with_regression(self, comparator) -> None:
"""Test time comparison writing with regression."""
current = BenchmarkData(1000, "2D").with_timing(100.0, 115.0, 130.0, "µs")
baseline = BenchmarkData(1000, "2D").with_timing(95.0, 100.0, 105.0, "µs")
output = StringIO()
time_change, is_regression = comparator._write_time_comparison(output, current, baseline)
# Change is (115 - 100) / 100 * 100 = 15%
assert time_change == pytest.approx(15.0, abs=1e-9)
assert is_regression # Greater than DEFAULT_REGRESSION_THRESHOLD
result = output.getvalue()
assert "15.0%" in result
assert "REGRESSION" in result
def test_write_time_comparison_with_improvement(self, comparator) -> None:
"""Test time comparison writing with significant improvement."""
current = BenchmarkData(1000, "2D").with_timing(80.0, 90.0, 100.0, "µs")
baseline = BenchmarkData(1000, "2D").with_timing(95.0, 100.0, 105.0, "µs")
output = StringIO()
time_change, is_regression = comparator._write_time_comparison(output, current, baseline)
# Change is (90 - 100) / 100 * 100 = -10%
assert time_change == pytest.approx(-10.0, abs=1e-9)
assert not is_regression
result = output.getvalue()
assert "10.0%" in result
assert "✅ IMPROVEMENT: Time decreased by 10.0% (faster performance)" in result
def test_write_time_comparison_zero_baseline(self, comparator) -> None:
"""Test time comparison with zero baseline time."""
current = BenchmarkData(1000, "2D").with_timing(100.0, 110.0, 120.0, "µs")
baseline = BenchmarkData(1000, "2D").with_timing(0.0, 0.0, 0.0, "µs")
output = StringIO()
time_change, is_regression = comparator._write_time_comparison(output, current, baseline)
assert time_change is None
assert not is_regression
result = output.getvalue()
assert "N/A (baseline mean is 0)" in result
@pytest.mark.parametrize("dev_mode", [False, True])
@patch("benchmark_utils.run_cargo_command")
def test_compare_omits_quiet_flag(self, mock_cargo, dev_mode) -> None:
"""Test that PerformanceComparator invokes cargo without --quiet flag (removed for better error visibility)."""
with tempfile.TemporaryDirectory() as temp_dir:
temp_path = Path(temp_dir)
baseline_file = temp_path / "baseline.txt"
# Create a minimal baseline file
baseline_content = """Date: 2023-12-15 10:30:00 UTC
Git commit: abc123
=== 10 Points (2D) ===
Time: [1.0, 1.0, 1.0] µs
"""
baseline_file.write_text(baseline_content)
# Mock successful cargo command
mock_cargo.return_value = completed_process(CI_MANIFEST_STDOUT)
comparator = PerformanceComparator(temp_path)
comparator.compare_with_baseline(baseline_file, dev_mode=dev_mode)
# Verify cargo was called without --quiet flag (removed for better error visibility)
assert mock_cargo.call_count >= 1
args = mock_cargo.call_args[0][0]
assert "--quiet" not in args # Changed: --quiet flag should NOT be present
assert args[:5] == ["bench", "--profile", TRUSTED_BENCH_PROFILE, "--bench", "ci_performance_suite"]
if dev_mode:
for arg in DEV_MODE_BENCH_ARGS:
assert arg in args
# And output is captured
assert mock_cargo.call_args.kwargs.get("capture_output") is True
def test_write_performance_comparison_no_average_regression(self, comparator) -> None:
"""Test performance comparison with individual regressions but no average regression."""
# Create current results with mixed performance changes
current_results = [
# Big regression: +20%
BenchmarkData(1000, "2D").with_timing(108.0, 120.0, 132.0, "µs"),
# Small improvement: -2%
BenchmarkData(2000, "2D").with_timing(186.0, 196.0, 206.0, "µs"),
# Big improvement: -15%
BenchmarkData(1000, "3D").with_timing(170.0, 187.0, 204.0, "µs"),
]
# Create baseline results
baseline_results = {
"1000_2D": BenchmarkData(1000, "2D").with_timing(95.0, 100.0, 105.0, "µs"),
"2000_2D": BenchmarkData(2000, "2D").with_timing(190.0, 200.0, 210.0, "µs"),
"1000_3D": BenchmarkData(1000, "3D").with_timing(200.0, 220.0, 240.0, "µs"),
}
output = StringIO()
regression_found = comparator._write_performance_comparison(output, current_results, baseline_results)
# Average change using geometric mean: ~0.0%
# This is less than DEFAULT_REGRESSION_THRESHOLD, so no overall regression
assert not regression_found
result = output.getvalue()
assert "SUMMARY" in result
assert "Total benchmarks compared: 3" in result
assert f"Individual regressions (>{THRESHOLD_PERCENT}): 1" in result # Only the +20% one
assert re.search(r"Average time change:\s*-?0\.0%", result)
assert "✅ OVERALL OK" in result
def test_write_performance_comparison_with_average_regression(self, comparator) -> None:
"""Test performance comparison with average regression exceeding threshold."""
# Create current results with overall performance degradation
current_results = [
# Regression: +20%
BenchmarkData(1000, "2D").with_timing(118.0, 120.0, 122.0, "µs"),
# Regression: +15%
BenchmarkData(2000, "2D").with_timing(222.0, 230.0, 238.0, "µs"),
# Small improvement: -1%
BenchmarkData(1000, "3D").with_timing(209.0, 217.8, 226.6, "µs"),
]
# Create baseline results
baseline_results = {
"1000_2D": BenchmarkData(1000, "2D").with_timing(95.0, 100.0, 105.0, "µs"),
"2000_2D": BenchmarkData(2000, "2D").with_timing(190.0, 200.0, 210.0, "µs"),
"1000_3D": BenchmarkData(1000, "3D").with_timing(200.0, 220.0, 240.0, "µs"),
}
output = StringIO()
regression_found = comparator._write_performance_comparison(output, current_results, baseline_results)
# Average change using geometric mean: 11.0%
# This exceeds DEFAULT_REGRESSION_THRESHOLD, so overall regression found
assert regression_found
result = output.getvalue()
assert "SUMMARY" in result
assert "Total benchmarks compared: 3" in result
assert f"Individual regressions (>{THRESHOLD_PERCENT}): 2" in result # The +20% and +15% ones
assert "Average time change: 11.0%" in result
assert "🚨 OVERALL REGRESSION" in result
def test_write_performance_comparison_with_average_improvement(self, comparator) -> None:
"""Test performance comparison with significant average improvement."""
# Create current results with overall performance improvement
current_results = [
# Improvement: -10%
BenchmarkData(1000, "2D").with_timing(81.0, 90.0, 99.0, "µs"),
# Improvement: -8%
BenchmarkData(2000, "2D").with_timing(175.2, 184.0, 192.8, "µs"),
# Small regression: +2%
BenchmarkData(1000, "3D").with_timing(209.0, 224.4, 239.8, "µs"),
]
# Create baseline results
baseline_results = {
"1000_2D": BenchmarkData(1000, "2D").with_timing(95.0, 100.0, 105.0, "µs"),
"2000_2D": BenchmarkData(2000, "2D").with_timing(190.0, 200.0, 210.0, "µs"),
"1000_3D": BenchmarkData(1000, "3D").with_timing(200.0, 220.0, 240.0, "µs"),
}
output = StringIO()
regression_found = comparator._write_performance_comparison(output, current_results, baseline_results)
# Average change using geometric mean: -5.5%
# This is significant improvement, so no regression found
assert not regression_found
result = output.getvalue()
assert "SUMMARY" in result
assert "Total benchmarks compared: 3" in result
assert f"Individual regressions (>{THRESHOLD_PERCENT}): 0" in result
expected_average_change = compute_average_time_change(current_results, baseline_results)
expected_average_line = f"Average time change: {expected_average_change:.1f}%"
assert expected_average_line in result
assert "✅ OVERALL OK" in result
def test_write_performance_comparison_missing_baseline(self, comparator) -> None:
"""Test performance comparison when some baselines are missing."""
current_results = [
BenchmarkData(1000, "2D").with_timing(105.0, 110.0, 115.0, "µs"),
BenchmarkData(3000, "2D").with_timing(300.0, 310.0, 320.0, "µs"), # No baseline
]
baseline_results = {
"1000_2D": BenchmarkData(1000, "2D").with_timing(95.0, 100.0, 105.0, "µs"),
}
output = StringIO()
regression_found = comparator._write_performance_comparison(output, current_results, baseline_results)
# Only one benchmark should be compared, regression could be found based on that single comparison
# In this case, we have 10% regression (110 vs 100), so regression should be detected
assert regression_found
result = output.getvalue()
assert "Total benchmarks compared: 1" in result
assert "3000 Points (2D)" in result # Should still show the benchmark without baseline
def test_write_performance_comparison_no_benchmarks(self, comparator) -> None:
"""Test performance comparison with no benchmarks."""
output = StringIO()
regression_found = comparator._write_performance_comparison(output, [], {})
# Should return False when no benchmarks to compare
assert not regression_found
@patch("benchmark_utils.get_git_commit_hash")
@patch("benchmark_utils.datetime")
def test_prepare_comparison_metadata(self, mock_datetime, mock_git, comparator, sample_baseline_content) -> None:
"""Test preparation of comparison metadata."""
# Mock current datetime
mock_now = Mock()
mock_now.strftime.return_value = "Thu Jun 15 14:30:00 PDT 2023"
mock_datetime.now.return_value.astimezone.return_value = mock_now
# Mock git commit
mock_git.return_value = "def456abc789"
metadata = comparator._prepare_comparison_metadata(sample_baseline_content)
assert metadata["current_date"] == "Thu Jun 15 14:30:00 PDT 2023"
assert metadata["current_commit"] == "def456abc789"
assert metadata["baseline_date"] == "2023-06-15 10:30:00 PDT"
assert metadata["baseline_commit"] == "abc123def456"
@patch("benchmark_utils.get_git_commit_hash")
def test_prepare_comparison_metadata_git_failure(self, mock_git, comparator, sample_baseline_content) -> None:
"""Test metadata preparation when git command fails."""
mock_git.side_effect = RuntimeError("Git not available")
metadata = comparator._prepare_comparison_metadata(sample_baseline_content)
assert metadata["current_commit"] == "unknown"
def test_regression_threshold_configuration(self, comparator) -> None:
"""Test that regression threshold can be configured."""
# Test default threshold
assert comparator.regression_threshold == DEFAULT_REGRESSION_THRESHOLD
# Test changing threshold
comparator.regression_threshold = 10.0
current = BenchmarkData(1000, "2D").with_timing(100.0, 107.0, 114.0, "µs")
baseline = BenchmarkData(1000, "2D").with_timing(95.0, 100.0, 105.0, "µs")
output = StringIO()
time_change, is_regression = comparator._write_time_comparison(output, current, baseline)
# 7% change should not be regression with 10% threshold
assert time_change == pytest.approx(7.0, abs=0.001) # Use pytest.approx for floating-point comparison
assert not is_regression
def test_write_error_file_baseline_not_found(self, comparator) -> None:
"""Test writing error file when baseline is not found."""
with tempfile.TemporaryDirectory() as temp_dir:
output_file = Path(temp_dir) / "error_results.txt"
baseline_file = Path(temp_dir) / "nonexistent_baseline.txt"
comparator._write_error_file(output_file, "Baseline file not found", baseline_file)
assert output_file.exists()
content = output_file.read_text()
assert "Comparison Results" in content
assert "❌ Error: Baseline file not found" in content
assert str(baseline_file) in content
assert "This error prevented the benchmark comparison from completing successfully" in content
def test_write_error_file_benchmark_error(self, comparator) -> None:
"""Test writing error file when benchmark execution fails."""
with tempfile.TemporaryDirectory() as temp_dir:
output_file = Path(temp_dir) / "error_results.txt"
error_message = "Failed to compile benchmarks: error[E0277]: trait bound not satisfied"
comparator._write_error_file(output_file, "Benchmark execution error", error_message)
assert output_file.exists()
content = output_file.read_text()
assert "❌ Error: Benchmark execution error" in content
assert error_message in content
assert "Please check the CI logs for more information" in content
def test_write_error_file_creates_parent_directory(self, comparator) -> None:
"""Test that _write_error_file creates parent directory if it doesn't exist."""
with tempfile.TemporaryDirectory() as temp_dir:
output_file = Path(temp_dir) / "nested" / "path" / "error_results.txt"
comparator._write_error_file(output_file, "Test error", "Test details")
assert output_file.exists()
assert output_file.parent.exists()
content = output_file.read_text()
assert "❌ Error: Test error" in content
def test_write_error_file_handles_write_failure(self, comparator) -> None:
"""Test that _write_error_file handles write failures gracefully."""
with tempfile.TemporaryDirectory() as temp_dir:
output_file = Path(temp_dir) / "error_results.txt"
# Mock Path.open to raise an exception
with patch.object(Path, "open", side_effect=OSError("Permission denied")):
# Should not raise exception, just log it
comparator._write_error_file(output_file, "Test error", "Test details")
# File should not exist due to write failure
assert not output_file.exists()
def test_sampling_warning_reports_dev_full_mismatch(self) -> None:
"""Test that comparison warns when baseline and current sampling modes differ."""
with tempfile.TemporaryDirectory() as temp_dir:
comparator = PerformanceComparator(Path(temp_dir))
baseline_content = f"""Date: 2023-12-15 10:30:00 UTC
Git commit: abc123
Sampling mode: dev
Cargo profile: {TRUSTED_BENCH_PROFILE}
Criterion sample size: 10
Criterion measurement time: 2
Criterion warm-up time: 1
"""
warning = comparator._sampling_warning(baseline_content, dev_mode=False)
assert "Sampling configuration differs from baseline" in warning
assert "sampling mode: baseline=dev, current=full" in warning
assert "Criterion sample size: baseline=10, current=criterion-default" in warning
assert "Criterion measurement time: baseline=2, current=criterion-default" in warning
assert "Criterion warm-up time: baseline=1, current=criterion-default" in warning
def test_sampling_warning_reports_missing_baseline_metadata(self, comparator, sample_baseline_content) -> None:
"""Test that legacy baselines without sampling metadata produce a warning."""
warning = comparator._sampling_warning(sample_baseline_content, dev_mode=False)
assert "Sampling configuration differs from baseline" in warning
assert "sampling mode: baseline=Unknown, current=full" in warning
assert f"Cargo profile: baseline=Unknown, current={TRUSTED_BENCH_PROFILE}" in warning
assert "Criterion sample size: baseline=Unknown, current=criterion-default" in warning
assert "Criterion measurement time: baseline=Unknown, current=criterion-default" in warning
assert "Criterion warm-up time: baseline=Unknown, current=criterion-default" in warning
class TestBaselineGenerator:
"""Test cases for BaselineGenerator benchmark execution."""
@staticmethod
def _sample_benchmark_results() -> list[BenchmarkData]:
"""Return a minimal parsed benchmark result set."""
return [BenchmarkData(10, "2D").with_timing(1.0, 2.0, 3.0, "µs")]
@patch("benchmark_utils.get_git_commit_hash", return_value="abc123")
@patch("benchmark_utils.CriterionParser.find_criterion_results")
@patch("benchmark_utils.run_cargo_command")
def test_generate_baseline_uses_perf_profile(self, mock_cargo, mock_find_results, mock_git) -> None:
"""Test that full baseline generation benchmarks with the trusted Cargo profile."""
mock_cargo.return_value = completed_process(CI_MANIFEST_STDOUT)
mock_find_results.return_value = self._sample_benchmark_results()