From b0f7d6c6610c72a696adcf32723b1ceb441f62b0 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:44:00 +0100 Subject: [PATCH] fix: carry the triage ranking in --json --- scripts/profiling/flagchecks.py | 9 +++- scripts/profiling/run.py | 10 +++- scripts/profiling/triage.py | 82 +++++++++++++++++++++++++-------- tests/test_profile_sync.py | 22 +++++++++ 4 files changed, 100 insertions(+), 23 deletions(-) diff --git a/scripts/profiling/flagchecks.py b/scripts/profiling/flagchecks.py index 572a16816..fd30e9769 100644 --- a/scripts/profiling/flagchecks.py +++ b/scripts/profiling/flagchecks.py @@ -95,10 +95,15 @@ def refuse_flag_combinations(args: argparse.Namespace) -> None: ("--triage", args.triage), ) if on ] + if len(machine) > 1 and set(machine) != {"--json", "--triage"}: + # One output per run: the first one emit_reports reached printed and + # the others were dropped. --json --triage is the ranking as JSON. + print(f"{' and '.join(machine)} are separate outputs, pass one", file=sys.stderr) + raise SystemExit(1) # The version check and detection live on the report, so the outputs # built from the report (text, --json, --markdown) carry them. A URL - # list and a ranking do not. - lists_only = args.fetch_plan or args.triage + # list and a ranking table do not. + lists_only = args.fetch_plan or (args.triage and not args.as_json) extras = [ flag for flag, on in ( ("--check-version", args.check_version and lists_only), diff --git a/scripts/profiling/run.py b/scripts/profiling/run.py index 185152a90..5740a0d6c 100644 --- a/scripts/profiling/run.py +++ b/scripts/profiling/run.py @@ -25,7 +25,9 @@ from profiling.reports import ( ) from profiling.resolver import build_report from profiling.sourcepaths import record_write -from profiling.triage import PROGRESS_SECONDS, Progress, print_interrupted, print_triage +from profiling.triage import ( + PROGRESS_SECONDS, Progress, print_interrupted, print_triage, score_reports, scored_to_dict, +) from profiling.version_basis import VersionTag, version_tags from profiling.versions import ( VersionReport, @@ -488,6 +490,12 @@ def emit_reports( ) -> bool | None: """Write the reports in the form the flags ask for. False when the triage was cut short.""" + if args.as_json and args.triage: + # The ranking travels in the report: each row carries its score, + # worst first, for a reader that cannot parse the table. + scoring = score_reports(args, selected, shown) + print(json.dumps([scored_to_dict(item) for item in scoring.ranked], indent=2)) + return scoring.complete if args.as_json: print(json.dumps([report_to_dict(r) for r in shown], indent=2)) return None diff --git a/scripts/profiling/triage.py b/scripts/profiling/triage.py index e6171f284..c4f188d01 100644 --- a/scripts/profiling/triage.py +++ b/scripts/profiling/triage.py @@ -6,9 +6,10 @@ import argparse import sys import time from collections.abc import Sequence +from dataclasses import dataclass, field from core import upstream -from profiling.reports import ProfileReport, triage_state +from profiling.reports import ProfileReport, report_to_dict, triage_state from profiling.version_basis import version_repo, version_tags from profiling.versions import VersionReport, check_version @@ -70,21 +71,40 @@ def print_interrupted(done: int, total: int, what: str) -> None: print(f"interrupted after {done} of {total} profiles: {what}", file=sys.stderr, flush=True) -def print_triage( +@dataclass(frozen=True) +class ScoredReport: + """One profile's drift score, and why its commit history went unread.""" + + report: ProfileReport + score: int + refused: str = "" + + +@dataclass +class Scoring: + """The scores a pass over the forges produced, worst first.""" + + ranked: list[ScoredReport] = field(default_factory=list) + # False when Ctrl-C cut the pass short: the ranking covers those scored. + complete: bool = True + + +def score_reports( args: argparse.Namespace, selected: dict, reports: list[ProfileReport] -) -> bool: - """Profiles ranked by drift, worst first. False when Ctrl-C cut the - scoring short: the ranking then covers the profiles scored.""" - ranked: list[tuple[int, ProfileReport, str]] = [] +) -> Scoring: + """Score every report by drift, asking the forges for versions and commits.""" + scored: list[ScoredReport] = [] sampled = 0 progress = Progress(len(reports), "scored", args.offline or len(reports) < 2) complete = True try: for done, report in enumerate(reports): progress.step(done, report.name) - sampled += _score(args, selected, report, ranked) + entry, was_sampled = _score(args, selected, report) + scored.append(entry) + sampled += was_sampled except KeyboardInterrupt: - print_interrupted(len(ranked), len(reports), "the ranking covers those scored") + print_interrupted(len(scored), len(reports), "the ranking covers those scored") complete = False if sampled: # One line for the run: a notice per profile buried the ranking @@ -94,23 +114,46 @@ def print_triage( f"{sampled} profiles citing more", file=sys.stderr, ) + return Scoring(sorted(scored, key=lambda item: -item.score), complete) + + +def scored_to_dict(item: ScoredReport) -> dict: + """A report's JSON form with its drift score and the history it lacked.""" + payload = report_to_dict(item.report) + payload["drift_score"] = item.score + payload["drift_refused"] = item.refused or None + return payload + + +def render_triage(scoring: Scoring) -> None: + """The ranking as a table, worst first.""" print(f"{'score':>5s} {'profile':30s} state (worst first)") pending = 0 - for score, report, refused in sorted(ranked, key=lambda item: -item[0]): + for item in scoring.ranked: + report = item.report state = triage_state(report) - if refused: - state += f", {refused}" + if item.refused: + state += f", {item.refused}" pending += bool(report.needs_review() or report.uncheckable()) - print(f"{score:5d} {report.name:30s} {state}") - print(f"{len(ranked)} profiles, {pending} with something to review") - return complete + print(f"{item.score:5d} {report.name:30s} {state}") + print(f"{len(scoring.ranked)} profiles, {pending} with something to review") + + +def print_triage( + args: argparse.Namespace, selected: dict, reports: list[ProfileReport] +) -> bool: + """Profiles ranked by drift, worst first. False when Ctrl-C cut the + scoring short: the ranking then covers the profiles scored.""" + scoring = score_reports(args, selected, reports) + render_triage(scoring) + return scoring.complete def _score( - args: argparse.Namespace, selected: dict, report: ProfileReport, ranked: list -) -> bool: - """Append one profile's drift score to ``ranked``. True when its commit - count was read on a sample of the paths it cites.""" + args: argparse.Namespace, selected: dict, report: ProfileReport +) -> tuple[ScoredReport, bool]: + """One profile's drift score, and whether its commit count was read on a + sample of the paths it cites.""" profile = selected[report.name] versions: list[VersionReport] = [] commits = 0 @@ -136,5 +179,4 @@ def _score( refused = "commit history unreachable" print(f"{report.name}: {exc}", file=sys.stderr) sampled = len(sources) > TRIAGE_PATH_SAMPLE and not refused - ranked.append((drift_score(report, versions, commits), report, refused)) - return sampled + return ScoredReport(report, drift_score(report, versions, commits), refused), sampled diff --git a/tests/test_profile_sync.py b/tests/test_profile_sync.py index e8093f7f3..f5870d0ab 100644 --- a/tests/test_profile_sync.py +++ b/tests/test_profile_sync.py @@ -5556,6 +5556,28 @@ class TestOutputModesApplyTheirFlags(unittest.TestCase): self.assertEqual(code, 1) self.assertIn("--check-version", err) + def test_json_carries_the_ranking(self): + """--json --triage printed the plain report: no score, no order.""" + code, out, err = self._main("--json", "--triage") + self.assertEqual(code, 0, err) + rows = json.loads(out) + self.assertEqual([r["name"] for r in rows], ["drift", "clean"]) + self.assertEqual([r["drift_score"] for r in rows], [30, 0]) + self.assertIsNone(rows[0]["drift_refused"]) + + def test_the_ranking_as_json_carries_the_version_check(self): + code, out, err = self._main("--json", "--triage", "--check-version") + self.assertEqual(code, 0, err) + self.assertTrue(all("version" in row for row in json.loads(out))) + + def test_two_outputs_are_refused(self): + for pair in (("--json", "--markdown"), ("--markdown", "--triage"), + ("--json", "--fetch-plan"), ("--fetch-plan", "--triage")): + code, out, err = self._main(*pair) + self.assertEqual(code, 1, pair) + self.assertIn("separate outputs", err, pair) + self.assertEqual(out, "", pair) + def test_a_profile_the_forge_failed_is_listed_and_fails_the_run(self): """Dropped by --changed-only, a 502 read as nothing to review.""" from unittest import mock