|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +# Copyright 2026 The Dapr Authors |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | +# Unless required by applicable law or agreed to in writing, software |
| 8 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 9 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 10 | +# See the License for the specific language governing permissions and |
| 11 | +# limitations under the License. |
| 12 | + |
| 13 | +"""Run-environment capture and Markdown formatting for the benchmark report.""" |
| 14 | + |
| 15 | +from __future__ import annotations |
| 16 | + |
| 17 | +import os |
| 18 | +import platform |
| 19 | +import shutil |
| 20 | +import subprocess |
| 21 | +from dataclasses import dataclass |
| 22 | +from datetime import datetime, timezone |
| 23 | +from pathlib import Path |
| 24 | + |
| 25 | +from dapr.ext.workflow._bench_harness import IS_DARWIN, ScenarioMetrics, SustainedMetrics |
| 26 | + |
| 27 | + |
| 28 | +def _read_text(path: str) -> str: |
| 29 | + try: |
| 30 | + return Path(path).read_text(encoding='utf-8', errors='ignore') |
| 31 | + except OSError: |
| 32 | + return '' |
| 33 | + |
| 34 | + |
| 35 | +def _cpu_model() -> str: |
| 36 | + """Best-effort CPU model name. Cross-platform; returns a placeholder on failure.""" |
| 37 | + if IS_DARWIN: |
| 38 | + sysctl = shutil.which('sysctl') |
| 39 | + if sysctl is not None: |
| 40 | + try: |
| 41 | + out = subprocess.run( |
| 42 | + [sysctl, '-n', 'machdep.cpu.brand_string'], |
| 43 | + capture_output=True, |
| 44 | + text=True, |
| 45 | + timeout=2, |
| 46 | + ) |
| 47 | + if out.returncode == 0 and out.stdout.strip(): |
| 48 | + return out.stdout.strip() |
| 49 | + except (subprocess.SubprocessError, OSError): |
| 50 | + pass |
| 51 | + cpuinfo = _read_text('/proc/cpuinfo') |
| 52 | + for line in cpuinfo.splitlines(): |
| 53 | + if line.startswith('model name'): |
| 54 | + return line.split(':', 1)[1].strip() |
| 55 | + return platform.processor() or platform.machine() or 'unknown' |
| 56 | + |
| 57 | + |
| 58 | +def _total_memory_gb() -> float: |
| 59 | + """Best-effort total physical memory in GB. Returns 0 on failure.""" |
| 60 | + if IS_DARWIN: |
| 61 | + sysctl = shutil.which('sysctl') |
| 62 | + if sysctl is not None: |
| 63 | + try: |
| 64 | + out = subprocess.run( |
| 65 | + [sysctl, '-n', 'hw.memsize'], |
| 66 | + capture_output=True, |
| 67 | + text=True, |
| 68 | + timeout=2, |
| 69 | + ) |
| 70 | + if out.returncode == 0 and out.stdout.strip().isdigit(): |
| 71 | + return int(out.stdout.strip()) / (1024**3) |
| 72 | + except (subprocess.SubprocessError, OSError): |
| 73 | + pass |
| 74 | + meminfo = _read_text('/proc/meminfo') |
| 75 | + for line in meminfo.splitlines(): |
| 76 | + if line.startswith('MemTotal:'): |
| 77 | + parts = line.split() |
| 78 | + if len(parts) >= 2 and parts[1].isdigit(): |
| 79 | + return int(parts[1]) / (1024**2) |
| 80 | + return 0.0 |
| 81 | + |
| 82 | + |
| 83 | +def _git_commit() -> str: |
| 84 | + """Short git commit hash, or 'unknown' if not in a git repo.""" |
| 85 | + git = shutil.which('git') |
| 86 | + if git is None: |
| 87 | + return 'unknown' |
| 88 | + try: |
| 89 | + out = subprocess.run( |
| 90 | + [git, 'rev-parse', '--short', 'HEAD'], |
| 91 | + capture_output=True, |
| 92 | + text=True, |
| 93 | + timeout=2, |
| 94 | + cwd=Path(__file__).parent, |
| 95 | + ) |
| 96 | + if out.returncode == 0: |
| 97 | + commit = out.stdout.strip() |
| 98 | + # Mark dirty if there are uncommitted changes. |
| 99 | + status = subprocess.run( |
| 100 | + [git, 'status', '--porcelain'], |
| 101 | + capture_output=True, |
| 102 | + text=True, |
| 103 | + timeout=2, |
| 104 | + cwd=Path(__file__).parent, |
| 105 | + ) |
| 106 | + if status.returncode == 0 and status.stdout.strip(): |
| 107 | + return f'{commit}-dirty' |
| 108 | + return commit |
| 109 | + except (subprocess.SubprocessError, OSError): |
| 110 | + pass |
| 111 | + return 'unknown' |
| 112 | + |
| 113 | + |
| 114 | +@dataclass(slots=True) |
| 115 | +class RunEnvironment: |
| 116 | + """Snapshot of the machine the benchmark ran on.""" |
| 117 | + |
| 118 | + timestamp_utc: str |
| 119 | + git_commit: str |
| 120 | + python_version: str |
| 121 | + python_implementation: str |
| 122 | + platform: str |
| 123 | + os_release: str |
| 124 | + cpu_model: str |
| 125 | + cpu_logical_cores: int |
| 126 | + cpu_physical_cores_hint: int |
| 127 | + total_memory_gb: float |
| 128 | + is_ci: bool |
| 129 | + |
| 130 | + @classmethod |
| 131 | + def capture(cls) -> 'RunEnvironment': |
| 132 | + return cls( |
| 133 | + timestamp_utc=datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC'), |
| 134 | + git_commit=_git_commit(), |
| 135 | + python_version=platform.python_version(), |
| 136 | + python_implementation=platform.python_implementation(), |
| 137 | + platform=platform.platform(), |
| 138 | + os_release=f'{platform.system()} {platform.release()} ({platform.machine()})', |
| 139 | + cpu_model=_cpu_model(), |
| 140 | + cpu_logical_cores=os.cpu_count() or 0, |
| 141 | + cpu_physical_cores_hint=os.cpu_count() or 0, |
| 142 | + total_memory_gb=_total_memory_gb(), |
| 143 | + is_ci=any(os.environ.get(k) for k in ('CI', 'GITHUB_ACTIONS', 'TRAVIS', 'BUILDKITE')), |
| 144 | + ) |
| 145 | + |
| 146 | + |
| 147 | +def _format_environment_block(env: RunEnvironment) -> str: |
| 148 | + mem_str = f'{env.total_memory_gb:.1f} GB' if env.total_memory_gb > 0 else 'unknown' |
| 149 | + return ( |
| 150 | + '## Run environment\n' |
| 151 | + '\n' |
| 152 | + f'- **Timestamp**: {env.timestamp_utc}\n' |
| 153 | + f'- **Git commit**: `{env.git_commit}`\n' |
| 154 | + f'- **Python**: {env.python_implementation} {env.python_version}\n' |
| 155 | + f'- **OS**: {env.os_release}\n' |
| 156 | + f'- **CPU**: {env.cpu_model} ({env.cpu_logical_cores} logical cores)\n' |
| 157 | + f'- **Memory**: {mem_str}\n' |
| 158 | + '\n' |
| 159 | + 'Numbers are specific to this machine; the sync-vs-async gap is what transfers across' |
| 160 | + ' hardware, not the absolute values.' |
| 161 | + ) |
| 162 | + |
| 163 | + |
| 164 | +def _speedup_cell(speedup: float) -> str: |
| 165 | + if speedup > 1.2: |
| 166 | + dot = '🟢' |
| 167 | + elif speedup >= 0.8: |
| 168 | + dot = '⚪' |
| 169 | + else: |
| 170 | + dot = '🔴' |
| 171 | + return f'{dot} {speedup:.1f}x' |
| 172 | + |
| 173 | + |
| 174 | +def _format_comparison_table( |
| 175 | + rows: list[tuple[str, ScenarioMetrics, ScenarioMetrics]], |
| 176 | + key_label: str = 'N', |
| 177 | + show_async_rss: bool = False, |
| 178 | +) -> str: |
| 179 | + rss_header = ' Async RAM (MB) |' if show_async_rss else '' |
| 180 | + rss_rule = ' ---: |' if show_async_rss else '' |
| 181 | + header = ( |
| 182 | + f'| {key_label} | Sync (s) | Async (s) | Speedup |{rss_header}\n' |
| 183 | + f'| ---: | ---: | ---: | ---: |{rss_rule}\n' |
| 184 | + ) |
| 185 | + lines = [] |
| 186 | + for key, sync_m, async_m in rows: |
| 187 | + speedup = sync_m.wallclock_s / async_m.wallclock_s if async_m.wallclock_s > 0 else 0.0 |
| 188 | + rss = f' {async_m.peak_rss_delta_mb:.0f} |' if show_async_rss else '' |
| 189 | + lines.append( |
| 190 | + f'| {key} | {sync_m.wallclock_s:.2f} | {async_m.wallclock_s:.2f} |' |
| 191 | + f' {_speedup_cell(speedup)} |{rss}' |
| 192 | + ) |
| 193 | + return header + '\n'.join(lines) |
| 194 | + |
| 195 | + |
| 196 | +def _format_sustained_table(sync_m: SustainedMetrics, async_m: SustainedMetrics) -> str: |
| 197 | + def row(label: str, sync_val: str, async_val: str) -> str: |
| 198 | + return f'| {label} | {sync_val} | {async_val} |' |
| 199 | + |
| 200 | + header = '| Metric | Sync | Async |\n| --- | ---: | ---: |\n' |
| 201 | + rows = [ |
| 202 | + row( |
| 203 | + 'Effective throughput', |
| 204 | + f'{sync_m.throughput_per_s:.0f}/s', |
| 205 | + f'{async_m.throughput_per_s:.0f}/s', |
| 206 | + ), |
| 207 | + row( |
| 208 | + 'p99 latency', |
| 209 | + f'{sync_m.latency_overall.p99_ms:.0f} ms', |
| 210 | + f'{async_m.latency_overall.p99_ms:.0f} ms', |
| 211 | + ), |
| 212 | + row( |
| 213 | + 'p99 first quarter', |
| 214 | + f'{sync_m.latency_first_quarter.p99_ms:.0f} ms', |
| 215 | + f'{async_m.latency_first_quarter.p99_ms:.0f} ms', |
| 216 | + ), |
| 217 | + row( |
| 218 | + 'p99 last quarter', |
| 219 | + f'{sync_m.latency_last_quarter.p99_ms:.0f} ms', |
| 220 | + f'{async_m.latency_last_quarter.p99_ms:.0f} ms', |
| 221 | + ), |
| 222 | + ] |
| 223 | + return header + '\n'.join(rows) |
0 commit comments