The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
ci: summarize cache hits with main-aware job details
ethernet4f53b89a471e
diff --git a/scripts/ci/cache_report.py b/scripts/ci/cache_report.pyindex 3ba333cbbab..ded5d20e2d2 100644--- a/scripts/ci/cache_report.py+++ b/scripts/ci/cache_report.py@@ -9,12 +9,12 @@ from __future__ import annotationsfrom datetime import datetimefrom html import escapeimport re-from typing import cast+from urllib.parse import quote-def _record(name: str, action: str) -> dict:+def _record(name: str, action: str, step_number: int | None) -> dict:return {- "name": name, "action": action, "requested_key": None, "matched_key": None,+ "name": name, "step_number": step_number, "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": [],@@ -41,23 +41,24 @@ class _CacheLogParser:self.path_input = Falseself.steps = [(datetime.fromisoformat(s["started_at"]).timestamp(),- datetime.fromisoformat(s["completed_at"]).timestamp() + 1, s["name"])+ datetime.fromisoformat(s["completed_at"]).timestamp() + 1, s["name"], s.get("number"))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+ def _context(self, timestamp: str | None, action: str) -> tuple[str, int | None]:+ step, number = None, Noneif timestamp:instant = datetime.fromisoformat(timestamp).timestamp()- step = next((name for start, end, name in reversed(self.steps)- if start <= instant < end), None)+ step, number = next(((name, number) for start, end, name, number in reversed(self.steps)+ if start <= instant < end), (None, None))labels = [_stable_label(label) for label in (step, self.marker) if label]- return " / ".join(dict.fromkeys(labels)) or action+ return " / ".join(dict.fromkeys(labels)) or action, numberdef _start(self, timestamp: str | None, action: str, save: bool):+ name, number = self._context(timestamp, action)self.phase = {- "entry": _record(self._name(timestamp, action), action), "save": save,+ "entry": _record(name, action, number), "save": save,"size": None, "received": None, "sent": None, "restored": False,"seen": False,}@@ -261,164 +262,193 @@ def _observed(entry: dict | None, phase: str) -> int | None:return None-def _transfer(entry: dict | None, phase: str) -> str:+def _archive_size(entry: dict | None) -> int | None: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+ return None+ if entry["save_status"] == "saved":+ return entry["saved_bytes"]+ if entry["restore_status"] in ("exact", "fallback"):+ return entry["restored_bytes"]+ return None-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 _bucket(entry: dict) -> str:+ status = entry["restore_status"]+ if status in ("exact", "fallback"):+ return "hits"+ if status == "miss" and not entry.get("restore_warnings", entry["warnings"]):+ return "misses"+ if status == "not-attempted":+ return "saves without restore"+ return "unavailable"-def _notes(timings: dict, baseline: dict | None) -> list[str]:+def _view(timings: dict, baseline: dict | None) -> dict: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."- )+ is_main = timings.get("is_main", False)+ references = {(e.get("job", ""), e["identity"]): e+ for e in (baseline or {}).get("cache_data", {}).get("entries", [])}+ groups: dict[str, list[dict]] = {name: [] for name in ("hits", "misses", "unavailable", "saves without restore")}+ attempts, missed = [], []+ for entry in data.get("entries", []):+ group = _bucket(entry)+ groups[group].append(entry)+ if entry["restore_status"] not in ("not-attempted", "lookup-only"):+ attempts.append(entry)+ if group != "hits":+ reference = entry if is_main else references.get((entry.get("job", ""), entry["identity"]))+ missed.append(_archive_size(reference))+ return {"groups": groups, "attempts": len(attempts), "missed": missed,+ "references": references, "is_main": is_main, "data": data,+ "has_baseline": "cache_data" in (baseline or {})}+++def _amount(values: list[int | None], label: str) -> str:+ known = [value for value in values if value is not None]+ unknown = len(values) - len(known)+ result = f"{_bytes(sum(known))} {label}" if known or not values else f"{label}: unknown"+ return result + (f" (+{unknown} unknown sizes)" if unknown else "")+++def _summary(view: dict) -> str:+ groups = view["groups"]+ result = (f"{len(groups['hits'])} / {view['attempts']} cache hits; "+ f"{len(groups['misses'])} miss{'es' if len(groups['misses']) != 1 else ''}; "+ + _amount([e["restored_bytes"] for e in groups["hits"]], "restored")+ + " / " + _amount(view["missed"], "not restored"))+ if view["is_main"]:+ result += "; " + _amount([e["saved_bytes"] for rows in groups.values() for e in rows+ if e["save_status"] == "saved"], "saved")+ return result + "."+++def _notes(view: dict) -> list[str]:+ source = "newly saved archive sizes" if view["is_main"] else "the main-size reference"+ notes = [f"Compressed archive bytes. Not-restored bytes use {source}; missing sizes remain unknown."]+ if not view["is_main"] and not view["has_baseline"]:+ notes.append("No main archive reference yet; deltas and missed sizes are unknown.")+ if view["data"].get("unavailable_jobs"):+ notes.append("Unavailable job logs: " + ", ".join(view["data"]["unavailable_jobs"]))+ lookups = sum(e["restore_status"] == "lookup-only" for e in view["groups"]["unavailable"])+ if lookups:+ notes.append(f"{lookups} lookup-only checks excluded from restore attempts.")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)}")+def _link(entry: dict, html: bool) -> str:+ url = entry.get("job_url", "")+ if not url.startswith(("https://", "http://")):+ return "unavailable"+ number = entry.get("step_number")+ label = "view step" if number is not None else "view job"+ if number is not None:+ url += f"#step:{number}:1"+ if html:+ return f'<a href="{escape(url, quote=True)}">{label}</a>'+ return f"[{label}]({quote(url, safe='/:#?=&%')})"+++def _saved(entry: dict) -> str:+ status = entry["save_status"]+ if status in ("saved", "skipped-exact-hit"):+ return _bytes(_observed(entry, "save")) + (" (exact-hit skip)" if status == "skipped-exact-hit" else "")+ return status.replace("-", " ")+++def _headers(group: str, is_main: bool) -> list[str]:+ headers = ["Job", "Step", "Logs"]+ if group == "hits":+ headers += ["Restored", "Saved" if is_main else "Δ vs main"]+ elif group == "unavailable":+ headers.append("Status")+ if is_main:+ headers.append("Saved")+ elif is_main:+ headers.append("Saved")+ return headers+++def _cells(entry: dict, group: str, view: dict) -> list[str]:+ cells = [entry.get("job", ""), entry["name"]]+ if group == "hits":+ cells.append(_bytes(entry["restored_bytes"]))+ if view["is_main"]:+ cells.append(_saved(entry))+ else:+ reference = view["references"].get((entry.get("job", ""), entry["identity"]))+ size = _archive_size(reference)+ current = entry["restored_bytes"]+ cells.append(_bytes(current - size, signed=True) if current is not None and size is not None else "unknown")+ elif group == "unavailable":+ cells.append(entry["restore_status"])+ if view["is_main"]:+ cells.append(_saved(entry))+ elif view["is_main"]:+ cells.append(_saved(entry))+ return cells+++def _table(rows: list[dict], group: str, view: dict, html: bool) -> str:+ headers = _headers(group, view["is_main"])+ encode = escape if html else _md+ if html:+ lines = ["<table><thead><tr>" + "".join(f"<th>{escape(h)}</th>" for h in headers) + "</tr></thead><tbody>"]+ else:+ lines = ["| " + " | ".join(headers) + " |", "| " + " | ".join(["---"] * len(headers)) + " |"]+ for entry in rows:+ cells = [encode(cell) for cell in _cells(entry, group, view)]+ cells.insert(2, _link(entry, html))+ lines.append("<tr>" + "".join(f"<td>{cell}</td>" for cell in cells) + "</tr>" if html+ else "| " + " | ".join(cells) + " |")+ if html:+ lines.append("</tbody></table>")+ return "\n".join(lines)+++def _details(view: dict, html: bool) -> str:+ encode = escape if html else _md+ lines = ["<details>", "<summary>per-job cache results</summary>", ""]+ for group, rows in view["groups"].items():+ if group not in ("hits", "misses") and (not rows or (group == "saves without restore" and not view["is_main"])):+ continue+ lines += [f"<h3>{group}</h3>" if html else f"### {group}", ""]+ lines += [_table(rows, group, view, html) if rows else "none", ""]+ for note in _notes(view):+ lines.append(f"<p>{encode(note)}</p>" if html else encode(note) + "\n")+ for rows in view["groups"].values():+ for entry in rows:+ for warning in entry["warnings"]:+ text = encode(f"{entry.get('job', '')} / {entry['name']}: {warning}")+ lines.append(f"<p>{text}</p>" if html else f"- {text}")+ lines += ["", "</details>"]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 ""+ if "cache_data" not in timings:+ return ""+ view = _view(timings, baseline)+ return "### CI caches\n\n" + _summary(view) + "\n\n" + _details(view, html=False)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."""+ view = _view(timings, baseline)+ return ('<section id="ci-caches"><h2>CI caches</h2><p>' + escape(_summary(view)) + '</p>'+ + _details(view, html=True) + '</section>')+++def cache_review_status(timings: dict, baseline: dict | None, report_url: str | None = None) -> list[dict]: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)}+ view = _view(timings, baseline)+ result = {"kind": "info", "title": "CI caches", "summary": _summary(view), "detail": _details(view, html=False)}if report_url:- result["link"] = report_url- result["link_label"] = "View report"+ result.update(link=report_url, link_label="View report")return [{"source": "ci caches", "results": [result]}]diff --git a/scripts/ci/timings_report.py b/scripts/ci/timings_report.pyindex de64d037bf2..7903fa407d6 100644--- a/scripts/ci/timings_report.py+++ b/scripts/ci/timings_report.py@@ -338,6 +338,9 @@ def collect_timings(token: str, repo: str, run_id: str, head_sha: str) -> dict:"run_id": run_id,"head_sha": head_sha,"created_at": created_at,+ "is_main": (run_info.get("head_branch") == "main"+ and bool(run_info.get("event"))+ and run_info["event"] not in ("pull_request", "pull_request_target")),"jobs": all_jobs,"cache_data": _collect_cache_data(all_jobs, repo, token),}diff --git a/tests/ci/test_cache_report.py b/tests/ci/test_cache_report.pyindex d9da6d2775a..9018777eef5 100644--- a/tests/ci/test_cache_report.py+++ b/tests/ci/test_cache_report.py@@ -104,96 +104,6 @@ def test_cache_invocations_account_only_confirmed_phase_local_archives():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():@@ -221,7 +131,7 @@ def test_restore_only_and_combined_actions_keep_the_same_comparison_identity():assert current[0]["save_status"] == "saved" and current[0]["saved_bytes"] == 150markdown = 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+ assert "+20 B" in markdown and "Saved" not in markdowndef test_failed_save_does_not_obscure_a_clean_restore_miss():@@ -231,10 +141,11 @@ def test_failed_save_does_not_obscure_a_clean_restore_miss():_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]}},+ markdown = report.render_cache_summary({"is_main": True, "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+ assert "0 / 1 cache hits" in markdown and "1 miss" in markdown+ assert "failed" in markdown and "finalization failed" in markdown+ assert "vs main" not in markdowndef test_content_key_changes_pair_restore_and_save_by_their_transport_paths():@@ -254,5 +165,6 @@ def test_content_key_changes_pair_restore_and_save_by_their_transport_paths():assert entries[0]["restored_bytes"] == 100 and entries[0]["saved_bytes"] == 140assert 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 summary+ summary = report.render_cache_summary({"is_main": True, "cache_data": {"entries": entries}}, None)+ assert "140 B" in summary and "100 B" in summary+ assert "vs main" not in summarydiff --git a/tests/ci/test_cache_report_collection.py b/tests/ci/test_cache_report_collection.pyindex 559314541be..7d3a8348c4e 100644--- a/tests/ci/test_cache_report_collection.py+++ b/tests/ci/test_cache_report_collection.py@@ -3,13 +3,16 @@ from __future__ import annotationsimport jsonimport threading++import pytestfrom http.server import BaseHTTPRequestHandler, ThreadingHTTPServerfrom urllib.parse import urlsplitfrom scripts.ci import assemble_review_comment, timings_report-def test_collected_cache_data_reaches_reports_without_forwarding_auth(monkeypatch):[email protected]("event,is_main", [("pull_request", False), ("push", True), ("workflow_dispatch", True)])+def test_collected_cache_data_reaches_reports_without_forwarding_auth(monkeypatch, event, is_main):timestamp = "2026-10-20T12:00:01Z "messages = ["##[group]Run actions/cache/restore@fixture", "with:",@@ -30,7 +33,7 @@ def test_collected_cache_data_reaches_reports_without_forwarding_auth(monkeypatc(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": (200, {}, json.dumps({"created_at": "2026-10-20T12:00:00Z", "head_branch": "main", "event": event}).encode()),f"{prefix}/runs/42/jobs": (200, {}, json.dumps({"jobs": jobs}).encode()),f"{prefix}/runs": (200, {}, b'{"workflow_runs": []}'),"/blob": (200, {}, log),@@ -65,6 +68,7 @@ def test_collected_cache_data_reaches_reports_without_forwarding_auth(monkeypatcthread.join()assert "cache_data" in current, "CI collection must retain per-cache data in the baseline JSON"+ assert current["is_main"] is is_main, "a PR from a branch named main is not a main run"caches = current["cache_data"]assert caches["jobs_collected"] == 1assert caches["unavailable_jobs"] == ["logs unavailable"]@@ -80,5 +84,6 @@ def test_collected_cache_data_reaches_reports_without_forwarding_auth(monkeypatcassert 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 "Cache artifacts" in timings_report.generate_html(current, old_baseline)+ assert "#step:1:1" in commentassert "CI caches" in timings_report.generate_summary(current, old_baseline)diff --git a/tests/ci/test_cache_report_views.py b/tests/ci/test_cache_report_views.pynew file mode 100644index 00000000000..694321bb701--- /dev/null+++ b/tests/ci/test_cache_report_views.py@@ -0,0 +1,77 @@+"""Cache presentation separates read-only comparisons from main's writes."""+from __future__ import annotations++import pytest++from scripts.ci import cache_report as report+from tests.ci.test_cache_report import _cache, _post+++def _snapshot(main: bool, *, baseline: bool = False) -> dict:+ log = "\n".join([+ _cache("Cache packages", "hit", [+ "Cache hit for: hit", f"Cache Size: ~0 MB ({80 if baseline else 100} B)",+ "Cache restored from key: hit",+ ]),+ _cache("Cache tools", "miss", ["Cache not found for input keys: miss"]),+ _cache("Cache broken", "broken", ["##[warning]Failed to restore: service | <script>"]),+ _cache("Lookup", "lookup", ["Cache found and can be restored from key: lookup"]),+ _post("Cache packages", [+ f"Sent {90 if baseline else 130} of {90 if baseline else 130} (100.0%), 1.0 MBs/sec",+ "Cache saved with key: hit",+ ]),+ _post("Cache tools", [+ f"Sent {70 if baseline else 40} of {70 if baseline else 40} (100.0%), 1.0 MBs/sec",+ "Cache saved with key: miss",+ ]),+ ])+ steps = [{"name": "Prepare packages", "number": 4, "started_at": "2026-10-20T20:00:00Z",+ "completed_at": "2026-10-20T20:00:59Z"}]+ entries = report.parse_cache_log(log, steps)+ return {"is_main": main, "cache_data": {"entries": [dict(e, job="job|<svg>",+ job_url="https://github.com/fixture/cache/actions/runs/1/job/2") for e in entries],+ "jobs_collected": 1, "unavailable_jobs": ["lost|<script>"]}}++[email protected]("is_main", [False, True], ids=["pull-request", "main"])+def test_cache_summary_and_expando_follow_the_run_mode(is_main):+ current, baseline = _snapshot(is_main), _snapshot(True, baseline=True)+ result = report.cache_review_status(current, baseline)[0]["results"][0]+ markdown, html = report.render_cache_summary(current, baseline), report.render_cache_html(current, baseline)+ assert "1 / 3 cache hits" in result["summary"]+ assert "1 miss" in result["summary"]+ assert "100 B restored" in result["summary"]+ assert f"{40 if is_main else 70} B not restored" in result["summary"]+ assert "unknown" in result["summary"]+ for rendered in (result["detail"], markdown, html):+ assert "<details>" in rendered and "<summary>" in rendered+ assert "hits" in rendered and "misses" in rendered+ assert "job" in rendered and "Cache packages" in rendered+ assert "#step:4:1" in rendered+ assert "lost" in rendered and "<script>" in rendered+ assert "<script>" not in rendered and "<svg>" not in rendered+ if is_main:+ assert "170 B saved" in result["summary"]+ assert "Saved" in html and "130 B" in html and "40 B" in html+ assert "vs main" not in html and "vs main" not in markdown+ assert "+10 B" not in html+ else:+ assert "saved" not in result["summary"]+ assert "Saved" not in html and "130 B" not in html+ assert "vs main" in html and "+10 B" in html+ misses = result["detail"].split("### misses", 1)[1].split("###", 1)[0]+ assert "Cache tools" in misses+ assert "Restored" not in misses and "vs main" not in misses+++def test_miss_bytes_remain_unknown_without_a_main_reference():+ current = _snapshot(False)+ result = report.cache_review_status(current, None)[0]["results"][0]+ assert "not restored: unknown" in result["summary"]+ assert "0 B not restored" not in result["summary"]+ assert "main-size reference" in result["detail"]+ assert "lookup-only" in result["detail"]+ current["cache_data"]["entries"][0]["restored_bytes"] = None+ unknown = report.cache_review_status(current, None)[0]["results"][0]+ assert "restored: unknown" in unknown["summary"]+ assert "0 B restored" not in unknown["summary"]