-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathci_lib.py
More file actions
executable file
·1907 lines (1754 loc) · 77.8 KB
/
Copy pathci_lib.py
File metadata and controls
executable file
·1907 lines (1754 loc) · 77.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
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
"""
revalidate_pr.py — probe CI health by pushing per-SHA placebo PRs.
For every commit merged to main since --starting-sha, push a tiny placebo
diff on a per-SHA branch and open a Draft PR. Watch CI; on failure, retry
up to N times via gh run rerun --failed. On all-pass, close PR + delete
branch. Persist verdicts and per-attempt failures to a JSON cache.
Subcommands:
run one cycle (cron-friendly, idempotent)
status print DB state per SHA
report verdict + flake leaderboard
reset SHA drop a SHA's entry to re-probe from scratch
Run flags:
--starting-sha SHA first SHA to probe (required first run; persisted)
--parallelism N max in-flight probes (default 4)
--max-attempts N retries per SHA (default 3)
--stalled-after-hours H stall threshold (default 3)
--dry-run / --dryrun no writes; reads OK, prints what would happen
Cache: ~/.cache/dynamo-utils/ci-health.json
Clone: /tmp/ci_health/repo
Lock: /tmp/ci_health/launch.pid
"""
from __future__ import annotations
import argparse
import contextlib
import fcntl
import json
import logging
import os
import re
import subprocess
import sys
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Iterable
from zoneinfo import ZoneInfo
PT = ZoneInfo("America/Los_Angeles")
REPO = "ai-dynamo/dynamo"
RAW_LOG_DIR = Path(
os.environ.get("DYNAMO_UTILS_CACHE_DIR")
or str(Path.home() / ".cache" / "dynamo-utils")
) / "raw-log-text"
# Prefer the dashboard's commit checkout (kept up-to-date by update_html_pages.sh)
# over revalidate's stale /tmp clone.
_DEFAULT_CLONES = [
Path.home() / "dev" / "commits",
Path("/tmp/ci_health/repo"),
]
CLONE_PATH = next((p for p in _DEFAULT_CLONES if (p / ".git").exists()), _DEFAULT_CLONES[0])
# Match either:
# FAILED tests/foo/test_bar.py::TestClass::test_method[params] - reason (assertion fail)
# ERROR tests/foo/test_bar.py::test_method - RuntimeError: ... (fixture/setup error)
# with optional GH Actions timestamp prefix and ANSI color codes.
_PYTEST_FAILED_RE = re.compile(
r"^(?:\d{4}-\d{2}-\d{2}T[\d:.]+Z\s+)?(?:\x1b\[[0-9;]*m)?(?:FAILED|ERROR)\s+(\S+::\S+)"
)
# Required status checks on `main` (from repo rulesets, integration_id 15368).
# Everything else (runtime tests, docker builds, …) is optional but rolls up
# into the status-check aggregators. Refresh via:
# gh api repos/ai-dynamo/dynamo/rules/branches/main
# Status icons matching show_commit_history Legend & Key
# (see html_pages/ci_status_icons.py — kept inline here so this script
# stays a single file).
_ICON_GREEN = "#2da44e"
_ICON_RED = "#c83a3a"
_ICON_GREY = "#8c959f"
ICON_REQ_PASS = (
f'<span class="legend-icon" style="color:{_ICON_GREEN};" title="required passed">'
'<svg aria-hidden="true" viewBox="0 0 16 16" width="14" height="14" '
'class="octicon octicon-check-circle-fill" fill="currentColor">'
'<path fill-rule="evenodd" d="M8 16A8 8 0 108 0a8 8 0 000 16zm3.78-9.78a.75.75 0 00-1.06-1.06L7 9.94 5.28 8.22a.75.75 0 10-1.06 1.06l2 2a.75.75 0 001.06 0l4-4z"/>'
"</svg></span>"
)
ICON_OPT_PASS = (
f'<span class="legend-icon" style="color:{_ICON_GREEN};" title="optional passed">'
'<svg aria-hidden="true" viewBox="0 0 16 16" width="14" height="14" '
'class="octicon octicon-check" fill="currentColor">'
'<path fill-rule="evenodd" d="M13.78 4.22a.75.75 0 00-1.06 0L6.75 10.19 3.28 6.72a.75.75 0 10-1.06 1.06l4 4a.75.75 0 001.06 0l7.5-7.5a.75.75 0 000-1.06z"/>'
"</svg></span>"
)
ICON_REQ_FAIL = (
f'<span class="legend-icon" style="color:{_ICON_RED};" title="required failed">'
'<svg aria-hidden="true" viewBox="0 0 16 16" width="14" height="14" '
'class="octicon octicon-x-circle-fill" fill="currentColor">'
'<circle cx="8" cy="8" r="8" fill="currentColor"/>'
'<path d="M4.5 4.5l7 7m-7 0l7-7" stroke="#fff" stroke-width="2" stroke-linecap="round"/>'
"</svg></span>"
)
ICON_OPT_FAIL = (
f'<span class="legend-icon" style="color:{_ICON_RED};" title="optional failed">'
'<svg aria-hidden="true" viewBox="0 0 16 16" width="14" height="14" '
'class="octicon octicon-x" fill="currentColor">'
'<path fill-rule="evenodd" d="M3.72 3.72a.75.75 0 011.06 0L8 6.94l3.22-3.22a.75.75 0 111.06 1.06L9.06 8l3.22 3.22a.75.75 0 11-1.06 1.06L8 9.06l-3.22 3.22a.75.75 0 11-1.06-1.06L6.94 8 3.72 4.78a.75.75 0 010-1.06z"/>'
"</svg></span>"
)
ICON_RUN = (
f'<span class="legend-icon" style="color:{_ICON_GREY};" title="in progress">'
'<svg aria-hidden="true" viewBox="0 0 16 16" width="14" height="14" '
'class="octicon octicon-clock" fill="currentColor">'
'<path d="M8 1C4.1 1 1 4.1 1 8s3.1 7 7 7 7-3.1 7-7-3.1-7-7-7zm0 12c-2.8 0-5-2.2-5-5s2.2-5 5-5 5 2.2 5 5-2.2 5-5 5z"/>'
'<path d="M8 4v5l3 2"/></svg></span>'
)
REQUIRED_CHECKS = frozenset({
"copyright-checks",
"DCO",
"backend-status-check",
"dynamo-status-check",
"pre-merge-status-check",
"deploy-status-check",
})
# DEFAULT_MAX_ATTEMPTS: legacy fallback used in the per-SHA "Runs: N/M" header.
# Plumbed through entry["max_attempts"] when present; otherwise defaults to 1.
DEFAULT_MAX_ATTEMPTS = 1
logger = logging.getLogger("ci_lib")
# ---------- helpers ----------
def short_sha(sha: str) -> str:
return sha[:11]
def run(
cmd: list[str],
*,
cwd: Path | None = None,
check: bool = True,
env: dict[str, str] | None = None,
) -> subprocess.CompletedProcess:
logger.debug("$ %s", " ".join(cmd))
return subprocess.run(
cmd,
cwd=cwd,
check=check,
capture_output=True,
text=True,
env=env,
)
def gh_api(
path: str,
*,
method: str = "GET",
fields: list[tuple[str, str]] | None = None,
) -> Any:
cmd = ["gh", "api", path]
if method != "GET":
cmd += ["--method", method]
if fields:
for k, v in fields:
cmd += ["-f", f"{k}={v}"]
proc = run(cmd, check=False)
if proc.returncode != 0:
raise RuntimeError(f"gh api {path} failed: {proc.stderr.strip()}")
if not proc.stdout.strip():
return None
return json.loads(proc.stdout)
# ---------- DB I/O ----------
# ---------- git ----------
def commit_subject_pr_author(sha: str) -> tuple[str, int | None, str]:
"""Return (subject_without_pr_suffix, pr_number, author) for `sha`."""
proc = run(
["git", "show", "-s", "--format=%s%x1f%an", sha],
cwd=CLONE_PATH,
check=False,
)
if proc.returncode != 0:
return ("", None, "")
raw = proc.stdout.strip()
if "\x1f" not in raw:
return (raw, None, "")
subject_full, author = raw.split("\x1f", 1)
pr: int | None = None
subject = subject_full
m = re.search(r"\s*\(#(\d+)\)\s*$", subject_full)
if m:
pr = int(m.group(1))
subject = subject_full[: m.start()].rstrip()
return (subject, pr, author)
# ---------- gh ----------
# ---------- log fetching + pytest failure extraction ----------
def fetch_job_log(job_id: int) -> Path | None:
"""Fetch a job's log text into ~/.cache/dynamo-utils/raw-log-text/<job_id>.log.
Returns the cached path on success, None on failure. Cache-hits skip the fetch.
Reuses the existing dynamo-utils raw-log-text convention so logs cached by
other tools (commit dashboards, ci_log_errors) are reused.
"""
RAW_LOG_DIR.mkdir(parents=True, exist_ok=True)
out = RAW_LOG_DIR / f"{job_id}.log"
if out.exists() and out.stat().st_size > 0:
return out
# `gh api .../logs` follows the Azure-blob redirect and emits plain text.
proc = subprocess.run(
["gh", "api", f"repos/{REPO}/actions/jobs/{job_id}/logs"],
capture_output=True,
text=False,
check=False,
)
if proc.returncode != 0:
logger.warning(
"fetch log job_id=%s failed: %s",
job_id,
proc.stderr.decode("utf-8", errors="replace")[:200],
)
return None
if not proc.stdout:
return None
out.write_bytes(proc.stdout)
return out
def extract_pytest_failures(log_path: Path) -> list[str]:
"""Return sorted unique pytest test IDs from `FAILED tests/...::test` lines."""
found: set[str] = set()
try:
with log_path.open("r", errors="replace") as fh:
for line in fh:
m = _PYTEST_FAILED_RE.match(line)
if m:
found.add(m.group(1))
except OSError as e:
logger.warning("read %s: %s", log_path, e)
return sorted(found)
# Lazy-imported once per process. Reuses the production ci_log_errors engine.
_CI_LOG_ERRORS_LOADED = False
def _ensure_ci_log_errors():
global _CI_LOG_ERRORS_LOADED
if _CI_LOG_ERRORS_LOADED:
return True
utils_root = str(Path.home() / "utils")
if utils_root not in sys.path:
sys.path.insert(0, utils_root)
try:
global _categorize_error_log_lines, _extract_error_snippet_from_log_file, _html_highlight_error_keywords
from ci_log_errors.engine import categorize_error_log_lines as _categorize_error_log_lines # type: ignore
from ci_log_errors.snippet import extract_error_snippet_from_log_file as _extract_error_snippet_from_log_file # type: ignore
from ci_log_errors.render import html_highlight_error_keywords as _html_highlight_error_keywords # type: ignore
_CI_LOG_ERRORS_LOADED = True
return True
except Exception as e:
logger.warning("ci_log_errors unavailable: %s", e)
return False
# Strip GH Actions ISO timestamp prefix like "2026-04-29T17:15:55.4973999Z "
_TS_PREFIX_RE = re.compile(r"^\d{4}-\d{2}-\d{2}T[\d:.]+Z\s+")
# Strip ANSI escape sequences (color codes)
_ANSI_RE = re.compile(r"\x1b\[[0-9;]*m")
# Detect any line that contains an echo'd string — `echo "..."` or `echo '...'` —
# whether at line start (xtrace `+ echo "X"`) or inside a longer shell command
# (Docker `RUN ... echo "ERROR: ..."`). We skip error-keyword highlighting on
# these lines because the keyword is *literal text being echoed*, not a real error.
_ECHO_LINE_RE = re.compile(r"""\becho\s+["']""")
def render_snippet_html(snippet_text: str) -> str:
"""Render a snippet with red error-keyword highlighting only.
Deliberately does NOT use the production renderer's command-block / blue-line
detection — those highlight things like `git version`, `PYTEST_CMD=...`,
`docker run ...` which add noise without signal.
Strips: ANSI escapes, GH Actions timestamps, [[CMD]]...[[/CMD]] cut-paste
blocks, and lines that are just shell command-noise prelude (Run, group
markers, env: blocks).
"""
if not snippet_text:
return ""
# 1. Strip the cut-pasteable command boxes
cleaned = re.sub(r"\[\[CMD\]\].*?\[\[/CMD\]\]\n?", "", snippet_text, flags=re.DOTALL)
out_lines: list[str] = []
for raw in cleaned.splitlines():
# 2. Strip GH Actions timestamp prefix and ANSI codes
line = _ANSI_RE.sub("", _TS_PREFIX_RE.sub("", raw))
# 3. Drop pure noise lines (best-effort — keep error context)
s = line.strip()
if not s:
out_lines.append("")
continue
if s.startswith("##[group]") or s == "##[endgroup]":
continue
if s.startswith("Categories:") or s == "...":
continue
# 4. Plain-escape echo lines — keywords inside literal echo args are noise
# Matches: 'echo "X"', '+ echo "X"' (xtrace), ' echo X', etc.
if _ECHO_LINE_RE.match(line):
out_lines.append(_html_escape(line))
continue
# 5. Highlight error keywords (red), default-render rest as plain text
if _ensure_ci_log_errors():
try:
out_lines.append(_html_highlight_error_keywords(line))
continue
except Exception:
pass
out_lines.append(_html_escape(line))
# Collapse runs of empty lines
collapsed: list[str] = []
blank = False
for ln in out_lines:
if ln == "":
if not blank:
collapsed.append("")
blank = True
else:
collapsed.append(ln)
blank = False
return "\n".join(collapsed).strip("\n")
# ---------- state machine ----------
# ---------- subcommands ----------
def _job_conclusion(j) -> str:
"""Read conclusion from a jobs[name] entry (handles legacy str + new dict)."""
if isinstance(j, str):
return j
if isinstance(j, dict):
return j.get("conclusion") or "?"
return "?"
def _job_url(j) -> str | None:
"""Read html_url from a jobs[name] entry. None for legacy str format."""
if isinstance(j, dict):
return j.get("url")
return None
def _fmt_duration(secs: int) -> str:
"""Compact human-readable duration: Ns / MmSSs / HhMm / DdHhMm.
Single-digit minor components stay unpadded ('4h3m', '1d4h5m') except for
the seconds in MmSSs which we keep zero-padded so 5m09s and 5m59s line up
visually in stacked tables. Examples: 45s, 5m31s, 5m09s, 4h3m, 1d4h5m.
"""
if secs < 0:
return "—"
if secs < 60:
return f"{secs}s"
if secs < 3600:
return f"{secs // 60}m{secs % 60:02d}s"
if secs < 86400:
return f"{secs // 3600}h{(secs % 3600) // 60}m"
days, rem = divmod(secs, 86400)
return f"{days}d{rem // 3600}h{(rem % 3600) // 60}m"
def _job_timing(j, conclusion: str = "") -> tuple[str, str]:
"""Return (started_str, duration_str) for display.
For running jobs (conclusion in running/queued/pending) and a known
started_at, emits a `<span class='live-duration' data-started='<iso>'>`
that the page's JS ticker updates every second.
"""
if not isinstance(j, dict):
return "—", "—"
s = j.get("started_at")
c = j.get("completed_at")
started = "—"
duration = "—"
if s:
dt = _to_pt(s)
if dt:
started = dt.strftime("%H:%M:%S")
if s and c:
try:
ds = datetime.fromisoformat(s)
dc = datetime.fromisoformat(c)
duration = _fmt_duration(int((dc - ds).total_seconds()))
except Exception:
pass
elif s and conclusion in ("running", "queued", "pending"):
try:
ds = datetime.fromisoformat(s)
now = datetime.now(timezone.utc)
initial = _fmt_duration(int((now - ds).total_seconds()))
except Exception:
initial = "—"
duration = (
f"<span class='live-duration' data-started='{s}'>{initial}</span>"
)
return started, duration
_LIVE_DURATION_JS = """
<script>
(function() {
function pad(n) { return n < 10 ? "0" + n : "" + n; }
function fmt(secs) {
if (secs < 0) return "—";
if (secs < 60) return secs + "s";
if (secs < 3600) return Math.floor(secs / 60) + "m" + pad(secs % 60) + "s";
if (secs < 86400) return Math.floor(secs / 3600) + "h" + Math.floor((secs % 3600) / 60) + "m";
var days = Math.floor(secs / 86400);
var rem = secs % 86400;
return days + "d" + Math.floor(rem / 3600) + "h" + Math.floor((rem % 3600) / 60) + "m";
}
function _setOver90m(el, secs) {
// Toggle the red-class on the cell that contains this live span (and on
// the span itself in case CSS targets it directly). >90m == > 5400s.
var over = secs > 5400;
el.classList.toggle("duration-over-90m", over);
var td = el.closest("td");
if (td) td.classList.toggle("duration-over-90m", over);
}
function tick() {
var now = Date.now();
document.querySelectorAll(".live-duration").forEach(function(el) {
var s = el.getAttribute("data-started");
if (!s) return;
var t = Date.parse(s);
if (isNaN(t)) return;
var secs = Math.floor((now - t) / 1000);
el.textContent = fmt(secs);
_setOver90m(el, secs);
});
document.querySelectorAll(".live-duration-total").forEach(function(el) {
var fixed = parseInt(el.getAttribute("data-fixed") || "0", 10) || 0;
var liveAttr = el.getAttribute("data-live") || "";
var liveSecs = 0;
if (liveAttr) {
liveAttr.split(",").forEach(function(s) {
if (!s) return;
var t = Date.parse(s);
if (isNaN(t)) return;
liveSecs += Math.floor((now - t) / 1000);
});
}
var total = fixed + liveSecs;
el.textContent = fmt(total);
_setOver90m(el, total);
});
}
tick();
setInterval(tick, 1000);
})();
function toggleSnip(ev, id) {
var row = document.getElementById(id);
if (row) row.classList.toggle('show');
var tgt = ev.currentTarget || ev.target;
if (tgt) {
var tri = tgt.querySelector('.triangle-toggle');
if (tri) tri.classList.toggle('expanded');
}
ev.stopPropagation();
}
</script>
"""
def _descriptive_counts(entry: dict) -> str:
"""Long form for HTML: '76 pass, 2 fail, 12 running, 4 skipped'."""
attempts = entry.get("attempts", [])
if not attempts:
return "—"
jobs = attempts[-1].get("jobs", {})
if not jobs:
return "—"
cons = [_job_conclusion(v) for v in jobs.values()]
p = sum(1 for c in cons if c == "success")
f = sum(1 for c in cons if c in ("failure", "timed_out"))
r = sum(1 for c in cons if c in ("running", "queued", "pending"))
s = sum(1 for c in cons if c in ("skipped", "cancelled", "neutral"))
parts = [f"{p} pass", f"{f} fail", f"{r} running"]
if s:
parts.append(f"{s} skipped")
return ", ".join(parts)
def _pr_url(pr: int | None) -> str:
if not pr or pr == "-" or pr == -1:
return "-"
return f"https://github.com/{REPO}/pull/{pr}"
def _to_pt(iso: str | None) -> datetime | None:
"""Parse an ISO-8601 string and convert to Pacific time."""
if not iso:
return None
try:
return datetime.fromisoformat(iso).astimezone(PT)
except Exception:
return None
def _short_merge_date(iso: str | None) -> str:
"""'YYYY-MM-DD HH:MM:SS PT' in Pacific time."""
dt = _to_pt(iso)
if dt is None:
return "?"
return dt.strftime("%Y-%m-%d %H:%M:%S PT")
def _html_escape(s: str) -> str:
return (
s.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
.replace('"', """)
)
# ---------------------------------------------------------------------------
# History bar primitives — shared between the per-SHA Run-history and the
# aggregate-report PR-history. Each "cell" represents a single run or SHA;
# the bar is a horizontal sequence of cells (oldest left → newest right).
# ---------------------------------------------------------------------------
_HB_BG = {
"failed": "#c83a3a",
"passed": "#2da44e",
"other": "#d0d7de",
"missing": "#d0d7de",
}
# CSS for both bars + popup. Inject once per page that uses the bar.
HB_CSS = (
"<style>"
"a.hb-link { text-decoration: none; } "
"a.hb-link[target=\"_blank\"]::after { content: none; } "
".hb-pop-menu { visibility: hidden; opacity: 0; "
"transition: visibility 0s linear 500ms, opacity 150ms ease 350ms; "
"position: absolute; top: 11px; left: 0; z-index: 1000; background: #fff; "
"border: 1px solid #d0d7de; border-radius: 4px; "
"box-shadow: 0 4px 8px rgba(0,0,0,0.12); padding: 6px 8px; line-height: 1.5; "
"font-size: 12px; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; "
"min-width: 280px; white-space: nowrap; } "
".hb-pop:hover .hb-pop-menu, .hb-pop-menu:hover { "
"visibility: visible; opacity: 1; "
"transition: visibility 0s linear 0s, opacity 100ms ease 0s; } "
".hb-pop-menu .hb-pop-head { display: block; color: #586069; font-size: 11px; "
"padding-bottom: 4px; border-bottom: 1px solid #eaecef; margin-bottom: 4px; } "
".hb-pop-menu .hb-pop-item { display: block; padding: 2px 4px; color: #24292e; "
"text-decoration: none; border-radius: 3px; } "
".hb-pop-menu a.hb-pop-item:hover { background: #f6f8fa; } "
".hb-pop-menu a.hb-pop-item[target=\"_blank\"]::after { content: \" \\2197\"; color: #959da5; }"
"</style>"
)
def hb_popup_menu(head: str, items: list[dict]) -> str:
"""items: each dict has status, label_text, sublabels, url."""
rows = []
for it in items:
bg = _HB_BG.get(it.get("status", "other"), "#d0d7de")
label_color = (
"#c83a3a" if it.get("status") == "failed"
else ("#2da44e" if it.get("status") == "passed" else "#586069")
)
line = (
f"<span style='display:inline-block;width:8px;height:8px;"
f"border-radius:2px;background:{bg};margin-right:6px;"
f"vertical-align:middle;'></span>"
f"<span style='color:{label_color};font-weight:600;'>{_html_escape(it.get('label_text', ''))}</span>"
)
for sub in it.get("sublabels") or []:
line += f" <span style='color:#586069;'>{_html_escape(sub)}</span>"
url = it.get("url")
if url:
rows.append(
f"<a class='hb-pop-item' href='{_html_escape(url)}' "
f"target='_blank' rel='noopener noreferrer'>{line}</a>"
)
else:
rows.append(f"<span class='hb-pop-item'>{line}</span>")
return (
f"<span class='hb-pop-menu'>"
f"<span class='hb-pop-head'>{_html_escape(head)}</span>"
+ "".join(rows)
+ "</span>"
)
def hb_cell(
*,
status: str, # 'failed'|'passed'|'other'|'missing'
title: str, # plain-text tooltip (will be escaped)
href: str | None = None,
count_in_cell: int | None = None, # show inside cell when > 1
popup_html: str = "", # output of hb_popup_menu, optional
width: int = 9,
height: int = 11,
) -> str:
bg = _HB_BG.get(status, "#d0d7de")
base = (
f"display:inline-block; width:{width}px; height:{height}px; "
"vertical-align:middle;"
)
count_label = (
f"<span style='font-size:8px;color:#fff;font-weight:700;"
f"line-height:{height}px;text-align:center;display:block;'>"
f"{'+' if count_in_cell > 9 else count_in_cell}"
f"</span>"
if count_in_cell and count_in_cell > 1 else ""
)
cell_inner = (
f"<span class='hb-cell' style='{base} background:{bg};' "
f"title='{_html_escape(title)}'>{count_label}</span>"
)
# Hover-popup wrapper (preferred for multi-host cells).
if popup_html:
return (
f"<span class='hb-pop' style='display:inline-block;position:relative;"
f"margin-right:1px;line-height:0;'>{cell_inner}{popup_html}</span>"
)
# Single-link wrapper.
if href:
return (
f"<a class='hb-link' href='{_html_escape(href)}' "
f"target='_blank' rel='noopener noreferrer'>"
+ cell_inner.replace(base, base + " margin-right:1px;")
+ "</a>"
)
# Plain cell with margin.
return cell_inner.replace(base, base + " margin-right:1px;")
def hb_bar(cells: list[str], font_size: int = 10) -> str:
return (
f"<span style='display:inline-block;white-space:nowrap;"
f"font-family:\"SF Mono\",Consolas,monospace;font-size:{font_size}px;'>"
+ "".join(cells)
+ "</span>"
)
THEME_BOOTSTRAP_SCRIPT = """<script>
(function() {
var cookieName = 'dynamo-dashboard-theme';
var mode = 'auto';
try {
String(document.cookie || '').split(';').forEach(function(cookie) {
var parts = cookie.trim().split('=');
if (decodeURIComponent(parts[0] || '') === cookieName) {
mode = decodeURIComponent(parts.slice(1).join('=') || '') || 'auto';
}
});
} catch (e) {}
function resolvedTheme(value) {
if (value === 'light' || value === 'dark') return value;
try {
return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
} catch (e) {
return 'light';
}
}
document.documentElement.setAttribute('data-theme-mode', mode);
document.documentElement.setAttribute('data-theme', resolvedTheme(mode));
})();
</script>"""
THEME_CONTROL_HTML = """<span class="theme-switcher" role="group" aria-label="Dashboard theme">
<span class="theme-label">Theme</span>
<button type="button" data-theme-choice="auto" aria-pressed="false">Auto</button>
<button type="button" data-theme-choice="light" aria-pressed="false">Light</button>
<button type="button" data-theme-choice="dark" aria-pressed="false">Dark</button>
</span>"""
THEME_RUNTIME_SCRIPT = """<script>
(function() {
var cookieName = 'dynamo-dashboard-theme';
var media = null;
try {
media = window.matchMedia ? window.matchMedia('(prefers-color-scheme: dark)') : null;
} catch (e) {}
function resolvedTheme(value) {
if (value === 'light' || value === 'dark') return value;
return media && media.matches ? 'dark' : 'light';
}
function currentMode() {
try {
var found = 'auto';
String(document.cookie || '').split(';').forEach(function(cookie) {
var parts = cookie.trim().split('=');
if (decodeURIComponent(parts[0] || '') === cookieName) {
found = decodeURIComponent(parts.slice(1).join('=') || '') || 'auto';
}
});
return found;
} catch (e) {}
return 'auto';
}
function rememberMode(mode) {
try {
document.cookie = cookieName + '=' + encodeURIComponent(mode) + '; Max-Age=31536000; Path=/; SameSite=Lax';
} catch (e) {}
}
function applyTheme(mode) {
if (mode !== 'light' && mode !== 'dark') mode = 'auto';
document.documentElement.setAttribute('data-theme-mode', mode);
document.documentElement.setAttribute('data-theme', resolvedTheme(mode));
document.querySelectorAll('[data-theme-choice]').forEach(function(btn) {
btn.setAttribute('aria-pressed', String(btn.getAttribute('data-theme-choice') === mode));
});
}
document.addEventListener('DOMContentLoaded', function() {
applyTheme(currentMode());
document.querySelectorAll('[data-theme-choice]').forEach(function(btn) {
btn.addEventListener('click', function() {
var mode = btn.getAttribute('data-theme-choice') || 'auto';
rememberMode(mode);
applyTheme(mode);
});
});
});
if (media) {
var onChange = function() {
if ((document.documentElement.getAttribute('data-theme-mode') || 'auto') === 'auto') {
applyTheme('auto');
}
};
try { media.addEventListener('change', onChange); }
catch (e) { try { media.addListener(onChange); } catch (ignored) {} }
}
})();
</script>"""
_HTML_STYLE = """
<style>
body { font: 14px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
margin: 0; padding: 24px; background: #fafbfc; color: #24292e; max-width: 1400px; }
h1 { font-size: 20px; margin: 0 0 4px 0; }
h2 { font-size: 16px; margin: 24px 0 8px 0; padding-bottom: 4px; border-bottom: 1px solid #e1e4e8; }
.meta { color: #586069; font-size: 13px; margin-bottom: 16px; }
.meta span { margin-right: 16px; }
.meta code, code { background: #f6f8fa; padding: 2px 6px; border-radius: 3px; font-size: 12px;
font-family: "SF Mono", Consolas, monospace; }
a { color: #0366d6; text-decoration: none; }
a:hover { text-decoration: underline; }
a[target="_blank"]::after { content: " ↗"; font-size: 0.85em; color: #959da5; }
.verdict-good { color: #28a745; font-weight: 600; }
.verdict-bad { color: #d73a49; font-weight: 600; }
.verdict-pending { color: #bf6c00; font-weight: 600; }
.pill { display: inline-block; padding: 2px 8px; border-radius: 10px; font-size: 12px;
font-weight: 500; }
.pill-pass { background: #d4edda; color: #155724; }
.pill-fail { background: #f8d7da; color: #721c24; }
.pill-run { background: #cce5ff; color: #004085; }
table { border-collapse: collapse; margin: 8px 0 16px 0; font-size: 13px; width: 100%; }
th, td { text-align: left; padding: 6px 10px; border-bottom: 1px solid #eaecef; vertical-align: top; }
th { background: #f6f8fa; font-weight: 600; font-size: 12px; text-transform: uppercase;
letter-spacing: 0.05em; color: #586069; }
tr.fail td { background: #f5c6cb; }
/* Final attempt of the job failed → unrecovered regression. Darker red. */
tr.fail-final td { background: #ea868f; }
/* Earlier failure that the job later recovered from. Lighter red. */
tr.fail-flake td { background: #fbe4e6; }
tr.pass td { background: #c3e6cb; }
tr.run td { background: #b8daff; }
tr.skip td { background: #f0f0f0; color: #6a737d; }
details { background: #fff; border: 1px solid #d0d7de; border-radius: 6px;
margin: 8px 0; padding: 0; }
details > summary { cursor: pointer; padding: 10px 14px; font-weight: 600;
list-style: none; user-select: none; }
details > summary::-webkit-details-marker { display: none; }
details > summary::before { content: "▶ "; color: #586069; font-size: 11px;
display: inline-block; transition: transform 0.1s; }
details[open] > summary::before { transform: rotate(90deg); }
details > summary:hover { background: #f6f8fa; border-radius: 6px 6px 0 0; }
details[open] > summary { border-bottom: 1px solid #eaecef; border-radius: 6px 6px 0 0; }
details > .details-body { padding: 0 14px 12px 14px; }
.cat-list { font-size: 11px; color: #586069; font-family: "SF Mono", Consolas, monospace; }
.attempt-badge { display: inline-block; padding: 1px 7px; margin: 0 4px 2px 0;
border-radius: 10px; font-size: 11px; font-weight: 600;
white-space: nowrap;
font-variant-numeric: tabular-nums; font-family: "SF Mono", Consolas, monospace; }
td.attempts-cell { white-space: nowrap; min-width: 180px; }
td.cat-cell { white-space: nowrap; min-width: 200px; }
td.started-cell, td.duration-cell, td.status-cell, td.attempt-cell { white-space: nowrap; }
td.duration-outlier { font-weight: 700; }
/* Anything > 90 min is unusually slow — red on the per-SHA pages only
(per-job row Duration cell, attempt-overview Duration column, Total CI
time). JS tickers toggle the class as the clock crosses 5400s. The
commit-history index.html keeps its own (unrelated) styling. */
.duration-over-90m, td.duration-over-90m { color: #d73a49; }
.attempt-summary { margin: 12px 0 4px 0; }
.attempt-summary .pill { margin-right: 6px; }
.snip-toggle { cursor: pointer; user-select: none; display: inline-block;
margin-left: 6px; vertical-align: middle; }
.triangle-toggle { display: inline-block; transition: transform 300ms ease;
transform-origin: center; color: #586069; font-size: 14px;
margin-right: 4px; }
.triangle-toggle.expanded { transform: rotate(90deg); }
.legend-icon { display: inline-flex; vertical-align: text-bottom; margin: 0 1px; }
table.attempt-table { width: auto; min-width: 540px; }
table.attempt-table th, table.attempt-table td { text-align: center; white-space: nowrap; }
table.attempt-table td.num-zero { color: #959da5; font-variant-numeric: tabular-nums; }
table.attempt-table td.num-nz { color: #24292e; font-variant-numeric: tabular-nums; font-weight: 600; }
table.attempt-table td:first-child, table.attempt-table th:first-child { text-align: left; }
.req-badge { display: inline-block; padding: 0 5px; margin-left: 6px;
border-radius: 3px; font-size: 10px; font-weight: 600;
background: #d73a49; color: #fff; vertical-align: middle;
letter-spacing: 0.04em; text-transform: uppercase; }
.opt-badge { display: inline-block; padding: 0 5px; margin-left: 6px;
border-radius: 3px; font-size: 10px; font-weight: 600;
background: #e1e4e8; color: #586069; vertical-align: middle;
letter-spacing: 0.04em; text-transform: uppercase; }
.status-x { display: inline-block; width: 14px; height: 14px; line-height: 14px;
text-align: center; background: #d73a49; color: #fff;
border-radius: 50%; font-weight: 700; font-size: 10px;
font-family: "SF Mono", Consolas, monospace; }
.status-check { display: inline-block; width: 14px; height: 14px; line-height: 14px;
text-align: center; background: #28a745; color: #fff;
border-radius: 50%; font-weight: 700; font-size: 10px; }
.status-dot { display: inline-block; width: 14px; height: 14px; line-height: 14px;
text-align: center; color: #586069; font-size: 14px; }
tr.snippet-row { display: none; }
tr.snippet-row.show { display: table-row; }
tr.snippet-row > td { padding: 4px 14px 8px 14px; }
tr.snippet-row.fail-final > td { background: #ea868f; }
tr.snippet-row.fail-flake > td { background: #fbe4e6; }
tr.snippet-row > td { background: #f5c6cb; }
pre.snip { background: #0d1117; color: #e6edf3; font-size: 11px;
padding: 10px 12px; border-radius: 4px; overflow-x: auto;
margin: 4px 0 0 0; max-height: 320px; overflow-y: auto;
white-space: pre-wrap; word-break: break-word;
font-family: "SF Mono", Consolas, monospace; line-height: 1.45; }
.job-name { font-family: "SF Mono", Consolas, monospace; font-size: 12px; white-space: nowrap; }
.test-list { margin: 4px 0 0 16px; padding: 0; font-size: 12px;
color: #586069; font-family: "SF Mono", Consolas, monospace; }
.test-list li { margin: 2px 0; }
.summary { display: flex; gap: 16px; margin: 8px 0 16px 0; }
.summary-box { background: #fff; border: 1px solid #e1e4e8; border-radius: 6px;
padding: 12px 16px; min-width: 100px; }
.summary-box .label { color: #586069; font-size: 11px; text-transform: uppercase;
letter-spacing: 0.05em; }
.summary-box .value { font-size: 22px; font-weight: 600; margin-top: 4px; }
.index-table tr:hover td { background: #f6f8fa; }
:root {
color-scheme: light dark;
--bg: #fafbfc;
--surface: #fff;
--surface-muted: #f6f8fa;
--border: #d0d7de;
--border-muted: #eaecef;
--text: #24292e;
--text-inverse: #fff;
--muted: #586069;
--link: #0366d6;
--success: #28a745;
--danger: #d73a49;
--warning: #bf6c00;
--success-bg: #c3e6cb;
--success-chip-bg: #d4edda;
--success-chip-text: #155724;
--danger-bg: #f5c6cb;
--danger-final-bg: #ea868f;
--danger-flake-bg: #fbe4e6;
--danger-chip-bg: #f8d7da;
--danger-chip-text: #721c24;
--run-bg: #b8daff;
--run-chip-bg: #cce5ff;
--run-chip-text: #004085;
--skip-bg: #f0f0f0;
--skip-chip-bg: #eaeef2;
--sha-zero: #959da5;
--theme-chip-bg: rgba(36, 41, 46, 0.08);
}
html[data-theme="dark"] {
color-scheme: dark;
--bg: #0d1117;
--surface: #161b22;
--surface-muted: #21262d;
--border: #30363d;
--border-muted: #30363d;
--text: #e6edf3;
--text-inverse: #fff;
--muted: #8b949e;
--link: #58a6ff;
--success: #3fb950;
--danger: #ff7b72;
--warning: #d29922;
--success-bg: #17351f;
--success-chip-bg: #17351f;
--success-chip-text: #7ee787;
--danger-bg: #4a1f24;
--danger-final-bg: #7d2f38;
--danger-flake-bg: #3d2027;
--danger-chip-bg: #4a1f24;
--danger-chip-text: #ffb3ad;
--run-bg: #0d2d4d;
--run-chip-bg: #0d2d4d;
--run-chip-text: #79c0ff;
--skip-bg: #21262d;
--skip-chip-bg: #21262d;
--sha-zero: #6e7681;
--theme-chip-bg: rgba(139, 148, 158, 0.18);
}
h1 { display: flex; align-items: baseline; gap: 12px; flex-wrap: wrap; }
.theme-switcher {
display: inline-flex;
align-items: center;
gap: 4px;
margin-left: auto;
padding: 2px;
border-radius: 999px;
background: var(--theme-chip-bg);
color: var(--text);
font-size: 11px;
font-weight: 400;
}
.theme-switcher .theme-label {
padding: 2px 6px;
color: var(--muted);
font-weight: 600;
}
.theme-switcher button {
border: 0;
border-radius: 999px;
padding: 2px 8px;
background: transparent;
color: var(--text);
font: inherit;
cursor: pointer;
}
.theme-switcher button[aria-pressed="true"] {
background: var(--surface);
color: var(--text);
font-weight: 700;
box-shadow: inset 0 0 0 1px var(--border);
}
.theme-switcher button:hover { background: var(--surface-muted); }
html[data-theme="dark"] body { background: var(--bg); color: var(--text); }
html[data-theme="dark"] h2 { border-bottom-color: var(--border); }
html[data-theme="dark"] .meta,
html[data-theme="dark"] .cat-list,
html[data-theme="dark"] .triangle-toggle,
html[data-theme="dark"] .test-list,
html[data-theme="dark"] .summary-box .label { color: var(--muted); }
html[data-theme="dark"] a { color: var(--link); }
html[data-theme="dark"] code,
html[data-theme="dark"] .meta code { background: var(--surface-muted); color: var(--text); }
html[data-theme="dark"] th {
background: var(--surface-muted);
color: var(--muted);
}
html[data-theme="dark"] th,
html[data-theme="dark"] td { border-bottom-color: var(--border-muted); }
html[data-theme="dark"] details,
html[data-theme="dark"] .summary-box {
background: var(--surface);
border-color: var(--border);
}
html[data-theme="dark"] details > summary:hover,
html[data-theme="dark"] .index-table tr:hover td { background: var(--surface-muted); }
html[data-theme="dark"] details[open] > summary { border-bottom-color: var(--border-muted); }
html[data-theme="dark"] .v-good,
html[data-theme="dark"] .verdict-good { color: var(--success); }
html[data-theme="dark"] .v-bad,
html[data-theme="dark"] .verdict-bad,
html[data-theme="dark"] .duration-over-90m,