The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
ci: compare cache archive transfers in the review comment
ethernet19ed6e147ce7
diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yamlindex dfdc519a49b..f9ecadfdc1e 100644--- a/.github/workflows/ci.yaml+++ b/.github/workflows/ci.yaml@@ -495,6 +495,9 @@ jobs:# ─────────────────────────────────────────────────────────────────────ci-timings:name: CI timing report+ permissions:+ contents: read+ actions: read # download completed jobs' cache transfer logsneeds: [all-checks-pass]if: always()runs-on: blacksmith-4vcpu-ubuntu-2404diff --git a/scripts/ci/cache_report.py b/scripts/ci/cache_report.pynew file mode 100644index 00000000000..3ba333cbbab--- /dev/null+++ b/scripts/ci/cache_report.py@@ -0,0 +1,424 @@+"""Cache archive observability from ordinary actions/cache logs (no inventory scans).++Sizes are compressed archive bytes, never unpacked directory or per-file changes.+A progress total is evidence of size, not evidence that a restore/write succeeded.+"""++from __future__ import annotations++from datetime import datetime+from html import escape+import re+from typing import cast+++def _record(name: str, action: str) -> dict:+ return {+ "name": name, "action": action, "requested_key": None, "matched_key": None,+ "restore_status": "not-attempted" if action.endswith("/save") else "unknown",+ "restored_bytes": None, "save_status": "not-attempted", "saved_bytes": None,+ "saved_key": None, "warnings": [], "restore_warnings": [], "paths": [],+ }+++def _message(raw: str) -> tuple[str | None, str]:+ raw = re.sub(r"\x1b\[[0-9;]*m", "", raw)+ match = re.match(r"^(\d{4}-\d\d-\d\dT[\d:.]+(?:Z|[+-][\d:]+)) (.*)$", raw)+ return (match[1], match[2]) if match else (None, raw)+++def _stable_label(name: str) -> str:+ # GitHub uses the pinned action reference as the default top-level step name.+ return re.sub(r"(actions/cache(?:/restore|/save)?)@\S+", r"\1", name.removeprefix("Post "))+++class _CacheLogParser:+ def __init__(self, steps: list[dict]):+ self.entries: list[dict] = []+ self.phase: dict | None = None+ self.marker: str | None = None+ self.inputs = False+ self.path_input = False+ self.steps = [+ (datetime.fromisoformat(s["started_at"]).timestamp(),+ datetime.fromisoformat(s["completed_at"]).timestamp() + 1, s["name"])+ for s in steps if s.get("started_at") and s.get("completed_at")+ and s.get("conclusion") != "skipped"+ ]++ def _name(self, timestamp: str | None, action: str) -> str:+ step = None+ if timestamp:+ instant = datetime.fromisoformat(timestamp).timestamp()+ step = next((name for start, end, name in reversed(self.steps)+ if start <= instant < end), None)+ labels = [_stable_label(label) for label in (step, self.marker) if label]+ return " / ".join(dict.fromkeys(labels)) or action++ def _start(self, timestamp: str | None, action: str, save: bool):+ self.phase = {+ "entry": _record(self._name(timestamp, action), action), "save": save,+ "size": None, "received": None, "sent": None, "restored": False,+ "seen": False,+ }++ def _save_target(self, entry: dict) -> dict | None:+ key = entry["saved_key"] or entry["requested_key"]+ candidates = [e for e in reversed(self.entries) if e["save_status"] == "not-attempted"]+ if key:+ exact = next((e for e in candidates if e["requested_key"] == key), None)+ if exact is not None:+ return exact+ # Content-keyed saves compute a new key after the build. Their identical+ # transport paths identify which restored archive the write replaces.+ if entry["paths"]:+ return next((e for e in candidates if e["paths"] == entry["paths"]), None)+ if key:+ return None+ # Missing-path and other pre-upload failures can have no key in the post log.+ return next((e for e in candidates if e["name"] == entry["name"]), None)++ def _finish(self):+ phase, self.phase = self.phase, None+ self.inputs = False+ self.path_input = False+ if phase is None:+ return+ entry = phase["entry"]+ if phase["save"]:+ if not phase["seen"]:+ return+ if entry["save_status"] == "not-attempted":+ entry["save_status"] = "unknown"+ if entry["save_status"] == "saved":+ entry["saved_bytes"] = phase["sent"] if phase["sent"] is not None else phase["size"]+ target = self._save_target(entry)+ if target:+ for field in ("saved_key", "save_status", "saved_bytes"):+ target[field] = entry[field]+ target["warnings"].extend(entry["warnings"])+ return+ elif phase["restored"]:+ entry["restore_status"] = (+ "exact" if entry["requested_key"] == entry["matched_key"] else "fallback"+ )+ entry["restored_bytes"] = phase["size"] if phase["size"] is not None else phase["received"]+ elif entry["restore_status"] == "unknown" and entry["warnings"]:+ entry["restore_status"] = "failed"+ self.entries.append(entry)++ def _warning(self, phase: dict, line: str) -> bool:+ match = re.match(r"^(?:##\[(?:warning|error)\]|\[(?:warning|error)\])(.+)$", line)+ message = match[1] if match else line+ failure = message.startswith(("Failed to save:", "Failed to restore:", "Path Validation Error:"))+ if not match and not failure:+ return False+ phase["entry"]["warnings"].append(message)+ if not phase["save"]:+ phase["entry"]["restore_warnings"].append(message)+ # Unrelated actions also emit warnings during Post job cleanup.+ phase["seen"] = phase["seen"] or failure+ if phase["save"] and failure:+ phase["entry"]["save_status"] = "failed"+ key = re.search(r"with key (.+?)(?:,|$)", message)+ if key:+ phase["entry"]["requested_key"] = key[1]+ return True++ def _event(self, phase: dict, line: str):+ if self._warning(phase, line):+ return+ size = re.fullmatch(r"Cache Size: ~[\d.]+ MB \((\d+) B\)", line)+ progress = re.fullmatch(r"(Received|Sent) \d+ of (\d+) \([\d.]+%\), [\d.]+ MBs/sec", line)+ if size:+ phase["size"] = int(size[1])+ if progress:+ phase["received" if progress[1] == "Received" else "sent"] = int(progress[2])+ phase["seen"] = True+ if phase["save"]:+ self._save_event(phase, line)+ else:+ self._restore_event(phase, line)++ def _save_event(self, phase: dict, line: str):+ entry = phase["entry"]+ saved = re.fullmatch(r"Cache saved with key: (.+)", line)+ skipped = re.fullmatch(r"Cache hit occurred on the primary key (.+), not saving cache\.", line)+ if saved or skipped:+ phase["seen"] = True+ entry["saved_key"] = (saved or skipped)[1]+ entry["save_status"] = "saved" if saved else "skipped-exact-hit"++ def _restore_event(self, phase: dict, line: str):+ entry = phase["entry"]+ hit = re.fullmatch(r"Cache hit for(?: restore-key)?: (.+)", line)+ restored = re.fullmatch(r"Cache restored from key: (.+)", line)+ miss = re.fullmatch(r"Cache not found for input keys: (.+)", line)+ lookup = re.fullmatch(r"Cache found and can be restored from key: (.+)", line)+ if hit or restored or lookup:+ entry["matched_key"] = (hit or restored or lookup)[1]+ if entry["requested_key"] is None and hit and "restore-key" not in line:+ entry["requested_key"] = hit[1]+ if restored or line == "Cache restored successfully":+ phase["restored"] = True+ if miss:+ entry["restore_status"] = "miss"+ if entry["requested_key"] is None:+ entry["requested_key"] = miss[1].split(", ")[0]+ if lookup or line == "Lookup only - skipping download":+ entry["restore_status"] = "lookup-only"++ def feed(self, timestamp: str | None, line: str):+ start = re.fullmatch(r"##\[start-action display=(.*);id=[^\]]+\]", line)+ if start:+ self._finish()+ self.marker = start[1]+ return+ if line.startswith("##[end-action"):+ self._finish()+ self.marker = None+ return+ if line == "Post job cleanup.":+ self._finish()+ self._start(timestamp, "actions/cache", save=True)+ return+ if line.startswith("##[group]Run "):+ self._finish()+ action = re.fullmatch(r"##\[group\]Run (actions/cache(?:/restore|/save)?)@\S+", line)+ if action:+ self._start(timestamp, action[1], save=action[1].endswith("/save"))+ self.inputs = True+ else:+ self.marker = None+ return+ if line == "##[endgroup]":+ self.inputs = False+ return+ if self.phase is None:+ return+ if self.inputs:+ path = re.fullmatch(r" path: ?(.*)", line)+ if path:+ self.phase["entry"]["paths"] = [path[1]] if path[1] else []+ self.path_input = True+ elif re.match(r" [\w-]+:", line) or line in ("with:", "env:"):+ self.path_input = False+ elif self.path_input and line:+ self.phase["entry"]["paths"].append(line)+ key = re.fullmatch(r" key: (.+)", line)+ if key:+ self.phase["entry"]["requested_key"] = key[1]+ return+ self._event(self.phase, line)+++def parse_cache_log(log: str, steps: list[dict] | None = None) -> list[dict]:+ """Parse invocation-local cache receipts; absent archive sizes remain ``None``.++ Raw GitHub API steps supply top-level labels when composite markers are absent.+ Identities are label + occurrence, independent of content keys and post UUIDs.+ Restore-only and explicit-save actions with the same primary key are paired,+ without applying the combined action's exact-hit save guard to explicit saves.+ """+ parser = _CacheLogParser(steps or [])+ for raw in log.splitlines():+ parser.feed(*_message(raw))+ parser._finish()+ occurrences: dict[str, int] = {}+ for entry in parser.entries:+ # PRs use restore-only PM actions where main uses combined cache actions.+ labels = [re.sub(r"^(?:Cache|Restore|Save) ", "", label).removesuffix(" without saving")+ for label in entry["name"].split(" / ")]+ name = " / ".join(labels)+ occurrences[name] = occurrences.get(name, 0) + 1+ entry["occurrence"] = occurrences[name]+ entry["identity"] = f"{name} #{entry['occurrence']}"+ return parser.entries+++def _bytes(value: int | None, *, signed: bool = False) -> str:+ if value is None:+ return "unknown"+ exact = f"{value:+,}" if signed else f"{value:,}"+ if abs(value) < 1024:+ return f"{exact} B"+ mib = f"{value / (1024 * 1024):+.2f}" if signed else f"{value / (1024 * 1024):.2f}"+ return f"{mib} MiB ({exact} B)"+++def _observed(entry: dict | None, phase: str) -> int | None:+ if entry is None:+ return None+ status = entry[f"{phase}_status"]+ if phase == "restore" and status in ("exact", "fallback"):+ return entry["restored_bytes"]+ if phase == "save" and status == "saved":+ return entry["saved_bytes"]+ if (phase, status) == ("save", "skipped-exact-hit"):+ return 0+ if (phase, status) == ("restore", "miss") and not entry.get("restore_warnings", entry["warnings"]):+ return 0+ return None+++def _transfer(entry: dict | None, phase: str) -> str:+ if entry is None:+ return "not observed"+ status = entry[f"{phase}_status"]+ return f"{status} · {_bytes(_observed(entry, phase))}"+++def _delta(current: dict | None, main: dict | None, phase: str) -> str:+ a, b = _observed(current, phase), _observed(main, phase)+ return _bytes(a - b, signed=True) if a is not None and b is not None else "unknown"+++def _archive_delta(entry: dict | None) -> str:+ if entry is None or entry["save_status"] != "saved":+ return "not written" if entry and entry["save_status"] == "skipped-exact-hit" else "unknown"+ saved, restored = _observed(entry, "save"), _observed(entry, "restore")+ if saved is None or restored is None:+ return "unknown"+ result = _bytes(saved - restored, signed=True)+ return result + " (miss → 0 B)" if entry["restore_status"] == "miss" else result+++def _comparison_rows(timings: dict, baseline: dict | None) -> list[tuple[dict | None, dict | None]]:+ def identity(entry):+ return entry.get("job", ""), entry["identity"]++ main = (baseline or {}).get("cache_data", {}).get("entries", [])+ main_map = {identity(e): e for e in main}+ current = timings["cache_data"].get("entries", [])+ current_ids = {identity(e) for e in current}+ return ([(e, main_map.get(identity(e))) for e in current]+ + [(None, e) for e in main if identity(e) not in current_ids])+++def _totals(timings: dict) -> tuple[int, int, int]:+ restored = saved = unknown = 0+ for entry in timings["cache_data"].get("entries", []):+ if entry["restore_status"] in ("exact", "fallback"):+ if entry["restored_bytes"] is None:+ unknown += 1+ else:+ restored += entry["restored_bytes"]+ if entry["save_status"] == "saved":+ if entry["saved_bytes"] is None:+ unknown += 1+ else:+ saved += entry["saved_bytes"]+ return restored, saved, unknown+++def _summary(timings: dict, baseline: dict | None) -> str:+ restored, saved, _ = _totals(timings)+ result = f"Observed compressed archives: restored {_bytes(restored)}; saved {_bytes(saved)} (known sizes only)."+ if "cache_data" not in (baseline or {}):+ result += " No cache-aware main baseline."+ return result+++def _notes(timings: dict, baseline: dict | None) -> list[str]:+ data = timings["cache_data"]+ notes = [_summary(timings, baseline),+ f"Job logs collected: {data.get('jobs_collected', 0)}. "+ f"Unknown archive sizes: {_totals(timings)[2]} successful transfer(s)."]+ if data.get("unavailable_jobs"):+ notes.append("Unavailable job logs: " + ", ".join(data["unavailable_jobs"]))+ baseline_data = (baseline or {}).get("cache_data")+ if baseline_data is None:+ notes.append("No cache-aware main baseline; comparisons are unknown, not zero.")+ elif baseline_data.get("unavailable_jobs"):+ notes.append("Unavailable main job logs: " + ", ".join(baseline_data["unavailable_jobs"]))+ notes.append(+ "Per-cache restored/saved deltas compare observed bytes against main. "+ "Missing invocations or measurements are unknown, not zero. "+ "Archive Δ is saved compressed archive bytes minus restored compressed archive bytes, "+ "not per-file growth. A clean miss explicitly uses 0 B restored; exact-hit skips write no archive."+ )+ return notes+++def _cells(current: dict | None, main: dict | None) -> list[str]:+ entry = cast(dict, current if current is not None else main)+ return [entry.get("job", ""), entry["identity"],+ _transfer(current, "restore"), _delta(current, main, "restore"),+ _transfer(current, "save"), _delta(current, main, "save"), _archive_delta(current)]+++def _headers() -> tuple[str, ...]:+ return ("Job", "Cache invocation", "Restored", "Restored Δ vs main", "Saved",+ "Saved Δ vs main", "Archive Δ (saved − restored)")+++def _md(value: str) -> str:+ text = escape(str(value)).replace("\r", " ").replace("\n", " ")+ return re.sub(r"([\\`*_\[\]|])", r"\\\1", text)+++def _markdown(timings: dict, baseline: dict | None, limit: int | None = None, *, standalone: bool = True) -> str:+ rows = _comparison_rows(timings, baseline)+ displayed = rows if limit is None else rows[:limit]+ notes = _notes(timings, baseline)+ lines = ["### CI caches", "", _md(notes[0])] if standalone else []+ lines += [*[_md(note) for note in notes[1:]], "",+ "| " + " | ".join(_headers()) + " |", "| " + " | ".join(["---"] * len(_headers())) + " |"]+ for current, main in displayed:+ lines.append("| " + " | ".join(_md(cell) for cell in _cells(current, main)) + " |")+ if limit is not None and len(rows) > limit:+ lines += ["", f"Showing {limit} of {len(rows)} caches; see the full HTML report for all invocations and keys."]+ for current, main in displayed:+ entry = cast(dict, current if current is not None else main)+ for warning in entry["warnings"]:+ lines.append(f"- {_md(entry.get('job', ''))} / {_md(entry['identity'])}: {_md(warning)}")+ return "\n".join(lines)+++def render_cache_summary(timings: dict, baseline: dict | None) -> str:+ """Full Markdown per-cache table for the Actions summary."""+ return _markdown(timings, baseline) if "cache_data" in timings else ""+++def render_cache_html(timings: dict, baseline: dict | None) -> str:+ """An embeddable HTML section with every invocation and complete cache keys."""+ if "cache_data" not in timings:+ return ""+ parts = ['<section id="ci-caches"><h2>CI caches</h2>']+ parts += [f"<p>{escape(note)}</p>" for note in _notes(timings, baseline)]+ parts += ["<table><thead><tr>" + "".join(f"<th>{escape(h)}</th>" for h in _headers())+ + "</tr></thead><tbody>"]+ for current, main in _comparison_rows(timings, baseline):+ parts.append("<tr>" + "".join(f"<td>{escape(cell)}</td>" for cell in _cells(current, main)) + "</tr>")+ parts.append("</tbody></table>")+ for current, main in _comparison_rows(timings, baseline):+ entry = cast(dict, current if current is not None else main)+ label = f"{entry.get('job', '')} / {entry['identity']}"+ parts.append(f"<details><summary>{escape(label)}</summary>")+ for version, record in (("Current", current), ("Main", main)):+ parts.append(f"<h4>{version}</h4>")+ if record is None:+ parts.append("<p>not observed</p>")+ continue+ parts.append("<dl>")+ for title, field in (("Requested key", "requested_key"), ("Matched key", "matched_key"),+ ("Saved key", "saved_key")):+ parts.append(f"<dt>{title}</dt><dd><code>{escape(record.get(field) or 'unknown')}</code></dd>")+ parts.append("</dl>")+ parts += [f"<p>{escape(warning)}</p>" for warning in record["warnings"]]+ parts.append("</details>")+ return "\n".join([*parts, "</section>"])+++def cache_review_status(+ timings: dict, baseline: dict | None, report_url: str | None = None,+) -> list[dict]:+ """An informational cache section for the existing unified CI review comment."""+ if "cache_data" not in timings:+ return []+ result = {"kind": "info", "title": "CI caches", "summary": _summary(timings, baseline),+ "detail": _markdown(timings, baseline, limit=20, standalone=False)}+ if report_url:+ result["link"] = report_url+ result["link_label"] = "View report"+ return [{"source": "ci caches", "results": [result]}]diff --git a/scripts/ci/timings_report.py b/scripts/ci/timings_report.pyindex 61550d46a6f..de64d037bf2 100644--- a/scripts/ci/timings_report.py+++ b/scripts/ci/timings_report.py@@ -1,12 +1,12 @@#!/usr/bin/env python3-"""Collect CI job/step timings from the GitHub API and generate an HTML diff report.+"""Collect CI timings and cache transfers from GitHub and generate an HTML diff report.In CI, the script reads GITHUB_TOKEN, GITHUB_REPOSITORY, GITHUB_RUN_ID, andGITHUB_SHA from the environment to collect timings via the REST API.If a baseline JSON file (ci-timings-baseline.json by default) exists, the-report includes a diff with per-job and per-step deltas, plus a gantt chart-overlaying current vs baseline bars.+report includes per-job/step timing deltas, per-cache archive-byte comparisons,+and a gantt chart overlaying current vs baseline bars.Usage:# Collect from API (CI mode):@@ -28,6 +28,12 @@ import urllib.parseimport urllib.requestfrom datetime import datetimefrom html import escape+from pathlib import Path++if __package__ in (None, ""):+ sys.path.insert(0, str(Path(__file__).resolve().parents[2]))++from scripts.ci.cache_report import cache_review_status, parse_cache_log, render_cache_html, render_cache_summaryAPI_BASE = "https://api.github.com"@@ -143,6 +149,51 @@ def api_get(path: str, token: str, params: dict | None = None,return results+class _LogRedirect(urllib.request.HTTPRedirectHandler):+ def redirect_request(self, req, fp, code, msg, headers, newurl):+ redirected = super().redirect_request(req, fp, code, msg, headers, newurl)+ if redirected is not None:+ # The signed log blob rejects a second Authorization mechanism.+ redirected.remove_header("Authorization")+ return redirected+++def _job_log(job_id: int, repo: str, token: str) -> str:+ request = urllib.request.Request(f"{API_BASE}/repos/{repo}/actions/jobs/{job_id}/logs", headers={+ "Authorization": f"Bearer {token}",+ "Accept": "application/vnd.github+json",+ "X-GitHub-Api-Version": "2022-11-28",+ "User-Agent": "ci-timings-report",+ })+ try:+ with urllib.request.build_opener(_LogRedirect).open(request, timeout=30) as response:+ return response.read().decode("utf-8-sig", errors="replace")+ except urllib.error.HTTPError as error:+ # Do not retain signed blob URLs in the public report.+ raise OSError(f"job log HTTP {error.code}") from error+++def _collect_cache_data(jobs: list[dict], repo: str, token: str) -> dict:+ entries, unavailable = [], []+ collected = 0+ seen: set[int] = set()+ for job in jobs:+ job_id = job.get("job_id")+ if is_skipped(job) or not job_id or job_id in seen:+ continue+ seen.add(job_id)+ name = " / ".join(part for part in (job["workflow_name"], job["name"]) if part)+ try:+ parsed = parse_cache_log(_job_log(job_id, repo, token), job["steps"])+ except OSError as error:+ print(f"Cache data unavailable for {name}: {error}", file=sys.stderr)+ unavailable.append(name)+ continue+ collected += 1+ entries.extend(dict(entry, job=name, job_id=job_id, job_url=job["html_url"]) for entry in parsed)+ return {"entries": entries, "unavailable_jobs": unavailable, "jobs_collected": collected}++def parse_ts(ts: str | None) -> datetime | None:if not ts:return None@@ -288,6 +339,7 @@ def collect_timings(token: str, repo: str, run_id: str, head_sha: str) -> dict:"head_sha": head_sha,"created_at": created_at,"jobs": all_jobs,+ "cache_data": _collect_cache_data(all_jobs, repo, token),}@@ -849,6 +901,7 @@ def generate_html(timings: dict, baseline: dict | None = None) -> str:html += '<h2>Step Details</h2>\n'html += _step_details(timings, baseline)+ html += render_cache_html(timings, baseline)html += '</body>\n</html>\n'return html@@ -891,7 +944,7 @@ def generate_summary(timings: dict, baseline: dict | None = None) -> str:lines.append(f"| Jobs without baseline | {stats['no_baseline']} | — | — |")lines.append("")- return "\n".join(lines)+ return "\n".join(lines) + render_cache_summary(timings, baseline)# ---------------------------------------------------------------------------@@ -971,7 +1024,7 @@ def generate_review_status(result["link"] = report_urlresult["link_label"] = "View report"- return [{"source": "ci timing", "results": [result]}]+ return [{"source": "ci timing", "results": [result]}] + cache_review_status(timings, baseline, report_url)# ---------------------------------------------------------------------------diff --git a/tests/ci/test_cache_report.py b/tests/ci/test_cache_report.pynew file mode 100644index 00000000000..d9da6d2775a--- /dev/null+++ b/tests/ci/test_cache_report.py@@ -0,0 +1,258 @@+"""Compressed archive accounting follows cache receipts, not progress or key hashes."""++from __future__ import annotations++import importlib+++def _cache(name, key, events, *, action="actions/cache", minute=0):+ marker = f"##[start-action display={name};id=forward.{name}]" if name else ""+ lines = [marker, f"##[group]Run {action}@55cc8345863c7cc4c66a329aec7e433d2d1c52a9",+ "with:", f" key: {key}", " lookup-only: false", "##[endgroup]", *events]+ if name:+ lines.append(f"##[end-action id=forward.{name};outcome=success]")+ return "\n".join(f"2026-10-20T20:{minute:02d}:10.1234567Z {line}" for line in lines if line)+++def _post(name, events):+ return "\n".join([+ "Post job cleanup.",+ f"##[start-action display={name};id=__changed-uuid.{name}]",+ "Post job cleanup.", *events,+ f"##[end-action id=__changed-uuid.{name};outcome=success]",+ ])+++def test_cache_invocations_account_only_confirmed_phase_local_archives():+ report = importlib.import_module("scripts.ci.cache_report")+ first = "tools-" + "a" * 64+ second = "tools-" + "b" * 64+ log = "\n".join([+ _cache("PM tools", first, [+ "Cache hit for restore-key: tools-main",+ "Received 0 of 100 (0.0%), 0.0 MBs/sec",+ "Received 100 of 100 (100.0%), 1.0 MBs/sec",+ "Cache Size: ~0 MB (100 B)", "Cache restored successfully",+ "Cache restored from key: tools-main",+ ]),+ _cache("PM tools", second, [f"Cache not found for input keys: {second}"]),+ _cache("uv", "uv-key", [+ "Cache hit for: uv-key", "Cache Size: ~0 MB (40 B)",+ "Cache restored successfully", "Cache restored from key: uv-key",+ ]),+ _cache("npm", "npm-key", [+ "Cache found and can be restored from key: npm-key", "Lookup only - skipping download",+ ]),+ _cache("unknown size", "unknown-key", ["Cache restored from key: unknown-key"]),+ _cache("transport", "failed-key", [+ "##[warning]Failed to restore: service unavailable",+ "Cache not found for input keys: failed-key",+ ]),+ _cache("race", "race-key", ["Cache not found for input keys: race-key"]),+ _cache("failed restore", "broken-key", [+ "Cache hit for: broken-key", "Received 90 of 90 (100.0%), 1.0 MBs/sec",+ "Cache Size: ~0 MB (90 B)", "##[warning]Failed to restore: tar failed",+ ]),+ _cache(None, "modules-key", [+ "Cache hit for: modules-key", "Cache Size: ~0 MB (7 B)",+ "Cache restored from key: modules-key",+ ], minute=1),+ _cache("unconfirmed", "unconfirmed-key", ["Cache not found for input keys: unconfirmed-key"], minute=2),+ "##[group]Run echo 'Cache saved with key: fake'",+ "echo 'Cache Size: ~0 MB (99999 B)'", "##[endgroup]",+ "Cache saved with key: fake", # Shell output outside a cache action is not a receipt.+ _post("PM tools", [+ "Sent 0 of 200 (0.0%), 0.0 MBs/sec", "Sent 200 of 200 (100.0%), 1.0 MBs/sec",+ f"Cache saved with key: {second}",+ ]),+ _post("PM tools", [+ "Sent 150 of 150 (100.0%), 1.0 MBs/sec", f"Cache saved with key: {first}",+ ]),+ _post("uv", ["Cache hit occurred on the primary key uv-key, not saving cache."]),+ _post("race", [+ "Sent 500 of 500 (100.0%), 1.0 MBs/sec",+ "##[warning]Failed to save: Unable to reserve cache with key race-key, another job may be creating this cache.",+ ]),+ _post("unknown size", ["Cache saved with key: unknown-key"]),+ _post("unconfirmed", ["Sent 300 of 300 (100.0%), 1.0 MBs/sec"]),+ _post("Upload artifact", ["##[warning]unrelated cleanup warning"]),+ ])+ steps = [{"name": "Restore node_modules", "number": 9, "started_at": "2026-10-20T20:01:10Z",+ "completed_at": "2026-10-20T20:01:11Z"}]+ entries = report.parse_cache_log(log, steps)+ assert len(entries) == 10+ assert [(e["requested_key"], e["matched_key"], e["restore_status"], e["restored_bytes"],+ e["save_status"], e["saved_bytes"]) for e in entries] == [+ (first, "tools-main", "fallback", 100, "saved", 150),+ (second, None, "miss", None, "saved", 200),+ ("uv-key", "uv-key", "exact", 40, "skipped-exact-hit", None),+ ("npm-key", "npm-key", "lookup-only", None, "not-attempted", None),+ ("unknown-key", "unknown-key", "exact", None, "saved", None),+ ("failed-key", None, "miss", None, "not-attempted", None),+ ("race-key", None, "miss", None, "failed", None),+ ("broken-key", "broken-key", "failed", None, "not-attempted", None),+ ("modules-key", "modules-key", "exact", 7, "not-attempted", None),+ ("unconfirmed-key", None, "miss", None, "unknown", None),+ ]+ assert "service unavailable" in entries[5]["warnings"][0]+ assert "Unable to reserve" in entries[6]["warnings"][0]+ assert "tar failed" in entries[7]["warnings"][0]+ assert entries[8]["name"] == "Restore node_modules"+ assert len({e["identity"] for e in entries}) == len(entries)+ changed = report.parse_cache_log(log.replace(first, "tools-" + "c" * 64)+ .replace(second, "tools-" + "d" * 64), steps)+ assert [e["identity"] for e in changed] == [e["identity"] for e in entries]+++def test_reports_compare_each_invocation_without_fabricating_missing_bytes():+ report = importlib.import_module("scripts.ci.cache_report")++ def parsed(restore_size, save_size, suffix):+ log = "\n".join([+ _cache("tools|<svg>", "first-" + suffix, [+ "Cache hit for restore-key: previous-key",+ f"Cache Size: ~0 MB ({restore_size} B)", "Cache restored from key: previous-key",+ ]),+ _cache("tools|<svg>", "second-" + suffix, [+ "Cache not found for input keys: second-" + suffix,+ ]),+ _cache("unknown", "unknown-" + suffix, ["Cache restored from key: unknown-" + suffix]),+ _cache("failed", "failed-" + suffix, [+ "Cache not found for input keys: failed-" + suffix,+ ]),+ _post("tools|<svg>", [+ f"Sent {save_size} of {save_size} (100.0%), 1.0 MBs/sec",+ "Cache saved with key: first-" + suffix,+ ]),+ _post("tools|<svg>", [+ "Sent 200 of 200 (100.0%), 1.0 MBs/sec", "Cache saved with key: second-" + suffix,+ ]),+ _post("unknown", ["Cache saved with key: unknown-" + suffix]),+ _post("failed", [+ "Sent 99999 of 99999 (100.0%), 1.0 MBs/sec",+ "##[warning]Failed to save: finalization | <script>alert(1)</script>",+ ]),+ ])+ entries = report.parse_cache_log(log)+ entries += report.parse_cache_log("\n".join(+ _cache(f"lookup-{i:02d}", f"lookup-{i:02d}", [+ f"Cache found and can be restored from key: lookup-{i:02d}",+ ]) for i in range(21)+ ))+ return [dict(e, job="job|<svg>") for e in entries]++ current = {"cache_data": {"entries": parsed(100, 150, "a" * 64),+ "unavailable_jobs": ["lost|<script>"], "jobs_collected": 1}}+ baseline = {"cache_data": {"entries": parsed(90, 120, "b" * 64),+ "unavailable_jobs": [], "jobs_collected": 1}}+ # A baseline miss is a known absence of transfer, not a missing measurement.+ baseline["cache_data"]["entries"][1].update(+ restore_status="exact", restored_bytes=200, matched_key="older",+ save_status="skipped-exact-hit", saved_bytes=None,+ )+ markdown = report.render_cache_summary(current, baseline)+ html = report.render_cache_html(current, baseline)+ status = report.cache_review_status(current, baseline, "https://example.test/report.html")+ assert status[0]["source"] == "ci caches"+ result = status[0]["results"][0]+ assert result["kind"] == "info"+ assert result["title"] == "CI caches"+ assert result["link"] == "https://example.test/report.html"+ assert "restored 100 B" in result["summary"]+ assert "saved 350 B" in result["summary"]+ assert "Showing 20 of 25 caches" in result["detail"]+ assert "lookup-20" not in result["detail"]+ assert "lookup-20" in markdown and "lookup-20" in html+ assert html.count("<tr>") == len(current["cache_data"]["entries"]) + 1+ for rendered in (markdown, result["detail"]):+ assert "+10 B" in rendered # Restored bytes compared to this invocation on main.+ assert "+30 B" in rendered # Saved bytes compared to this invocation on main.+ assert "+50 B" in rendered # Saved minus restored, not a main comparison.+ assert "-200 B" in rendered and "+200 B" in rendered+ assert "miss → 0 B" in rendered+ assert "unknown" in rendered.lower() and "lookup-only" in rendered+ assert "finalization \\| <script>" in rendered+ assert "lost\\|<script>" in rendered+ assert "job\\|<svg>" in rendered+ assert "tools\\|<svg>" in rendered+ assert "per-file" in rendered+ assert "<script>" not in rendered and "<svg>" not in rendered+ assert "first-" + "a" * 64 in html and "previous-key" in html+ assert "Requested key" in html and "Matched key" in html+ assert "<script>" in html and "<script>" not in html+ assert "<svg>" in html and "<svg>" not in html+ assert "Unknown archive sizes: 2" in markdown+ for old_baseline in (None, {"jobs": []}):+ result = report.cache_review_status(current, old_baseline)[0]["results"][0]+ assert "no cache-aware main baseline" in result["summary"].lower()+ assert "link" not in result+ assert "no cache-aware main baseline" in result["detail"].lower()+ assert "+100 B" not in result["detail"]+ assert report.cache_review_status({}, baseline) == []+ assert report.render_cache_summary({}, baseline) == ""+ assert report.render_cache_html({}, baseline) == ""+ empty = {"cache_data": {"entries": [], "jobs_collected": 0, "unavailable_jobs": ["denied"]}}+ assert "denied" in report.cache_review_status(empty, baseline)[0]["results"][0]["detail"]+ assert "not observed" in report.render_cache_summary(empty, baseline)+++def test_restore_only_and_combined_actions_keep_the_same_comparison_identity():+ report = importlib.import_module("scripts.ci.cache_report")+ main = report.parse_cache_log("\n".join([+ _cache("Cache verified PM tools", "main-hash", [+ "Cache hit for: main-hash", "Cache Size: ~0 MB (100 B)",+ "Cache restored from key: main-hash",+ ]),+ _post("Cache verified PM tools", [+ "Cache hit occurred on the primary key main-hash, not saving cache.",+ ]),+ ]))+ current = report.parse_cache_log("\n".join([+ _cache("Restore verified PM tools without saving", "pr-hash", [+ "Cache hit for: pr-hash", "Cache Size: ~0 MB (120 B)",+ "Cache restored from key: pr-hash",+ ], action="actions/cache/restore"),+ _cache("Save verified PM tools", "pr-hash", [+ "Sent 150 of 150 (100.0%), 1.0 MBs/sec", "Cache saved with key: pr-hash",+ ], action="actions/cache/save"),+ ]))+ assert len(current) == 1+ assert current[0]["identity"] == main[0]["identity"]+ assert current[0]["save_status"] == "saved" and current[0]["saved_bytes"] == 150+ markdown = report.render_cache_summary({"cache_data": {"entries": current}},+ {"cache_data": {"entries": main}})+ assert "+20 B" in markdown and "+150 B" in markdown and "+30 B" in markdown+++def test_failed_save_does_not_obscure_a_clean_restore_miss():+ report = importlib.import_module("scripts.ci.cache_report")+ entry = report.parse_cache_log("\n".join([+ _cache("Cache downloads", "key", ["Cache not found for input keys: key"]),+ _post("Cache downloads", ["##[warning]Failed to save: finalization failed"]),+ ]))[0]+ main = dict(entry, restore_status="exact", restored_bytes=10, save_status="skipped-exact-hit")+ markdown = report.render_cache_summary({"cache_data": {"entries": [entry]}},+ {"cache_data": {"entries": [main]}})+ assert "miss · 0 B" in markdown and "-10 B" in markdown+ assert "failed · unknown" in markdown and "finalization failed" in markdown+++def test_content_key_changes_pair_restore_and_save_by_their_transport_paths():+ report = importlib.import_module("scripts.ci.cache_report")+ restore = _cache("Restore signature candidates", "before-build", [+ "Cache hit for restore-key: previous-signatures", "Cache Size: ~0 MB (100 B)",+ "Cache restored from key: previous-signatures",+ ], action="actions/cache/restore").replace("with:", "with:\n path: /cache/signatures\n/cache/policy")+ save = _cache("Save verified signatures", "after-build", [+ "Sent 140 of 140 (100.0%), 1.0 MBs/sec", "Cache saved with key: after-build",+ ], action="actions/cache/save").replace("with:", "with:\n path: /cache/signatures\n/cache/policy")+ unrelated = _cache("Save another cache", "another-key", [+ "Sent 10 of 10 (100.0%), 1.0 MBs/sec", "Cache saved with key: another-key",+ ], action="actions/cache/save").replace("with:", "with:\n path: /cache/other")+ entries = report.parse_cache_log("\n".join([restore, save, unrelated]))+ assert len(entries) == 2, "a content-key change still writes the same restored cache paths"+ assert entries[0]["restored_bytes"] == 100 and entries[0]["saved_bytes"] == 140+ assert entries[0]["saved_key"] == "after-build"+ assert entries[1]["restore_status"] == "not-attempted" and entries[1]["saved_bytes"] == 10+ summary = report.render_cache_summary({"cache_data": {"entries": entries}}, None)+ assert "+40 B" in summarydiff --git a/tests/ci/test_cache_report_collection.py b/tests/ci/test_cache_report_collection.pynew file mode 100644index 00000000000..559314541be--- /dev/null+++ b/tests/ci/test_cache_report_collection.py@@ -0,0 +1,84 @@+"""Exercise Actions log collection through the existing report/comment path."""+from __future__ import annotations++import json+import threading+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from urllib.parse import urlsplit++from scripts.ci import assemble_review_comment, timings_report+++def test_collected_cache_data_reaches_reports_without_forwarding_auth(monkeypatch):+ timestamp = "2026-10-20T12:00:01Z "+ messages = [+ "##[group]Run actions/cache/restore@fixture", "with:",+ " path: /cache", " key: fixture-v1-current", "##[endgroup]",+ "Cache hit for restore-key: fixture-v1-previous",+ "Received 100 of 100 (100.0%), 1.0 MBs/sec",+ "Cache Size: ~0 MB (100 B)", "Cache restored successfully",+ "Cache restored from key: fixture-v1-previous",+ ]+ log = "\n".join(timestamp + line for line in messages).encode()+ jobs = [{+ "id": number, "name": name, "status": "completed", "conclusion": conclusion,+ "started_at": "2026-10-20T12:00:00Z", "completed_at": "2026-10-20T12:00:02Z",+ "html_url": f"https://github.com/fixture/cache/actions/runs/42/job/{number}",+ "steps": [{"name": "Cache artifacts", "number": 1, "status": "completed", "conclusion": "success",+ "started_at": "2026-10-20T12:00:00Z", "completed_at": "2026-10-20T12:00:02Z"}],+ } for number, name, conclusion in [(101, "working", "success"), (102, "logs unavailable", "success"),+ (103, "not selected", "skipped")]]+ prefix = "/repos/fixture/cache/actions"+ routes = {+ f"{prefix}/runs/42": (200, {}, json.dumps({"created_at": "2026-10-20T12:00:00Z"}).encode()),+ f"{prefix}/runs/42/jobs": (200, {}, json.dumps({"jobs": jobs}).encode()),+ f"{prefix}/runs": (200, {}, b'{"workflow_runs": []}'),+ "/blob": (200, {}, log),+ }+ requests = []++ class Handler(BaseHTTPRequestHandler):+ def do_GET(self):+ path = urlsplit(self.path).path+ requests.append((path, self.headers.get("Authorization")))+ status, headers, body = routes.get(path, (404, {}, b"missing"))+ self.send_response(status)+ for name, value in headers.items():+ self.send_header(name, value)+ self.end_headers()+ self.wfile.write(body)++ def log_message(self, format: str, *args: object) -> None:+ pass++ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ address = f"http://127.0.0.1:{server.server_port}"+ routes[f"{prefix}/jobs/101/logs"] = (302, {"Location": address + "/blob"}, b"")+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ monkeypatch.setattr(timings_report, "API_BASE", address)+ try:+ current = timings_report.collect_timings("fixture-token", "fixture/cache", "42", "head")+ finally:+ server.shutdown()+ server.server_close()+ thread.join()++ assert "cache_data" in current, "CI collection must retain per-cache data in the baseline JSON"+ caches = current["cache_data"]+ assert caches["jobs_collected"] == 1+ assert caches["unavailable_jobs"] == ["logs unavailable"]+ assert len(caches["entries"]) == 1+ assert caches["entries"][0]["restored_bytes"] == 100+ assert ("/blob", None) in requests, "the signed log-blob hop must not receive the API bearer"+ assert (f"{prefix}/jobs/101/logs", "Bearer fixture-token") in requests+ assert not any("/jobs/103/" in path for path, _ in requests)++ old_baseline = {"jobs": current["jobs"]}+ statuses = timings_report.generate_review_status(current, old_baseline, "https://example.invalid/report")+ cache_status, = [s for s in statuses if s["source"] == "ci caches"]+ assert cache_status["results"][0]["link"] == "https://example.invalid/report"+ comment = assemble_review_comment.assemble(review_statuses_json=json.dumps(statuses))+ assert "CI caches" in comment and "logs unavailable" in comment+ assert "fixture-v1" in timings_report.generate_html(current, old_baseline)+ assert "CI caches" in timings_report.generate_summary(current, old_baseline)