Repository navigation
Expand file tree
/
Copy pathperf_proof.py
More file actions
1438 lines (1262 loc) · 63.8 KB
/
Copy pathperf_proof.py
File metadata and controls
1438 lines (1262 loc) · 63.8 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
"""Changeset performance proof for bazel-diff.
This is the one tool a change's author runs to show that the change made bazel-diff faster or
leaner (or at least not slower or fatter). It takes a changeset -- two revisions, a revision plus
patches, or the uncommitted working tree -- builds a bazel-diff binary from each side, runs both
binaries on Bazel workspaces of several sizes, and measures what the *bazel-diff process* costs on
each: CPU time (user + system), peak resident memory, and wall time, with the Bazel server's own
CPU reported alongside. It then says, per workload, stage and metric, whether the candidate is
better, worse or indistinguishable from the base, and whether both sides produced byte-identical
hashes and the same impacted set.
Why a dedicated tool rather than `time` and a screenshot:
- **Interleaved A/B.** Every iteration runs base and candidate back to back, and the order flips
each iteration, so thermal throttling, page-cache state and whatever else drifts over a run
lands on both sides equally.
- **Process-exact numbers.** Each stage is reaped with ``os.wait4``, so CPU seconds and peak RSS
are the kernel's accounting for the bazel-diff process tree (bazel-diff plus the Bazel client it
spawns), not a sampled approximation. The Bazel *server* is a daemon outside that tree; its CPU
is read from its pid separately so a change that alters the query shape still shows up.
- **A statistical verdict.** Medians are compared and a two-sided Mann-Whitney U test decides
whether a difference beyond the noise threshold is real. "Improved" needs both a difference
larger than ``--threshold`` percent and ``p < --alpha``; a large but noisy difference is
reported as inconclusive, not as a win.
- **Correctness is part of the proof.** A faster binary that produces different hashes has
changed behaviour, not performance. Outputs from every run are compared against the first base
run; a mismatch fails the proof unless ``--allow-output-diff`` says the change is meant to
move the hashes.
The flow measured per workload and iteration is the README recipe, split into stages:
git checkout <base>; bazel shutdown
1. generate-hashes (cold Bazel server)
2. generate-hashes (warm server; bazel-diff's own cost is clearest here)
git checkout <head>
3. generate-hashes --depEdgesFile (warm server, dependency tracking on)
4. get-impacted-targets --depEdgesFile (no Bazel involved)
Workloads are the synthetic genrule workspaces of tools/firecracker/bench/gen_project.py (the
presets the nightly benches use: tiny, small, medium, large, xlarge) and, optionally, a real
repository and commit pair.
Usage (from a checkout; the harness builds from git, your tree is never modified):
# Prove HEAD against its merge-base with master on small + medium + large, 5 iterations.
python3 tools/perf/perf_proof.py
# Explicit revisions, or a patch series on top of a base, or the uncommitted working tree.
python3 tools/perf/perf_proof.py --base v70.0.0 --candidate my-branch
python3 tools/perf/perf_proof.py --base master --patch 0001-faster.patch --patch 0002.patch
python3 tools/perf/perf_proof.py --candidate WORKTREE
# Smoke run (tiny workload, 2 iterations), or more statistical power on one size.
python3 tools/perf/perf_proof.py --quick
python3 tools/perf/perf_proof.py --workload large --iterations 10
# Measure the harness's own noise floor: the base binary against itself.
python3 tools/perf/perf_proof.py --aa
Every Bazel invocation the harness makes, builds included, runs with ``--nohome_rc``; it is not
configurable, because a run that a developer's ``~/.bazelrc`` can shape is not reproducible.
Builds happen in a worktree under ``~/.cache/bazel-diff-perf-proof/`` that persists between runs,
so only the first run on a machine pays a cold Bazel build; later runs rebuild incrementally.
The harness is deliberately not a `py_binary`: it builds bazel-diff with `bazel build`, which
would deadlock on the output-base lock if the harness were itself launched via `bazel run`.
Python 3.9+, standard library only. See tools/perf/README.md.
"""
from __future__ import annotations
import argparse
import json
import math
import os
import platform
import re
import shutil
import statistics
import subprocess
import sys
import tempfile
import threading
import time
from dataclasses import dataclass, field
from itertools import combinations
from pathlib import Path
from typing import Any, Callable, Optional
sys.path.insert(0, str(Path(__file__).resolve().parent))
import tango_compare as tc # noqa: E402 (shared workload/subprocess helpers)
REPO_ROOT = tc.REPO_ROOT
BUILD_TARGET = tc.BUILD_TARGET
# Stage name -> description. Order is the order they run in per flow.
STAGES: list[tuple[str, str]] = [
("gen_base_cold", "generate-hashes @base, cold Bazel server"),
("gen_base_warm", "generate-hashes @base, warm Bazel server"),
("gen_head_deps", "generate-hashes @head --depEdgesFile, warm server"),
("impacted", "get-impacted-targets --depEdgesFile (no Bazel)"),
]
STAGE_NAMES = [s for s, _ in STAGES]
STAGE_LABELS = dict(STAGES)
# Metric key -> (label, unit). Lower is better for every metric.
METRICS: dict[str, tuple[str, str]] = {
"cpu_s": ("bazel-diff CPU (user+sys)", "s"),
"peak_rss_bytes": ("bazel-diff peak RSS", "MiB"),
"user_s": (" of which user", "s"),
"sys_s": (" of which sys", "s"),
"wall_s": ("wall time", "s"),
"bazel_cpu_s": ("Bazel server CPU", "s"),
}
# The metrics the overall verdict is built from. Wall time is reported but excluded by default:
# on the generate-hashes stages it is dominated by `bazel query`, whose variance has nothing to
# do with the change under test. `--verdict-metrics` overrides.
DEFAULT_VERDICT_METRICS = ("cpu_s", "peak_rss_bytes")
VERDICT_IMPROVED = "improved"
VERDICT_REGRESSED = "regressed"
VERDICT_UNCHANGED = "unchanged"
VERDICT_INCONCLUSIVE = "inconclusive"
VERDICT_INSUFFICIENT = "insufficient"
EXIT_OK = 0
EXIT_FAILURE = 1
EXIT_OUTPUT_MISMATCH = 2
EXIT_REGRESSED = 3
EXIT_NO_IMPROVEMENT = 4
# Exact Mann-Whitney enumeration is used while C(n+m, n) is at most this; above it the normal
# approximation (with tie and continuity corrections) is used.
EXACT_MAX_COMBINATIONS = 20000
RSS_SAMPLE_INTERVAL_S = 0.05
# Every Bazel invocation the harness makes, builds included, starts with this. A developer's
# ~/.bazelrc can change compilation flags, add a build event service, or alter query behaviour,
# so without it two runs on two machines are not comparable. It is not configurable.
MANDATORY_STARTUP_OPTIONS = ["--nohome_rc"]
log = tc.log
vlog = tc.vlog
# ----------------------------------------------------------------------------------------------
# Pure helpers (unit-tested in perf_proof_test.py; nothing here shells out)
# ----------------------------------------------------------------------------------------------
def startup_options_for(extra: str) -> list[str]:
"""The mandatory startup options followed by the user's extra ones. Anything that would
re-enable the home rc is refused, since it would make the run irreproducible."""
out = list(MANDATORY_STARTUP_OPTIONS)
for opt in extra.split():
if opt == "--home_rc" or opt.startswith("--home_rc="):
raise SystemExit(f"{opt} is not allowed: the harness always runs Bazel with --nohome_rc "
"so a ~/.bazelrc cannot shape the measurement")
if opt not in out:
out.append(opt)
return out
def maxrss_to_bytes(ru_maxrss: int, system: Optional[str] = None) -> int:
"""`ru_maxrss` is bytes on macOS and kibibytes everywhere else."""
system = system or platform.system()
return int(ru_maxrss) if system == "Darwin" else int(ru_maxrss) * 1024
def parse_ps_time(text: str) -> Optional[float]:
"""Parse the `[[H:]M:]S[.ss]` CPU time `ps -o utime`/`stime` prints (BSD/macOS)."""
text = text.strip()
if not text:
return None
parts = text.split(":")
try:
nums = [float(p) for p in parts]
except ValueError:
return None
if not 1 <= len(nums) <= 3:
return None
total = 0.0
for n in nums:
total = total * 60 + n
return total
def parse_proc_stat_cpu(stat_line: str, clk_tck: int) -> Optional[float]:
"""utime + stime (fields 14 and 15 of /proc/<pid>/stat) in seconds."""
rparen = stat_line.rfind(")")
if rparen < 0:
return None
fields = stat_line[rparen + 1:].split()
# After the comm field, index 0 is `state` (field 3), so utime (14) is index 11.
if len(fields) < 13:
return None
try:
return (int(fields[11]) + int(fields[12])) / float(clk_tck)
except ValueError:
return None
def parse_proc_status_rss(status_text: str) -> tuple[Optional[int], Optional[int]]:
"""(VmRSS, VmHWM) in bytes from /proc/<pid>/status."""
rss = hwm = None
for line in status_text.splitlines():
if line.startswith("VmRSS:"):
rss = int(line.split()[1]) * 1024
elif line.startswith("VmHWM:"):
hwm = int(line.split()[1]) * 1024
return rss, hwm
def median(xs: list[float]) -> Optional[float]:
return statistics.median(xs) if xs else None
def _ranks(values: list[float]) -> list[float]:
"""Average ranks (1-based) with ties sharing the mean rank."""
order = sorted(range(len(values)), key=lambda i: values[i])
ranks = [0.0] * len(values)
i = 0
while i < len(order):
j = i
while j + 1 < len(order) and values[order[j + 1]] == values[order[i]]:
j += 1
avg = (i + j + 2) / 2.0
for k in range(i, j + 1):
ranks[order[k]] = avg
i = j + 1
return ranks
def mann_whitney_p(a: list[float], b: list[float]) -> Optional[float]:
"""Two-sided Mann-Whitney U p-value for H0: the two samples come from one distribution.
Exact (by enumerating every labelling of the pooled sample) while the number of labellings is
small, otherwise the normal approximation with tie and continuity corrections. Returns None
when either sample is empty.
"""
n, m = len(a), len(b)
if n == 0 or m == 0:
return None
pooled = list(a) + list(b)
ranks = _ranks(pooled)
rank_sum_a = sum(ranks[:n])
u_obs = rank_sum_a - n * (n + 1) / 2.0
mu = n * m / 2.0
dev_obs = abs(u_obs - mu)
total = n + m
if math.comb(total, n) <= EXACT_MAX_COMBINATIONS:
hits = 0
count = 0
for idx in combinations(range(total), n):
count += 1
u = sum(ranks[i] for i in idx) - n * (n + 1) / 2.0
if abs(u - mu) >= dev_obs - 1e-9:
hits += 1
return hits / count
# Normal approximation.
tie_term = 0.0
seen: dict[float, int] = {}
for v in pooled:
seen[v] = seen.get(v, 0) + 1
for t in seen.values():
tie_term += t ** 3 - t
var = n * m / 12.0 * ((total + 1) - tie_term / (total * (total - 1)))
if var <= 0:
return 1.0
z = max(dev_obs - 0.5, 0.0) / math.sqrt(var)
return math.erfc(z / math.sqrt(2))
def min_achievable_p(n: int, m: int) -> float:
"""The smallest two-sided p the exact Mann-Whitney test can produce for sample sizes n and m
(the two most extreme labellings out of C(n+m, n))."""
if n == 0 or m == 0:
return 1.0
return min(1.0, 2.0 / math.comb(n + m, n))
def iterations_for_alpha(alpha: float) -> int:
"""Fewest equal-sized iterations whose extreme outcome is significant at alpha."""
n = 1
while min_achievable_p(n, n) >= alpha:
n += 1
return n
def compare_samples(base: list[float], cand: list[float], threshold_pct: float, alpha: float) -> dict[str, Any]:
"""Medians, relative change and the verdict for one (stage, metric). Lower is better."""
mb, mc = median(base), median(cand)
delta_pct: Optional[float] = None
if mb is not None and mc is not None and mb > 0:
delta_pct = (mc / mb - 1.0) * 100.0
p = mann_whitney_p(base, cand)
if len(base) < 2 or len(cand) < 2 or delta_pct is None:
verdict = VERDICT_INSUFFICIENT
elif abs(delta_pct) < threshold_pct:
verdict = VERDICT_UNCHANGED
elif min_achievable_p(len(base), len(cand)) >= alpha:
# No outcome of this many samples could be significant at alpha, so the difference can
# neither be confirmed nor dismissed: more iterations are needed, not a coin flip.
verdict = VERDICT_INSUFFICIENT
elif p is not None and p < alpha:
verdict = VERDICT_IMPROVED if delta_pct < 0 else VERDICT_REGRESSED
else:
verdict = VERDICT_INCONCLUSIVE
return {
"n_base": len(base),
"n_candidate": len(cand),
"base_median": mb,
"candidate_median": mc,
"base_min": min(base) if base else None,
"base_max": max(base) if base else None,
"candidate_min": min(cand) if cand else None,
"candidate_max": max(cand) if cand else None,
"delta_pct": delta_pct,
"p_value": p,
"verdict": verdict,
}
def overall_verdict(comparisons: list[dict[str, Any]]) -> str:
"""Fold the per-(workload, stage, metric) verdicts that drive the decision into one word.
Any regression wins (a change that speeds up one size and slows down another is not a proven
improvement); then any improvement; then too few samples to judge a difference; then
all-unchanged; otherwise inconclusive (differences beyond the threshold that the samples do
not confirm).
"""
verdicts = {c["verdict"] for c in comparisons}
if VERDICT_REGRESSED in verdicts:
return "REGRESSED"
if VERDICT_IMPROVED in verdicts:
return "IMPROVED"
if VERDICT_INSUFFICIENT in verdicts:
return "INSUFFICIENT DATA"
if verdicts and verdicts <= {VERDICT_UNCHANGED}:
return "NO CHANGE"
return "INCONCLUSIVE"
def classify_candidate(spec: Optional[str]) -> str:
"""'worktree' for the uncommitted tree, 'patch' for an existing .patch/.diff file, else 'rev'."""
if spec is None:
return "rev"
if spec.upper() == "WORKTREE":
return "worktree"
p = Path(spec)
if p.suffix.lower() in (".patch", ".diff") and p.is_file():
return "patch"
return "rev"
def json_dict_diff(ref_text: str, run_text: str, limit: int = 5) -> dict[str, Any]:
"""Describe how two JSON objects (hash maps) differ: keys only on one side, keys whose value moved."""
try:
ref = json.loads(ref_text)
run = json.loads(run_text)
except json.JSONDecodeError as e:
return {"parse_error": str(e)}
if not isinstance(ref, dict) or not isinstance(run, dict):
return {"identical": ref == run, "note": "not JSON objects"}
only_ref = sorted(set(ref) - set(run))
only_run = sorted(set(run) - set(ref))
changed = sorted(k for k in ref.keys() & run.keys() if ref[k] != run[k])
return {
"identical": not (only_ref or only_run or changed),
"only_in_reference": len(only_ref),
"only_in_run": len(only_run),
"changed": len(changed),
"examples": {
"only_in_reference": only_ref[:limit],
"only_in_run": only_run[:limit],
"changed": changed[:limit],
},
}
def fmt_metric(value: Optional[float], metric: str) -> str:
if value is None:
return "n/a"
if metric == "peak_rss_bytes":
return f"{value / (1024 * 1024):.1f} MiB"
return f"{value:.3f}s" if value < 10 else f"{value:.2f}s"
def fmt_delta(delta_pct: Optional[float]) -> str:
if delta_pct is None:
return "n/a"
return f"{delta_pct:+.1f}%"
def fmt_p(p: Optional[float]) -> str:
if p is None:
return "n/a"
return "<0.001" if p < 0.001 else f"{p:.3f}"
def _verdict_badge(v: str) -> str:
return {
VERDICT_IMPROVED: "**improved**",
VERDICT_REGRESSED: "**REGRESSED**",
VERDICT_UNCHANGED: "unchanged",
VERDICT_INCONCLUSIVE: "inconclusive",
VERDICT_INSUFFICIENT: "insufficient data",
}.get(v, v)
def render_summary(report: dict[str, Any]) -> str:
"""GitHub-flavored markdown: the verdict, the changeset, correctness, then a table per workload."""
cs = report["changeset"]
env = report["environment"]
cfg = report["config"]
out: list[str] = []
out.append(f"# bazel-diff perf proof: {cs['base']['describe']} → {cs['candidate']['describe']}")
out.append("")
headline = report["verdict"]
reasons = list(report.get("verdict_reasons", []))
if headline == "INSUFFICIENT DATA":
reasons.append(
f"{cfg['iterations']} iterations cannot reach α={cfg['alpha']:g}; run at least "
f"--iterations {iterations_for_alpha(cfg['alpha'])}"
)
elif headline == "INCONCLUSIVE":
reasons.append("the differences above were not statistically significant; rerun with more --iterations")
out.append(f"**Verdict: {headline}**" + (f" — {'; '.join(reasons)}" if reasons else ""))
if not report["outputs_consistent"]:
out.append("")
out.append(
"**⚠ Outputs differ between base and candidate** (hashes, dependency edges or impacted set). "
"This is a behaviour change, not a performance change; see Correctness."
+ (" `--allow-output-diff` was given, so this does not fail the proof." if cfg.get("allow_output_diff") else "")
)
if report.get("failures"):
out.append("")
out.append(f"**{len(report['failures'])} run(s) failed**; see Failures.")
out.append("")
out.append("| | base | candidate |")
out.append("|---|---|---|")
out.append(f"| source | {cs['base']['describe']} | {cs['candidate']['describe']} |")
out.append(f"| commit | `{cs['base'].get('commit') or 'n/a'}` | `{cs['candidate'].get('commit') or 'n/a'}` |")
out.append(f"| tree | `{cs['base'].get('tree') or 'n/a'}` | `{cs['candidate'].get('tree') or 'n/a'}` |")
out.append(f"| bazel-diff --version | {cs['base'].get('version') or 'n/a'} | {cs['candidate'].get('version') or 'n/a'} |")
out.append(f"| build | {cs['base'].get('build') or 'prebuilt'} | {cs['candidate'].get('build') or 'prebuilt'} |")
out.append("")
out.append(
f"Environment: {env.get('platform')}, {env.get('cpu_count')} CPUs, "
f"{env.get('mem_total_gib') or '?'} GiB RAM, Bazel {env.get('bazel_version')}, Python {env.get('python')}. "
f"{cfg['iterations']} interleaved iterations per workload (order alternates), "
f"threshold ±{cfg['threshold_pct']:g}%, α={cfg['alpha']:g}, verdict metrics: "
+ ", ".join(METRICS[m][0] for m in cfg["verdict_metrics"])
+ "."
)
out.append("")
out.append("## Correctness")
out.append("")
out.append("| workload | hashes (base rev) | hashes (head rev) | dependency edges | impacted set | impacted count |")
out.append("|---|---|---|---|---|---:|")
for wl in report["workloads"]:
c = wl["correctness"]
def mark(key: str) -> str:
v = c.get(key)
return "n/a" if v is None else ("identical" if v else "**DIFFERS**")
out.append(
f"| {wl['name']} | {mark('base_hashes')} | {mark('head_hashes')} | {mark('dep_edges')} | "
f"{mark('impacted')} | {c.get('impacted_count', 'n/a')} |"
)
out.append("")
for wl in report["workloads"]:
meta = wl.get("meta", {})
desc = ""
if wl.get("kind") == "synthetic":
desc = f" ({meta.get('packages')} packages, {meta.get('rule_targets')} rule targets)"
elif wl.get("kind") == "repo":
desc = f" ({meta.get('url')} {meta.get('from')}..{meta.get('to')})"
out.append(f"## {wl['name']}{desc}")
out.append("")
out.append("| stage | metric | base (median) | candidate (median) | Δ | p | verdict |")
out.append("|---|---|---:|---:|---:|---:|---|")
for stage in STAGE_NAMES:
first = True
for metric in METRICS:
cmp = wl["comparisons"].get(stage, {}).get(metric)
if cmp is None:
continue
label = STAGE_LABELS[stage] if first else ""
first = False
drives = metric in cfg["verdict_metrics"]
badge = _verdict_badge(cmp["verdict"]) if drives else f"_{cmp['verdict']}_"
out.append(
f"| {label} | {METRICS[metric][0]} | {fmt_metric(cmp['base_median'], metric)} | "
f"{fmt_metric(cmp['candidate_median'], metric)} | {fmt_delta(cmp['delta_pct'])} | "
f"{fmt_p(cmp['p_value'])} | {badge} |"
)
out.append("")
if report.get("failures"):
out.append("## Failures")
out.append("")
for f in report["failures"]:
out.append(f"- `{f['workload']}` {f['variant']} iteration {f['iteration']} {f['stage']}: {f['error']}")
out.append("")
out.append("## How to read this")
out.append("")
out.append(
"- Lower is better for every metric. Δ is the candidate's median relative to the base's; "
"p is a two-sided Mann-Whitney U test over the per-iteration samples."
)
out.append(
f"- A verdict of improved/regressed needs |Δ| ≥ {cfg['threshold_pct']:g}% **and** p < {cfg['alpha']:g}. "
"A large Δ with a high p is *inconclusive*: rerun with more `--iterations`."
)
out.append(
"- bazel-diff CPU and peak RSS are the kernel's accounting (`wait4`) for the bazel-diff process and the "
"Bazel client it spawns. Bazel server CPU is the daemon's CPU delta over the stage, read from its pid "
"(approximate). Wall time on the generate-hashes stages is mostly `bazel query`."
)
out.append(
"- Verdict metrics decide the headline; the others are shown in italics for context."
)
return "\n".join(out) + "\n"
# ----------------------------------------------------------------------------------------------
# Process measurement
# ----------------------------------------------------------------------------------------------
def read_process_cpu_seconds(pid: Optional[int]) -> Optional[float]:
"""utime + stime of a live process, or None when it is gone or unreadable."""
if pid is None or pid <= 0:
return None
stat = Path(f"/proc/{pid}/stat")
if stat.exists():
try:
return parse_proc_stat_cpu(stat.read_text(), os.sysconf("SC_CLK_TCK"))
except OSError:
return None
proc = subprocess.run(["ps", "-o", "utime=,stime=", "-p", str(pid)], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
if proc.returncode != 0 or not proc.stdout.strip():
return None
parts = proc.stdout.split()
if len(parts) != 2:
return None
u, s = parse_ps_time(parts[0]), parse_ps_time(parts[1])
return None if u is None or s is None else u + s
def _read_rss_bytes(pid: int) -> Optional[int]:
status = Path(f"/proc/{pid}/status")
if status.exists():
try:
rss, _ = parse_proc_status_rss(status.read_text())
return rss
except OSError:
return None
proc = subprocess.run(["ps", "-o", "rss=", "-p", str(pid)], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
if proc.returncode != 0 or not proc.stdout.strip():
return None
try:
return int(proc.stdout.strip()) * 1024
except ValueError:
return None
@dataclass
class Measurement:
ok: bool
returncode: Optional[int]
wall_s: float
user_s: float
sys_s: float
cpu_s: float
peak_rss_bytes: int
sampled_peak_rss_bytes: Optional[int]
bazel_cpu_s: Optional[float]
timed_out: bool = False
error: Optional[str] = None
def as_dict(self) -> dict[str, Any]:
return {
"ok": self.ok,
"returncode": self.returncode,
"wall_s": round(self.wall_s, 4),
"user_s": round(self.user_s, 4),
"sys_s": round(self.sys_s, 4),
"cpu_s": round(self.cpu_s, 4),
"peak_rss_bytes": self.peak_rss_bytes,
"sampled_peak_rss_bytes": self.sampled_peak_rss_bytes,
"bazel_cpu_s": None if self.bazel_cpu_s is None else round(self.bazel_cpu_s, 4),
"timed_out": self.timed_out,
"error": self.error,
}
def measure_process(
cmd: list[str],
cwd: Optional[Path],
log_path: Path,
timeout_s: float,
bazel_cpu_before: Optional[float] = None,
bazel_cpu_after: Optional[Callable[[], Optional[float]]] = None,
env: Optional[dict[str, str]] = None,
) -> Measurement:
"""Run `cmd` to completion and return the kernel's resource accounting for it.
The child is reaped with ``os.wait4`` so user/sys CPU and max RSS cover the whole process tree
bazel-diff waited for (itself and the Bazel client). A sampler thread also polls the main
process's RSS, as a cross-check and to enforce ``timeout_s``.
"""
vlog(f"$ {' '.join(cmd)}" + (f" (cwd={cwd})" if cwd else ""))
log_path.parent.mkdir(parents=True, exist_ok=True)
samples: list[int] = []
stop = threading.Event()
killed = {"timed_out": False}
with open(log_path, "wb") as logf:
t0 = time.monotonic()
proc = subprocess.Popen(cmd, cwd=str(cwd) if cwd else None, stdout=logf, stderr=subprocess.STDOUT, env=env)
def sampler() -> None:
deadline = t0 + timeout_s
while not stop.is_set():
rss = _read_rss_bytes(proc.pid)
if rss is not None:
samples.append(rss)
if time.monotonic() > deadline:
killed["timed_out"] = True
try:
proc.kill()
except OSError:
pass
return
stop.wait(RSS_SAMPLE_INTERVAL_S)
th = threading.Thread(target=sampler, daemon=True)
th.start()
_, status, ru = os.wait4(proc.pid, 0)
wall = time.monotonic() - t0
stop.set()
th.join()
# Tell Popen the child is gone so its finalizer does not try to reap it again.
proc.returncode = os.waitstatus_to_exitcode(status) if hasattr(os, "waitstatus_to_exitcode") else status
after = bazel_cpu_after() if bazel_cpu_after else None
bazel_cpu = None
if after is not None:
bazel_cpu = after - (bazel_cpu_before or 0.0)
rc = proc.returncode
ok = rc == 0 and not killed["timed_out"]
error = None
if killed["timed_out"]:
error = f"timed out after {timeout_s:.0f}s"
elif rc != 0:
tail = ""
try:
tail = "\n".join(log_path.read_text(errors="replace").splitlines()[-15:])
except OSError:
pass
error = f"exit {rc}: {' '.join(cmd)}\n{tail}"
return Measurement(
ok=ok,
returncode=rc,
wall_s=wall,
user_s=ru.ru_utime,
sys_s=ru.ru_stime,
cpu_s=ru.ru_utime + ru.ru_stime,
peak_rss_bytes=maxrss_to_bytes(ru.ru_maxrss),
sampled_peak_rss_bytes=max(samples) if samples else None,
bazel_cpu_s=bazel_cpu,
timed_out=killed["timed_out"],
error=error,
)
# ----------------------------------------------------------------------------------------------
# Changeset resolution and builds
# ----------------------------------------------------------------------------------------------
@dataclass
class Variant:
name: str # "base" | "candidate"
describe: str
commit: Optional[str] = None
tree: Optional[str] = None
patches: list[str] = field(default_factory=list)
binary: Optional[Path] = None
build: Optional[str] = None
version: Optional[str] = None
def as_dict(self) -> dict[str, Any]:
return {
"name": self.name,
"describe": self.describe,
"commit": self.commit,
"tree": self.tree,
"patches": self.patches,
"binary": str(self.binary) if self.binary else None,
"build": self.build,
"version": self.version,
}
def repo_git(*args: str) -> str:
return tc.git(REPO_ROOT, *args)
def short_describe(sha: str) -> str:
subject = repo_git("log", "-1", "--format=%s", sha)
if len(subject) > 60:
subject = subject[:57] + "..."
return f"{sha[:10]} {subject}"
def resolve_base(spec: Optional[str], main_branch: str) -> str:
if spec:
return repo_git("rev-parse", "--verify", spec + "^{commit}")
for ref in (main_branch, f"origin/{main_branch}"):
proc = tc.run(["git", "-C", REPO_ROOT, "merge-base", "HEAD", ref], check=False)
if proc.returncode == 0 and proc.stdout.strip():
return proc.stdout.strip()
raise SystemExit(
f"cannot find the merge-base of HEAD with {main_branch} or origin/{main_branch}; pass --base <rev>"
)
def snapshot_working_tree(workdir: Path) -> tuple[str, str]:
"""Commit the current working tree (tracked changes + untracked, non-ignored files) without
touching the real index or HEAD. Returns (commit, tree)."""
index = workdir / "worktree-snapshot.index"
env = dict(os.environ, GIT_INDEX_FILE=str(index))
tc.run(["git", "-C", REPO_ROOT, "read-tree", "HEAD"], env=env)
tc.run(["git", "-C", REPO_ROOT, "add", "-A"], env=env)
tree = tc.run(["git", "-C", REPO_ROOT, "write-tree"], env=env).stdout.strip()
head = repo_git("rev-parse", "HEAD")
commit = tc.run(
["git", "-C", REPO_ROOT, "commit-tree", tree, "-p", head, "-m", "perf_proof: working tree snapshot"],
env=dict(env, GIT_AUTHOR_NAME="perf_proof", GIT_AUTHOR_EMAIL="perf@bazel-diff.local",
GIT_COMMITTER_NAME="perf_proof", GIT_COMMITTER_EMAIL="perf@bazel-diff.local"),
).stdout.strip()
return commit, tree
def tree_of_worktree(worktree: Path, workdir: Path) -> str:
"""Tree hash of a worktree's current content (for provenance after applying patches)."""
index = workdir / "provenance.index"
env = dict(os.environ, GIT_INDEX_FILE=str(index))
tc.run(["git", "-C", worktree, "read-tree", "HEAD"], env=env)
tc.run(["git", "-C", worktree, "add", "-A"], env=env)
return tc.run(["git", "-C", worktree, "write-tree"], env=env).stdout.strip()
def rmtree_force(path: Path) -> None:
"""shutil.rmtree that copes with Bazel's write-protected output directories."""
def on_error(func, failed_path, _exc_info):
parent = Path(failed_path).parent
try:
os.chmod(parent, 0o700)
os.chmod(failed_path, 0o700)
func(failed_path)
except OSError:
pass
shutil.rmtree(path, onerror=on_error)
def git_common_dir() -> str:
return repo_git("rev-parse", "--path-format=absolute", "--git-common-dir")
def default_build_dir() -> Path:
"""A per-repository directory under the user's cache that survives between runs, so every
run after the first pays an incremental build (seconds) rather than a cold one (minutes:
a fresh output base re-fetches and rebuilds every crate and the toolchain)."""
root = Path(os.environ.get("XDG_CACHE_HOME") or (Path.home() / ".cache")) / "bazel-diff-perf-proof"
import hashlib
key = hashlib.sha1(git_common_dir().encode()).hexdigest()[:12]
return root / key
class SourceWorktree:
"""One detached git worktree the two variants are checked out into in turn, so the second
build is an incremental one on top of the first (the same thing a developer's build does).
The worktree and its Bazel output base live in a build directory that persists between runs
(see default_build_dir); the harness re-attaches to it when it is a worktree of this
repository and recreates it otherwise."""
def __init__(self, build_dir: Path, base_sha: str, bazel: str, startup_options: list[str], fresh: bool = False):
self.path = build_dir / "src"
self.output_base = build_dir / "bazel-output-base"
self.cargo_target = build_dir / "cargo-target"
self.bazel_startup = [*startup_options, f"--output_base={self.output_base}"]
if fresh and build_dir.exists():
log(f"removing build directory {build_dir}")
if self.output_base.exists() and self.path.is_dir():
# Bazel knows how to take its own output base apart (write-protected trees included).
tc.run([bazel, *self.bazel_startup, "clean", "--expunge"], cwd=self.path, check=False)
tc.run(["git", "-C", REPO_ROOT, "worktree", "remove", "--force", self.path], check=False)
rmtree_force(build_dir)
build_dir.mkdir(parents=True, exist_ok=True)
if self.path.exists() and self._is_our_worktree():
log(f"reusing build worktree {self.path}")
self.checkout(base_sha)
else:
if self.path.exists():
log(f"{self.path} is not a worktree of this repository; recreating it")
shutil.rmtree(self.path, ignore_errors=True)
tc.run(["git", "-C", REPO_ROOT, "worktree", "prune"], check=False)
log(f"checking out {base_sha[:10]} into {self.path}")
tc.run(["git", "-C", REPO_ROOT, "worktree", "add", "--detach", "--quiet", self.path, base_sha])
def _is_our_worktree(self) -> bool:
proc = tc.run(["git", "-C", self.path, "rev-parse", "--path-format=absolute", "--git-common-dir"], check=False)
return proc.returncode == 0 and proc.stdout.strip() == git_common_dir()
def checkout(self, sha: str) -> None:
tc.run(["git", "-C", self.path, "checkout", "--quiet", "--force", "--detach", sha])
tc.run(["git", "-C", self.path, "clean", "-fdq"])
def apply_patches(self, patches: list[Path]) -> None:
for p in patches:
log(f"applying {p}")
tc.run(["git", "-C", self.path, "apply", "--whitespace=nowarn", p.resolve()])
def build(self, builder: str, bazel: str, variant: Variant, dest: Path) -> None:
t0 = time.monotonic()
if builder == "bazel":
cmd = [
bazel, *self.bazel_startup, "build", BUILD_TARGET, "--config=release",
"--output_groups=-clippy_checks,-rustfmt_checks",
]
built = self.path / "bazel-bin" / "src" / "bazel-diff"
elif builder == "cargo":
cmd = ["cargo", "build", "--release", "--locked"]
built = self.cargo_target / "release" / "bazel-diff"
else:
raise SystemExit(f"unknown builder {builder}")
log(f"[{variant.name}] building: {' '.join(str(c) for c in cmd)}")
env = dict(os.environ)
if builder == "cargo":
env["CARGO_TARGET_DIR"] = str(self.cargo_target)
proc = tc.run(cmd, cwd=self.path, env=env, check=False)
if proc.returncode != 0:
tail = "\n".join(proc.stdout.splitlines()[-40:])
raise SystemExit(f"[{variant.name}] build failed ({proc.returncode}):\n{tail}")
dest.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(built.resolve(), dest)
dest.chmod(0o755)
variant.binary = dest
variant.build = f"{builder} ({'--config=release' if builder == 'bazel' else '--release'}), {time.monotonic() - t0:.0f}s"
def close(self, bazel: str) -> None:
"""Stop the build server; the worktree and output base stay for the next run."""
if self.output_base.exists():
tc.run([bazel, *self.bazel_startup, "shutdown"], cwd=self.path, check=False)
def bazel_diff_version(binary: Path) -> str:
proc = tc.run([binary, "--version"], check=False)
return proc.stdout.strip().splitlines()[-1] if proc.stdout.strip() else "unknown"
def resolve_changeset(args: argparse.Namespace, workdir: Path) -> tuple[Variant, Variant]:
base_sha = resolve_base(args.base, args.main_branch)
base = Variant(name="base", describe=short_describe(base_sha), commit=base_sha,
tree=repo_git("rev-parse", base_sha + "^{tree}"))
if args.aa:
cand = Variant(name="candidate", describe=f"{base.describe} (A/A: same binary)", commit=base_sha, tree=base.tree)
return base, cand
patches = [Path(p) for p in (args.patch or [])]
kind = classify_candidate(args.candidate)
if kind == "patch":
patches.insert(0, Path(args.candidate))
kind = "rev"
cand_sha = base_sha
elif kind == "worktree":
dirty = tc.run(["git", "-C", REPO_ROOT, "status", "--porcelain"], check=False).stdout.strip()
if not dirty:
log("note: the working tree is clean; WORKTREE is the same as HEAD")
cand_sha, _ = snapshot_working_tree(workdir)
else:
cand_sha = repo_git("rev-parse", "--verify", (args.candidate or "HEAD") + "^{commit}")
if not patches and not args.candidate:
dirty = tc.run(["git", "-C", REPO_ROOT, "status", "--porcelain", "--untracked-files=no"], check=False).stdout.strip()
if dirty:
log("note: the working tree has uncommitted changes that HEAD does not include; "
"pass --candidate WORKTREE to measure them")
for p in patches:
if not p.is_file():
raise SystemExit(f"patch not found: {p}")
if patches:
describe = f"{base_sha[:10]} + {len(patches)} patch(es): " + ", ".join(p.name for p in patches)
elif kind == "worktree":
describe = f"working tree ({repo_git('rev-parse', '--short=10', 'HEAD')} + uncommitted changes)"
else:
describe = short_describe(cand_sha)
if not patches and cand_sha == base_sha:
raise SystemExit(
f"base and candidate are the same commit ({base_sha[:10]}); nothing to compare. "
"Pass --candidate/--patch, or --aa to measure the noise floor."
)
cand = Variant(name="candidate", describe=describe, commit=cand_sha,
tree=None if patches else repo_git("rev-parse", cand_sha + "^{tree}"),
patches=[str(p) for p in patches])
return base, cand
def build_variants(args: argparse.Namespace, workdir: Path, base: Variant, cand: Variant) -> None:
bin_dir = workdir / "bin"
def adopt(variant: Variant, given: str) -> None:
src = Path(given)
if not src.is_file():
raise SystemExit(f"--{variant.name}-binary: no file at {src}")
dest = bin_dir / variant.name / "bazel-diff"
dest.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(src.resolve(), dest)
dest.chmod(0o755)
variant.binary = dest
variant.build = f"prebuilt ({src})"
if args.base_binary:
adopt(base, args.base_binary)
if args.candidate_binary:
adopt(cand, args.candidate_binary)
if args.aa and base.binary is None and cand.binary is not None:
base.binary = cand.binary
need_base = base.binary is None
need_cand = cand.binary is None and not args.aa
if need_base or need_cand:
build_dir = Path(args.build_dir).resolve() if args.build_dir else default_build_dir()
build_startup = startup_options_for(args.build_bazel_startup_options)
wt = SourceWorktree(build_dir, base.commit or "HEAD", args.build_bazel, build_startup, fresh=args.fresh_build)
try:
if need_base:
wt.build(args.builder, args.build_bazel, base, bin_dir / "base" / "bazel-diff")
if need_cand:
if cand.patches:
wt.checkout(base.commit)
wt.apply_patches([Path(p) for p in cand.patches])
cand.tree = tree_of_worktree(wt.path, workdir)
else:
wt.checkout(cand.commit)
wt.build(args.builder, args.build_bazel, cand, bin_dir / "candidate" / "bazel-diff")
finally:
wt.close(args.build_bazel)
log(f"build directory kept for the next run: {build_dir} (--fresh-build recreates it)")
if args.aa:
cand.binary = base.binary
cand.build = base.build
for v in (base, cand):
if v.binary is None or not v.binary.is_file():
raise SystemExit(f"{v.name}: no bazel-diff binary at {v.binary}")
v.version = bazel_diff_version(v.binary)
# ----------------------------------------------------------------------------------------------
# Workloads and the measured flow
# ----------------------------------------------------------------------------------------------
def bazel_server_pid(bazel: str, startup_options: list[str], workspace: Path) -> Optional[int]:
proc = tc.run([bazel, *startup_options, "info", "server_pid"], cwd=workspace, check=False)
# stderr is merged into stdout, so take the last line that is just a number.
pids = [line.strip() for line in proc.stdout.splitlines() if line.strip().isdigit()]
return int(pids[-1]) if pids else None
@dataclass
class FlowContext:
bazel: str
startup_options: list[str]
generate_args: list[str]
timeout_s: float
def run_flow(ctx: FlowContext, binary: Path, wl: tc.Workload, out_dir: Path) -> dict[str, Any]:
"""One pass of the four stages with one binary. Returns per-stage measurements and output paths."""
out_dir.mkdir(parents=True, exist_ok=True)
ws = wl.path
startup = " ".join(ctx.startup_options)
common = [str(binary)]
gen_common = ["generate-hashes", "-w", str(ws), "-b", ctx.bazel]
if startup:
gen_common.append(f"--bazelStartupOptions={startup}")
gen_common += ctx.generate_args
paths = {
"base_hashes": out_dir / "base.json",
"base_hashes_warm": out_dir / "base_warm.json",