Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

make benchmark comments compact and show only the latest scan (#2178)

ktd4bc773d8534
diff --git a/scripts/benchmarks/README.md b/scripts/benchmarks/README.md
index b1deb3863a..99487d27ae 100644
--- a/scripts/benchmarks/README.md
+++ b/scripts/benchmarks/README.md
@@ -98,9 +98,15 @@ The runtime rows show medians across the 10 independent trials. Batch iteration
sizes are fixed in `kernel.py`; failures and incomplete output remain failed samples. These are
subsystem measurements alongside the normal installed CLI benchmarks, not end-to-end tool latency.
-The comment shows medians, signed absolute/percentage deltas, successful/attempted counts, and spread.
-`↓` means improvement, bold `↑` means regression, `≈` means no clear change, and `—` means unavailable
-or incomplete. Arrows require a change larger than the metric's absolute floor, relative floor,
+The comment has four columns: metric, main, PR, and signed change with the percentage in parentheses.
+A single summary counts regressions, improvements, metrics with no clear change, and incomplete or
+unavailable comparisons. Improvements are green with `↓`, regressions red with `↑`, and changes within
+the noise threshold remain neutral with `≈`. The entire change value, including the arrow, delta, and
+percentage, goes from muted to vivid as the absolute percentage grows, reaching maximum intensity at
+100%. An undefined percentage uses the muted shade. Colors use GitHub's native MathJax rendering;
+no external badge service is required. Successful/attempted counts and spread appear in the collapsed
+methodology.
+Arrows require a change larger than the metric's absolute floor, relative floor,
and observed spread. The initial relative floor is 20% for timings and memory, 0.5% for artifact
size, and 1% for disk footprint. A same-revision calibration on separate sandboxes showed roughly
7–18% variation across several timings; the conservative floor avoids labeling that as a code regression.
@@ -109,8 +115,10 @@ raw trials before acting on small changes; sandbox scheduling and filesystem cac
## Lifecycle and costs
-The main workflow posts a single marked comment and updates it in place. The completion workflow
-publishes the final result or a cancellation/failure notice. Publishers serialize by PR and check the
+The main workflow posts a single marked comment and updates it in place. A new push replaces the
+previous table with a short running notice and a link to the latest run. The completion workflow
+fills that same comment with the latest results or a cancellation/failure notice. Previous results
+remain available in workflow artifacts. Publishers serialize by PR and check the
current head, latest run ID, attempt, and existing comment generation before writing. A rerun of an
older commit cannot overwrite a newer result, including when the newer run has the same head SHA.
diff --git a/scripts/benchmarks/report.py b/scripts/benchmarks/report.py
index 5e34c15890..5da2a3f7f5 100644
--- a/scripts/benchmarks/report.py
+++ b/scripts/benchmarks/report.py
@@ -3,7 +3,9 @@ from __future__ import annotations
import hashlib
import json
import statistics
+from collections import Counter
from dataclasses import dataclass
+from typing import Literal
from schema import Metric, Observation, Report
@@ -32,16 +34,22 @@ class Definition:
unit: str
absolute: float
relative: float
- better: str
- worse: str
+
+
+@dataclass(frozen=True)
+class Comparison:
+ main: str
+ head: str
+ change: str
+ outcome: Literal["improved", "regressed", "no clear change", "incomplete", "unavailable"]
METRICS = (
- Definition("cold", "Cold startup", 1000, "ms", 0.1, PERFORMANCE_NOISE_FLOOR, "faster", "slower"),
- Definition("warm", "Warm startup", 1000, "ms", 0.1, PERFORMANCE_NOISE_FLOOR, "faster", "slower"),
- Definition("install", "Installation", 1, "s", 1, PERFORMANCE_NOISE_FLOOR, "faster", "slower"),
- Definition("bundle", "Compressed release artifacts", 1e-6, "MB", 65536, 0.005, "smaller", "larger"),
- Definition("disk", "Installed footprint", 1e-6, "MB", 1048576, 0.01, "smaller", "larger"),
+ Definition("cold", "Cold startup", 1000, "ms", 0.1, PERFORMANCE_NOISE_FLOOR),
+ Definition("warm", "Warm startup", 1000, "ms", 0.1, PERFORMANCE_NOISE_FLOOR),
+ Definition("install", "Installation", 1, "s", 1, PERFORMANCE_NOISE_FLOOR),
+ Definition("bundle", "Compressed release artifacts", 1e-6, "MB", 65536, 0.005),
+ Definition("disk", "Installed footprint", 1e-6, "MB", 1048576, 0.01),
Definition(
"rss",
"Idle memory, summed RSS",
@@ -49,8 +57,6 @@ METRICS = (
"MB",
10485760,
PERFORMANCE_NOISE_FLOOR,
- "less memory",
- "more memory",
),
)
RUNTIME_METRICS = (
@@ -61,8 +67,6 @@ RUNTIME_METRICS = (
"ms",
0.005,
PERFORMANCE_NOISE_FLOOR,
- "faster",
- "slower",
),
Definition(
"kernel_exec",
@@ -71,19 +75,11 @@ RUNTIME_METRICS = (
"ms",
0.0001,
PERFORMANCE_NOISE_FLOOR,
- "faster",
- "slower",
- ),
- Definition("bash", "Empty bash command", 1000, "ms", 0.001, PERFORMANCE_NOISE_FLOOR, "faster", "slower"),
- Definition(
- "git_status", "Bash git status", 1000, "ms", 0.001, PERFORMANCE_NOISE_FLOOR, "faster", "slower"
- ),
- Definition(
- "output", "Bash 32 KiB output", 1000, "ms", 0.001, PERFORMANCE_NOISE_FLOOR, "faster", "slower"
- ),
- Definition(
- "mixed", "35 cells / 9 shell calls", 1000, "ms", 0.005, PERFORMANCE_NOISE_FLOOR, "faster", "slower"
),
+ Definition("bash", "Empty bash command", 1000, "ms", 0.001, PERFORMANCE_NOISE_FLOOR),
+ Definition("git_status", "Bash git status", 1000, "ms", 0.001, PERFORMANCE_NOISE_FLOOR),
+ Definition("output", "Bash 32 KiB output", 1000, "ms", 0.001, PERFORMANCE_NOISE_FLOOR),
+ Definition("mixed", "35 cells / 9 shell calls", 1000, "ms", 0.005, PERFORMANCE_NOISE_FLOOR),
Definition(
"interrupt",
"Python interrupt to done",
@@ -91,15 +87,9 @@ RUNTIME_METRICS = (
"ms",
0.0005,
PERFORMANCE_NOISE_FLOOR,
- "faster",
- "slower",
- ),
- Definition(
- "snapshot", "Python state snapshot", 1000, "ms", 0.001, PERFORMANCE_NOISE_FLOOR, "faster", "slower"
- ),
- Definition(
- "restore", "Python state restore", 1000, "ms", 0.001, PERFORMANCE_NOISE_FLOOR, "faster", "slower"
),
+ Definition("snapshot", "Python state snapshot", 1000, "ms", 0.001, PERFORMANCE_NOISE_FLOOR),
+ Definition("restore", "Python state restore", 1000, "ms", 0.001, PERFORMANCE_NOISE_FLOOR),
Definition(
"kernel_rss",
"Python idle RSS",
@@ -107,8 +97,6 @@ RUNTIME_METRICS = (
"MB",
1048576,
PERFORMANCE_NOISE_FLOOR,
- "less memory",
- "more memory",
),
Definition(
"loaded_rss",
@@ -117,8 +105,6 @@ RUNTIME_METRICS = (
"MB",
1048576,
PERFORMANCE_NOISE_FLOOR,
- "less memory",
- "more memory",
),
)
@@ -169,38 +155,61 @@ def number(value: float, definition: Definition, signed: bool = False) -> str:
return f"{scaled:+,.{precision}f}" if signed else f"{scaled:,.{precision}f}"
+def change_color(relative_change: float | None, regressed: bool) -> str:
+ muted, vivid = ((170, 106, 101), (229, 72, 77)) if regressed else ((102, 129, 109), (31, 146, 78))
+ intensity = min(abs(relative_change), 1.0) if relative_change is not None else 0.0
+ channels = (round(start + (end - start) * intensity) for start, end in zip(muted, vivid, strict=True))
+ return "#" + "".join(f"{channel:02x}" for channel in channels)
+
+
def comparison(
definition: Definition, baseline: list[Observation], candidate: list[Observation], expected: int
-) -> tuple[str, str, str, str, str]:
+) -> Comparison:
left, right = values(baseline), values(candidate)
main = statistics.median(left) if left else None
head = statistics.median(right) if right else None
main_text = "—" if main is None else f"{number(main, definition)} {definition.unit}"
head_text = "—" if head is None else f"{number(head, definition)} {definition.unit}"
if main is None or head is None:
- return main_text, head_text, "—", "N/A", "unavailable"
+ return Comparison(main_text, head_text, "—", "unavailable")
delta = head - main
- percentage = f"{delta / main * 100:+.2f}%" if main else "N/A"
+ relative_change = delta / main if main else None
+ percentage = f"{relative_change * 100:+.2f}%" if relative_change is not None else "N/A"
+ change = f"{number(delta, definition, True)} {definition.unit} ({percentage})"
if len(left) != expected or len(right) != expected:
- return (
- main_text,
- head_text,
- f"— {number(delta, definition, True)} {definition.unit}",
- percentage,
- "incomplete",
- )
+ return Comparison(main_text, head_text, f"{change}; incomplete", "incomplete")
threshold = max(definition.absolute, main * definition.relative, spread(left), spread(right))
- signal, outcome = "≈", "no clear change"
- if abs(delta) > threshold:
- signal, outcome = ("↑", definition.worse) if delta > 0 else ("↓", definition.better)
- change = f"{signal} {number(delta, definition, True)} {definition.unit}"
- if signal == "↑":
- change, outcome = f"**{change}**", f"**{outcome}**"
- return main_text, head_text, change, percentage, outcome
+ if abs(delta) <= threshold:
+ return Comparison(main_text, head_text, f"≈ {change}", "no clear change")
+ signal = "↑" if delta > 0 else "↓"
+ color = change_color(relative_change, regressed=delta > 0)
+ text = f"{signal} {change}".replace("%", r"\%")
+ colored = rf"$`\textcolor{{{color}}}{{\textsf{{{text}}}}}`$"
+ return Comparison(main_text, head_text, colored, "regressed" if delta > 0 else "improved")
+
+
+def comparisons(report: Report) -> dict[Metric, Comparison]:
+ results = {}
+ for definition in (*METRICS, *RUNTIME_METRICS):
+ expected = report.config.install_trials if definition.key == "install" else report.config.trials
+ if definition.key in ("bundle", "disk"):
+ expected = 1
+ results[definition.key] = comparison(
+ definition,
+ report.main.metrics.get(definition.key, []),
+ report.pr_head.metrics.get(definition.key, []),
+ expected,
+ )
+ return results
def render(report: Report) -> str:
run_url = f"https://github.com/{report.repository}/actions/runs/{report.run_id}"
+ result_link = (
+ f"[Run, logs, and downloadable raw results]({run_url})"
+ if report.pr
+ else "Local run; raw results are stored beside this report."
+ )
lines = [
MARKER,
f"<!-- run:{report.run_id}:{report.attempt} head:{report.head_sha} -->",
@@ -208,16 +217,29 @@ def render(report: Report) -> str:
f"### Prime Agent performance — {report.status}",
"",
f"PR `{report.head_sha[:8]}` compared with main `{report.base_sha[:8]}`.",
- *(
- ["Waiting for contributor vouch before credentials or sandboxes are allocated.", ""]
- if report.status == "pending-trust"
- else []
- ),
- "↓ improved · ↑ regressed · ≈ no clear change · — unavailable",
"",
- "| Metric | Main | This PR | Change | Change % | Result |",
- "| --- | ---: | ---: | ---: | ---: | --- |",
]
+ if report.status in ("running", "pending-trust"):
+ message = (
+ "Waiting for contributor vouch before credentials or sandboxes are allocated."
+ if report.status == "pending-trust"
+ else "Benchmarking the latest PR commit. Results will appear here when this run finishes."
+ )
+ return "\n".join([*lines, message, "", result_link, ""])
+ results = comparisons(report)
+ counts = Counter(result.outcome for result in results.values())
+ summary = [f"{counts[outcome]} {outcome}" for outcome in ("regressed", "improved", "no clear change")]
+ summary.extend(
+ f"{counts[outcome]} {outcome}" for outcome in ("incomplete", "unavailable") if counts[outcome]
+ )
+ lines.extend(
+ [
+ f"**Overall: {' · '.join(summary)}.**",
+ "",
+ "| Metric | Main | This PR | Change |",
+ "| --- | ---: | ---: | ---: |",
+ ]
+ )
for definition in (*METRICS, *RUNTIME_METRICS):
if definition == RUNTIME_METRICS[0]:
lines.extend(
@@ -225,31 +247,18 @@ def render(report: Report) -> str:
"",
"**Python runtime**",
"",
- "| Metric | Main | This PR | Change | Change % | Result |",
- "| --- | ---: | ---: | ---: | ---: | --- |",
+ "| Metric | Main | This PR | Change |",
+ "| --- | ---: | ---: | ---: |",
]
)
- expected = report.config.install_trials if definition.key == "install" else report.config.trials
- if definition.key in ("bundle", "disk"):
- expected = 1
- cells = comparison(
- definition,
- report.main.metrics.get(definition.key, []),
- report.pr_head.metrics.get(definition.key, []),
- expected,
- )
- lines.append(f"| {definition.title} | {' | '.join(cells)} |")
+ result = results[definition.key]
+ lines.append(f"| {definition.title} | {result.main} | {result.head} | {result.change} |")
compute = sum(s.estimated_usd for s in report.sandboxes)
cost_text = (
f"**Sandbox cost: ~${compute:.4f}** — no inference calls."
if report.sandboxes
else "Cost pending or unavailable; sandbox usage has not been collected."
)
- result_link = (
- f"[Run, logs, and downloadable raw results]({run_url})"
- if report.pr
- else "Local run; raw results are stored beside this report."
- )
lines.extend(
[
"",
diff --git a/scripts/benchmarks/tests/test_benchmarks.py b/scripts/benchmarks/tests/test_benchmarks.py
index 554db5d3a1..9f5017f939 100644
--- a/scripts/benchmarks/tests/test_benchmarks.py
+++ b/scripts/benchmarks/tests/test_benchmarks.py
@@ -2,10 +2,12 @@ from __future__ import annotations
import json
import os
+import re
import subprocess
import sys
import tempfile
import unittest
+from colorsys import rgb_to_hsv
from datetime import UTC, datetime
from pathlib import Path
from types import SimpleNamespace
@@ -115,32 +117,103 @@ class ReportTests(unittest.TestCase):
observations(*samples["pr"]),
len(samples["main"]),
)
- self.assertEqual(result[-1], "no clear change")
+ self.assertEqual(result.outcome, "no clear change")
def test_slower_and_faster_have_consistent_signs_and_arrows(self):
baseline = observations(*([2.0] * 10))
slower = comparison(METRICS[0], baseline, observations(*([2.5] * 10)), 10)
faster = comparison(METRICS[0], baseline, observations(*([1.5] * 10)), 10)
- self.assertEqual(slower[2:], ("**↑ +500.0 ms**", "+25.00%", "**slower**"))
- self.assertEqual(faster[2:], ("↓ -500.0 ms", "-25.00%", "faster"))
+ self.assertEqual(slower.outcome, "regressed")
+ self.assertEqual(faster.outcome, "improved")
+ self.assertEqual(slower.change, r"$`\textcolor{#b9625f}{\textsf{↑ +500.0 ms (+25.00\%)}}`$")
+ self.assertEqual(faster.change, r"$`\textcolor{#548565}{\textsf{↓ -500.0 ms (-25.00\%)}}`$")
+
+ def test_larger_percentages_are_more_vivid_and_intensity_is_capped(self):
+ def color(baseline, head):
+ result = comparison(METRICS[3], observations(baseline), observations(head), 1)
+ match = re.search(r"\\textcolor\{(#[0-9a-f]{6})\}", result.change)
+ self.assertIsNotNone(match)
+ return match[1]
+
+ baseline = 100_000_000
+ for direction in (-1, 1):
+ with self.subTest(direction=direction):
+ colors = [
+ color(baseline, baseline * (1 + direction * fraction))
+ for fraction in (0.01, 0.25, 0.5, 1.0)
+ ]
+ saturation, brightness = [], []
+ for hex_color in colors:
+ _, s, v = rgb_to_hsv(*(int(hex_color[i : i + 2], 16) / 255 for i in (1, 3, 5)))
+ saturation.append(s)
+ brightness.append(v)
+ self.assertEqual(saturation, sorted(set(saturation)))
+ self.assertEqual(brightness, sorted(set(brightness)))
+ self.assertEqual(color(baseline * 2, baseline * 2 * (1 + direction * 0.5)), colors[2])
+ self.assertEqual(color(baseline, baseline * 2), color(baseline, baseline * 6))
+ self.assertEqual(color(0, baseline), "#aa6a65")
def test_noise_and_partial_results_are_not_regressions(self):
noisy = observations(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
shifted = observations(1.2, 2.2, 3.2, 4.2, 5.2, 6.2, 7.2, 8.2, 9.2, 10.2)
- self.assertEqual(comparison(METRICS[0], noisy, shifted, 10)[4], "no clear change")
+ self.assertEqual(comparison(METRICS[0], noisy, shifted, 10).outcome, "no clear change")
shifted[-1] = Observation(trial=9, error="timed out")
- self.assertEqual(comparison(METRICS[0], noisy, shifted, 10)[4], "incomplete")
- self.assertEqual(comparison(METRICS[0], [], shifted, 10)[4], "unavailable")
+ incomplete = comparison(METRICS[0], noisy, shifted, 10)
+ self.assertEqual(incomplete.outcome, "incomplete")
+ self.assertIn("incomplete", incomplete.change)
+ self.assertNotIn("textcolor", incomplete.change)
+ self.assertEqual(comparison(METRICS[0], [], shifted, 10).outcome, "unavailable")
def test_zero_baseline_and_small_bundle_changes(self):
cells = comparison(METRICS[3], observations(0), observations(65537), 1)
- self.assertEqual(cells[3], "N/A")
- self.assertIn("larger", cells[4])
+ self.assertIn("(N/A)", cells.change)
+ self.assertEqual(cells.outcome, "regressed")
unchanged = comparison(METRICS[3], observations(10_000_000), observations(10_001_000), 1)
- self.assertEqual(unchanged[4], "no clear change")
+ self.assertEqual(unchanged.outcome, "no clear change")
+ self.assertEqual(unchanged.change, "≈ +0.001 MB (+0.01%)")
+
+ def test_compact_tables_summarize_outcomes_without_treating_missing_samples_as_unchanged(self):
+ report = fixture()
+ report.status = "partial"
+ for definition in (*METRICS, *RUNTIME_METRICS):
+ count = 1 if definition.key in ("bundle", "disk") else (3 if definition.key == "install" else 10)
+ report.main.metrics[definition.key] = observations(*([2.0] * count))
+ report.pr_head.metrics[definition.key] = observations(*([2.0] * count))
+ report.pr_head.metrics["cold"] = observations(*([1.5] * 10))
+ report.pr_head.metrics["warm"] = observations(*([2.5] * 10))
+ report.pr_head.metrics["install"] = observations(2.0, 2.0)
+ report.pr_head.metrics["bundle"] = []
+ text = render(report)
+ self.assertIn(
+ "**Overall: 1 regressed · 1 improved · 13 no clear change · 1 incomplete · 1 unavailable.**",
+ text,
+ )
+ tables = text.split("<details>")[0]
+ self.assertEqual(tables.count("| Metric | Main | This PR | Change |"), 2)
+ for row in tables.splitlines():
+ if row.startswith("|"):
+ self.assertEqual(len(row.strip("|").split("|")), 4)
+ self.assertNotIn("| Change % |", text)
+ self.assertNotIn("| Result |", text)
+ self.assertNotIn("↓ improved", text)
+
+ def test_running_and_pending_comments_hide_previous_results(self):
+ report = fixture()
+ report.main.metrics["cold"] = observations(*([2.0] * 10))
+ report.pr_head.metrics["cold"] = observations(*([1.5] * 10))
+ for status in ("running", "pending-trust"):
+ with self.subTest(status=status):
+ report.status = status
+ text = render(report)
+ self.assertNotIn("| Metric |", text)
+ self.assertNotIn("Overall:", text)
+ self.assertNotIn("1,500.0", text)
+ self.assertIn("/actions/runs/100", text)
+ self.assertIn(f"status:{status}", text)
def test_comment_escapes_untrusted_text_and_reports_failures(self):
report = fixture()
+ report.status = "failed"
report.pr_head.error = "<img src=x> | ![click](https://example.test)\n<!-- comment -->"
text = render(report)
self.assertTrue(text.startswith(MARKER))
@@ -201,6 +274,32 @@ class FakeGitHub(GitHub):
class PublishingTests(unittest.TestCase):
+ def test_new_commit_replaces_the_previous_table_in_the_same_comment(self):
+ previous = fixture()
+ previous.status = "completed"
+ previous.head_sha = previous.pr_head.sha = "c" * 40
+ previous.run_id = 99
+ previous.main.metrics["cold"] = observations(*([2.0] * 10))
+ previous.pr_head.metrics["cold"] = observations(*([1.5] * 10))
+ github = FakeGitHub()
+ github.comments = [{"id": 2, "user": {"login": "github-actions[bot]"}, "body": render(previous)}]
+ current = fixture()
+ self.assertTrue(github.publish(current))
+ method, path, body = github.writes[-1]
+ self.assertEqual((method, path), ("PATCH", "issues/comments/2"))
+ self.assertIn("Benchmarking the latest PR commit", body["body"])
+ self.assertNotIn("| Metric |", body["body"])
+ self.assertNotIn(previous.head_sha[:8], body["body"])
+ github.comments[0]["body"] = body["body"]
+ self.assertFalse(github.publish(previous))
+ self.assertEqual(len(github.writes), 1)
+ current.status = "completed"
+ current.main.metrics = previous.main.metrics
+ current.pr_head.metrics = previous.pr_head.metrics
+ self.assertTrue(github.publish(current))
+ self.assertEqual(github.writes[-1][:2], ("PATCH", "issues/comments/2"))
+ self.assertIn("| Metric | Main | This PR | Change |", github.writes[-1][2]["body"])
+
def test_superseded_commit_and_same_commit_rerun_do_not_publish(self):
for case in ("head", "new_run", "attempt", "closed"):
with self.subTest(case=case):