From 1ca4506927b3016ecb61fccc5f2fbe3675894fca Mon Sep 17 00:00:00 2001 From: Ramon Roche Date: Fri, 2 Oct 2026 16:17:02 -0700 Subject: [PATCH] feat(ci): show the cost of each AI review on the PR MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The review footer now ends with the run's cost, model, number of model calls and wall time, for example "Cost: $7.42 · Claude Opus 5.5 · 12 model call(s) · 22 min"; a refusal notice shows what was spent before the refusal. The cost is Claude Code's own estimate at list prices, which matched a recomputation from token counts on Bedrock. Making the price visible on every review also discourages casual re-runs. Assisted-by: Claude:claude-opus-5-5 Signed-off-by: Ramon Roche --- Tools/ci/ai_review/pipeline.py | 17 ++++++++++--- Tools/ci/ai_review/render.py | 41 +++++++++++++++++++++++++------ Tools/ci/ai_review/test_render.py | 21 ++++++++++++++++ 3 files changed, 68 insertions(+), 11 deletions(-) diff --git a/Tools/ci/ai_review/pipeline.py b/Tools/ci/ai_review/pipeline.py index 2ed1c61bb32..3bc8c6cb0c5 100644 --- a/Tools/ci/ai_review/pipeline.py +++ b/Tools/ci/ai_review/pipeline.py @@ -9,6 +9,7 @@ import dataclasses import fnmatch import json import re +import time from dataclasses import dataclass from pathlib import Path from typing import Any, Dict, List, Optional, Tuple @@ -149,7 +150,8 @@ def run(s: Settings) -> Dict[str, Any]: """Run the whole pipeline. Returns the report data it also writes.""" s.work_dir.mkdir(parents=True, exist_ok=True) pr = context.gather(s.repo, s.pr_number) - usage: Dict[str, Any] = {'changed_lines': pr.changed_lines} + usage: Dict[str, Any] = {'changed_lines': pr.changed_lines, + 'started': time.monotonic()} # Every PR is reviewed regardless of size; only one made entirely of # generated files (lock files, translations) has nothing to review. @@ -193,6 +195,12 @@ def run(s: Settings) -> Dict[str, Any]: return data +def _stamp_wall_time(usage: Dict[str, Any]) -> None: + started = usage.pop('started', None) + if isinstance(started, float): + usage['wall_seconds'] = round(time.monotonic() - started, 1) + + def refused(s: Settings, pr: context.PrContext, e: agent.AgentRefusal, usage: Dict[str, Any]) -> Dict[str, Any]: """The reviewer model declined: no review, and say exactly why. @@ -203,8 +211,9 @@ def refused(s: Settings, pr: context.PrContext, e: agent.AgentRefusal, """ usage['refused'] = {'model': e.model, 'category': e.category, 'request_id': e.request_id} + _stamp_wall_time(usage) artifact = render.write_refusal(s.out_dir, pr.number, pr.head_sha, e, - s.model_label) + s.model_label, usage) report = render.refusal_report(e, artifact, usage) (s.work_dir / 'report.md').write_text(report, encoding='utf-8') (s.work_dir / 'usage.json').write_text(json.dumps(usage, indent=2)) @@ -240,8 +249,10 @@ def finish(s: Settings, pr_number: int, head_sha: str, diff_text: str, head_files = route.load_head_files( s.checkout, sorted({f.path for f, _ in pairs if f.path})) routed = route.route(pairs, diff_map, head_files) + _stamp_wall_time(usage) artifact = render.write_artifact(s.out_dir, pr_number, head_sha, routed, - model_summary, s.model_label, checklist) + model_summary, s.model_label, checklist, + usage) usage.update(sandbox_stats(s.work_dir / SANDBOX_LOG)) report = render.report_markdown(routed, artifact, usage, checklist) (s.work_dir / 'report.md').write_text(report, encoding='utf-8') diff --git a/Tools/ci/ai_review/render.py b/Tools/ci/ai_review/render.py index b87dd5ed153..b9240516212 100644 --- a/Tools/ci/ai_review/render.py +++ b/Tools/ci/ai_review/render.py @@ -87,8 +87,25 @@ def checklist_line(checklist: Dict[str, ChecklistEntry]) -> str: return ' · '.join(cells) +def cost_line(usage: Optional[Dict[str, Any]], model_name: str) -> str: + """'Cost: $1.23 · Claude Opus 5.5 · 4 model calls · 7 min'. + + Claude Code's own estimate at list prices; on Bedrock it matched a + recomputation from token counts to the cent. + """ + if not usage or 'cost_usd' not in usage: + return '' + parts = [f'Cost: ${usage["cost_usd"]:.2f}', model_name, + f'{usage.get("calls", 0)} model call(s)'] + seconds = usage.get('wall_seconds') + if isinstance(seconds, (int, float)): + parts.append(f'{max(1, round(seconds / 60))} min') + return ' · '.join(parts) + + def summary(routed: Routed, model_summary: str, model_name: str, - checklist: Optional[Dict[str, ChecklistEntry]] = None) -> str: + checklist: Optional[Dict[str, ChecklistEntry]] = None, + usage: Optional[Dict[str, Any]] = None) -> str: parts = [f'**Automated review** ({model_name}): {routed.verdict}.'] if model_summary.strip(): parts += ['', model_summary.strip()] @@ -103,9 +120,11 @@ def summary(routed: Routed, model_summary: str, model_name: str, f'{len(routed.collapsed)} more finding(s) ' 'worth checking (lower confidence or outside the ' 'diff)', '', items, '', ''] + cost = cost_line(usage, model_name) parts += ['', f'Written by an AI model and checked by a second, ' f'independent pass. It can be wrong; maintainers decide. ' - f'[How this review works]({README_URL})'] + f'[How this review works]({README_URL})' + + (f'
{cost}' if cost else '') + ''] text = '\n'.join(parts) if len(text.encode('utf-8')) > SUMMARY_LIMIT: text = text.encode('utf-8')[:SUMMARY_LIMIT - 200].decode( @@ -127,7 +146,8 @@ def find_leaks(texts: Iterable[str], secrets: Iterable[str]) -> List[str]: def write_artifact(out_dir: Path, pr_number: int, commit_sha: str, routed: Routed, model_summary: str, model_name: str, - checklist: Optional[Dict[str, ChecklistEntry]] = None + checklist: Optional[Dict[str, ChecklistEntry]] = None, + usage: Optional[Dict[str, Any]] = None ) -> Dict[str, Any]: out_dir.mkdir(parents=True, exist_ok=True) manifest = { @@ -135,7 +155,8 @@ def write_artifact(out_dir: Path, pr_number: int, commit_sha: str, 'marker': MARKER, 'event': 'COMMENT', 'commit_sha': commit_sha, - 'summary': summary(routed, model_summary, model_name, checklist), + 'summary': summary(routed, model_summary, model_name, checklist, + usage), # a review with only a summary is still a review; and each run # replaces the previous one instead of piling up 'post_without_comments': True, @@ -147,7 +168,8 @@ def write_artifact(out_dir: Path, pr_number: int, commit_sha: str, return {'manifest': manifest, 'comments': body} -def refusal_summary(e: Any, model_name: str) -> str: +def refusal_summary(e: Any, model_name: str, + usage: Optional[Dict[str, Any]] = None) -> str: """Review body when the model declined: not a review, with the reason. The reason is the model provider's own text, passed through verbatim @@ -163,19 +185,22 @@ def refusal_summary(e: Any, model_name: str) -> str: 'This is usually a false positive from the provider\'s safety ' 'classifier, not a judgement about the PR. A maintainer can ' 're-run the review or review it by hand.', '', - f'[How this review works]({README_URL})'] + f'[How this review works]({README_URL})' + + (f'
{cost_line(usage, model_name)}' + if cost_line(usage, model_name) else '') + '
'] return '\n'.join(lines) def write_refusal(out_dir: Path, pr_number: int, commit_sha: str, e: Any, - model_name: str) -> Dict[str, Any]: + model_name: str, + usage: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: out_dir.mkdir(parents=True, exist_ok=True) manifest = { 'pr_number': pr_number, 'marker': MARKER, 'event': 'COMMENT', 'commit_sha': commit_sha, - 'summary': refusal_summary(e, model_name), + 'summary': refusal_summary(e, model_name, usage), # the notice must reach the PR even though there are no findings 'post_without_comments': True, 'supersede_previous': True, diff --git a/Tools/ci/ai_review/test_render.py b/Tools/ci/ai_review/test_render.py index 93bd9aa7377..255bfc36edc 100644 --- a/Tools/ci/ai_review/test_render.py +++ b/Tools/ci/ai_review/test_render.py @@ -78,6 +78,27 @@ class TestRender(unittest.TestCase): self.assertEqual(len(comments), 1) +class TestCostLine(unittest.TestCase): + + def test_cost_in_review_footer(self) -> None: + usage = {'cost_usd': 7.4239, 'calls': 12, 'wall_seconds': 1290.0} + text = render.summary(route.Routed(), '', 'Claude Opus 5.5', + usage=usage) + self.assertIn('Cost: $7.42 · Claude Opus 5.5 · 12 model call(s) · ' + '22 min', text) + + def test_no_usage_no_cost_line(self) -> None: + self.assertEqual(render.cost_line(None, 'm'), '') + self.assertNotIn('Cost:', render.summary(route.Routed(), '', 'm')) + + def test_refusal_shows_what_was_spent(self) -> None: + from ai_review import agent + e = agent.AgentRefusal('m', 'declined', 'cyber', 'req') + text = render.refusal_summary(e, 'm', {'cost_usd': 0.01, + 'calls': 0}) + self.assertIn('Cost: $0.01', text) + + class TestLeaks(unittest.TestCase): def test_detects_secret(self) -> None: