Debian Codegraph @

others/mbedtls/tf-psa-crypto/drivers/pqcp/mldsa-native/.github/actions/cbmc/report.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 # Copyright (c) The mldsa-native project authors
3 # SPDX-License-Identifier: Apache-2.0 OR ISC OR MIT
4
5 """CBMC proof results reporter for GitHub Actions."""
6
7 import argparse
8 import base64
9 import json
10 import os
11 import subprocess
12 import tempfile
13 from collections import namedtuple
14
15 # GitHub context
16 GITHUB_REPOSITORY = os.environ.get("GITHUB_REPOSITORY", "")
17 GITHUB_REF = os.environ.get("GITHUB_REF", "")
18 GITHUB_SHA = os.environ.get("GITHUB_SHA", "")[:7]
19
20 COMMENT_TAG = "cbmc-report"
21
22 # Status symbols
23 OK = "✅"
24 WARN = "⚠️"
25 FAIL = "❌"
26
27 ProofResult = namedtuple(
28 "ProofResult", ["name", "status", "current", "previous", "change"]
29 )
30
31
32 def get_args():
33 parser = argparse.ArgumentParser(description="CBMC proof results reporter")
34 parser.add_argument("--results-json", required=True)
35 parser.add_argument(
36 "--mldsa-parameter-set", required=True, choices=["44", "65", "87"]
37 )
38 parser.add_argument("--min-runtime", type=int, default=20)
39 parser.add_argument("--regression-threshold", type=float, default=1.5)
40 parser.add_argument("--gh-pages-branch", default="gh-pages")
41 parser.add_argument("--data-dir", default="dev/cbmc")
42 return parser.parse_args()
43
44
45 def get_pr_number():
46 """Get PR number from GitHub event."""
47 event_path = os.environ.get("GITHUB_EVENT_PATH")
48 if not event_path or not os.path.exists(event_path):
49 return None
50 with open(event_path) as f:
51 event = json.load(f)
52 return event.get("pull_request", {}).get("number")
53
54
55 def fetch_baseline(cfg):
56 """Fetch baseline data from gh-pages branch."""
57 baseline_file = f"{cfg.data_dir}/mldsa-{cfg.param_set}.json"
58 subprocess.run(
59 ["git", "fetch", "origin", cfg.gh_pages_branch, "--depth=1"],
60 capture_output=True,
61 )
62 result = subprocess.run(
63 ["git", "show", f"origin/{cfg.gh_pages_branch}:{baseline_file}"],
64 capture_output=True,
65 text=True,
66 )
67 if result.returncode == 0 and result.stdout.strip():
68 return json.loads(result.stdout)
69 return None
70
71
72 def render_table(rows):
73 """Render a markdown table from ProofResult rows."""
74 lines = [
75 "| Proof | Status | Current | Previous | Change |",
76 "|-------|--------|---------|----------|--------|",
77 ]
78 lines.extend(
79 f"| `{r.name}` | {r.status} | {r.current} | {r.previous} | {r.change} |"
80 for r in rows
81 )
82 return lines
83
84
85 def classify_proof(r, baseline_runtimes, cfg):
86 """Classify a single proof result, returning (ProofResult, is_alert)."""
87 name = r["name"]
88 base = baseline_runtimes.get(name, {})
89 base_val, base_failed = base.get("value"), base.get("status") == "failed"
90
91 if r.get("status") == "failed":
92 prev = "failed" if base_failed else (f"{base_val}s" if base_val else "-")
93 return ProofResult(name, FAIL, "-", prev, "-"), True
94
95 cur_val = r["value"]
96 if base_failed:
97 return ProofResult(name, OK, f"{cur_val}s", "failed", "fixed"), False
98 if base_val is None:
99 return ProofResult(name, OK, f"{cur_val}s", "-", "new"), False
100
101 ratio = cur_val / base_val if base_val > 0 else 1
102 change = f"{(ratio - 1) * 100:+.0f}%" if base_val > 0 else "-"
103 is_regression = cur_val >= cfg.min_runtime and ratio >= cfg.regression_threshold
104 status = WARN if is_regression else OK
105 return (
106 ProofResult(name, status, f"{cur_val}s", f"{base_val}s", change),
107 is_regression,
108 )
109
110
111 def compute_total_runtime(data):
112 """Compute total runtime from proof results."""
113 if not data:
114 return None
115 return sum(
116 r["value"] for r in data.get("runtimes", []) if r.get("status") != "failed"
117 )
118
119
120 def build_comment(current, baseline, cfg):
121 """Build the PR comment markdown."""
122 baseline_runtimes = {r["name"]: r for r in (baseline or {}).get("runtimes", [])}
123 alerts, all_rows = [], []
124
125 for r in current.get("runtimes", []):
126 result, is_alert = classify_proof(r, baseline_runtimes, cfg)
127 all_rows.append(result)
128 if is_alert:
129 alerts.append(result)
130
131 def sort_key(r):
132 return -1 if r.current == "-" else -int(r.current.rstrip("s"))
133
134 all_rows.sort(key=sort_key)
135
136 # Compute total runtimes and add as first row
137 cur_total = compute_total_runtime(current)
138 base_total = compute_total_runtime(baseline)
139 if base_total and base_total > 0:
140 total_ratio = cur_total / base_total
141 total_change = f"{(total_ratio - 1) * 100:+.1f}%"
142 total_status = WARN if total_ratio >= 1.25 else OK
143 else:
144 total_change = "-"
145 total_status = OK
146 total_row = ProofResult(
147 "**TOTAL**",
148 total_status,
149 f"{cur_total}s",
150 f"{base_total}s" if base_total else "-",
151 total_change,
152 )
153 all_rows.insert(0, total_row)
154 if total_status == WARN:
155 alerts.insert(0, total_row)
156
157 lines = [
158 f"<!-- {COMMENT_TAG}(start): mldsa-{cfg.param_set} -->",
159 f"## CBMC Results (ML-DSA-{cfg.param_set})",
160 "",
161 ]
162
163 if alerts:
164 lines += [f"{WARN} **Attention Required**", ""] + render_table(alerts) + [""]
165
166 total = current.get("summary", {}).get("total", len(all_rows))
167 lines += (
168 [
169 "<details>",
170 f"<summary>Full Results ({total} proofs)</summary>",
171 "",
172 ]
173 + render_table(all_rows)
174 + [
175 "",
176 "</details>",
177 "",
178 f"<!-- {COMMENT_TAG}(end): mldsa-{cfg.param_set} -->",
179 ]
180 )
181 return "\n".join(lines)
182
183
184 def post_or_update_comment(pr_number, body, cfg):
185 """Post or update PR comment."""
186 tag = f"<!-- {COMMENT_TAG}(start): mldsa-{cfg.param_set} -->"
187 result = subprocess.run(
188 [
189 "gh",
190 "api",
191 f"repos/{GITHUB_REPOSITORY}/issues/{pr_number}/comments",
192 "--jq",
193 f'.[] | select(.body | startswith("{tag}")) | .id',
194 ],
195 capture_output=True,
196 text=True,
197 )
198 existing_id = (
199 result.stdout.strip().split("\n")[0]
200 if result.returncode == 0 and result.stdout.strip()
201 else None
202 )
203
204 with tempfile.NamedTemporaryFile(mode="w", suffix=".md", delete=False) as f:
205 f.write(body)
206 tmp_path = f.name
207
208 try:
209 if existing_id:
210 subprocess.run(
211 [
212 "gh",
213 "api",
214 f"repos/{GITHUB_REPOSITORY}/issues/comments/{existing_id}",
215 "-X",
216 "PATCH",
217 "-F",
218 f"body=@{tmp_path}",
219 ],
220 check=True,
221 )
222 print(f"Updated existing comment {existing_id}")
223 else:
224 subprocess.run(
225 [
226 "gh",
227 "api",
228 f"repos/{GITHUB_REPOSITORY}/issues/{pr_number}/comments",
229 "-X",
230 "POST",
231 "-F",
232 f"body=@{tmp_path}",
233 ],
234 check=True,
235 )
236 print("Created new comment")
237 finally:
238 os.unlink(tmp_path)
239
240
241 def push_to_gh_pages(current, cfg):
242 """Push results to gh-pages branch using GitHub Contents API."""
243 file_path = f"{cfg.data_dir}/mldsa-{cfg.param_set}.json"
244 content_b64 = base64.b64encode(json.dumps(current, indent=2).encode()).decode()
245
246 result = subprocess.run(
247 [
248 "gh",
249 "api",
250 f"repos/{GITHUB_REPOSITORY}/contents/{file_path}?ref={cfg.gh_pages_branch}",
251 "--jq",
252 ".sha",
253 ],
254 capture_output=True,
255 text=True,
256 )
257 sha = result.stdout.strip() if result.returncode == 0 else ""
258
259 cmd = [
260 "gh",
261 "api",
262 f"repos/{GITHUB_REPOSITORY}/contents/{file_path}",
263 "-X",
264 "PUT",
265 "-F",
266 f"message=Update CBMC results for ML-DSA-{cfg.param_set} ({GITHUB_SHA})",
267 "-F",
268 f"content={content_b64}",
269 "-F",
270 f"branch={cfg.gh_pages_branch}",
271 ]
272 if sha:
273 cmd.extend(["-F", f"sha={sha}"])
274
275 subprocess.run(cmd, check=True)
276 print(f"Pushed results to {cfg.gh_pages_branch}")
277
278
279 def main():
280 args = get_args()
281 args.param_set = args.mldsa_parameter_set
282
283 with open(args.results_json) as f:
284 current = json.load(f)
285 baseline = fetch_baseline(args)
286
287 pr_number = get_pr_number()
288 if pr_number:
289 post_or_update_comment(pr_number, build_comment(current, baseline, args), args)
290 elif GITHUB_REF in ("refs/heads/main", "refs/heads/master"):
291 push_to_gh_pages(current, args)
292 else:
293 print(f"Not a PR and not main branch ({GITHUB_REF}), skipping")
294
295
296 if __name__ == "__main__":
297 main()