From 714683d63c6ce8ee211a8b17cfb62d2766ddbef4 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:19:30 +0100 Subject: [PATCH] fix: record every profile a pass writes --- scripts/profile_sync.py | 4 +-- scripts/profiling/realignpass.py | 18 +++++----- scripts/profiling/run.py | 25 ++++++------- scripts/profiling/sourcepaths.py | 24 +++++++++++-- tests/test_profile_sync.py | 60 +++++++++++++++++++++++++------- 5 files changed, 91 insertions(+), 40 deletions(-) diff --git a/scripts/profile_sync.py b/scripts/profile_sync.py index 7451ae35b..4a900558b 100644 --- a/scripts/profile_sync.py +++ b/scripts/profile_sync.py @@ -205,7 +205,7 @@ def main() -> None: run_realign(args, selected) return - reports, failed, complete = read_selected(args, selected, writes) + reports, failed, written, complete = read_selected(args, selected, writes) # --changed-only narrows every output, not the text report alone: the # documented `--all --changed-only --json` listed every profile. @@ -214,7 +214,7 @@ def main() -> None: if not args.changed_only or report.needs_review() or report.name in failed ] complete = emit_reports(args, selected, reports, shown) is not False and complete - refresh_source_paths(args) + refresh_source_paths(args, written) if not complete: raise SystemExit(130) if failed or (args.strict and any( diff --git a/scripts/profiling/realignpass.py b/scripts/profiling/realignpass.py index 658d1d7c7..cd2703138 100644 --- a/scripts/profiling/realignpass.py +++ b/scripts/profiling/realignpass.py @@ -8,32 +8,30 @@ from pathlib import Path from core import upstream from profiling.realign import realign_prose -from profiling.run import WRITTEN_PROFILES -from profiling.sourcepaths import refresh_source_paths +from profiling.sourcepaths import record_write, refresh_source_paths from profiling.yamledit import YamlWriteError def run_realign(args: argparse.Namespace, selected: dict) -> None: """--realign-prose over the selected profiles, exit 1 when one failed.""" failed: set[str] = set() + written: set[str] = set() for name in selected: profile_path = Path(args.emulators_dir) / f"{name}.yml" if not profile_path.is_file(): continue try: - before = profile_path.read_bytes() - for line in realign_prose( - profile_path, args.cache_dir, args.offline, args.dry_run - ): - print(f"{name}: {line}") - if profile_path.read_bytes() != before: - WRITTEN_PROFILES.add(name) + with record_write(profile_path, name, written): + for line in realign_prose( + profile_path, args.cache_dir, args.offline, args.dry_run + ): + print(f"{name}: {line}") except upstream.UpstreamError as exc: print(f"{name}: {exc}", file=sys.stderr) failed.add(name) except YamlWriteError as exc: print(f"{name}: write refused: {exc}", file=sys.stderr) failed.add(name) - refresh_source_paths(args) + refresh_source_paths(args, written) if failed: raise SystemExit(1) diff --git a/scripts/profiling/run.py b/scripts/profiling/run.py index ce9f382a7..74a10fa4b 100644 --- a/scripts/profiling/run.py +++ b/scripts/profiling/run.py @@ -25,6 +25,7 @@ from profiling.reports import ( ) from profiling.repos import select_repo 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.versions import ( newer_release, @@ -135,7 +136,6 @@ def _promote( file=sys.stderr, ) return False - WRITTEN_PROFILES.add(name) return True @@ -311,8 +311,12 @@ def read_one_profile( reports: list[ProfileReport], failed: set[str], writes: bool, + written: set[str], ) -> None: - """Build one profile's report into ``reports``, then apply the writes.""" + """Build one profile's report into ``reports``, then apply the writes. + + A profile the writes changed is added to ``written``. + """ profile_path = Path(args.emulators_dir) / f"{name}.yml" try: report = _build_full_report(args, name, profile, profile_path, failed) @@ -330,7 +334,8 @@ def read_one_profile( reports.append(report) if writes: try: - _apply_writes(args, name, profile, report) + with record_write(profile_path, name, written): + _apply_writes(args, name, profile, report) except YamlWriteError as exc: # The guard already left the file untouched, so keep going. print(f"{name}: write refused: {exc}", file=sys.stderr) @@ -345,12 +350,13 @@ def read_one_profile( def read_selected( args: argparse.Namespace, selected: dict, writes: bool -) -> tuple[list[ProfileReport], set[str], bool]: +) -> tuple[list[ProfileReport], set[str], set[str], bool]: """Every selected profile's pass: the reports, the profiles that failed, - and whether the pass ran to its end.""" + the profiles it wrote, and whether the pass ran to its end.""" # A profile that could not be compared or written is not a profile with # nothing to review: it stays in every output and fails the run. failed: set[str] = set() + written: set[str] = set() reports: list[ProfileReport] = [] quiet = args.offline or len(selected) < 2 if not quiet: @@ -364,18 +370,13 @@ def read_selected( try: for name, profile in selected.items(): progress.step(len(reports), name) - read_one_profile(args, name, profile, reports, failed, writes) + read_one_profile(args, name, profile, reports, failed, writes, written) except KeyboardInterrupt: # What was read is still worth printing: a ranking of 200 profiles # beats none after 15 minutes. print_interrupted(len(reports), len(selected), "the output covers those read") complete = False - return reports, failed, complete - - -# Profiles this run wrote. Their new pins name trees the site's record of -# cited source paths does not hold yet. -WRITTEN_PROFILES: set[str] = set() + return reports, failed, written, complete def _build_full_report( diff --git a/scripts/profiling/sourcepaths.py b/scripts/profiling/sourcepaths.py index fcf39cd7e..9b79e3651 100644 --- a/scripts/profiling/sourcepaths.py +++ b/scripts/profiling/sourcepaths.py @@ -5,12 +5,30 @@ from __future__ import annotations import argparse import os import sys +from collections.abc import Iterator +from contextlib import contextmanager +from pathlib import Path from model.profiles import load_emulator_profiles -from profiling.run import WRITTEN_PROFILES -def refresh_source_paths(args: argparse.Namespace) -> None: +@contextmanager +def record_write(path: Path, name: str, written: set[str]) -> Iterator[None]: + """Add *name* to *written* when the profile's bytes changed in the block. + + Every writer of a pass runs inside it, so a new writer cannot forget to + say it wrote: --backfill-commits and --attribute-refs never did, and the + pins they wrote stayed out of the record. A write put back is no write. + """ + before = path.read_bytes() if path.is_file() else None + try: + yield + finally: + if path.is_file() and path.read_bytes() != before: + written.add(name) + + +def refresh_source_paths(args: argparse.Namespace, written: set[str]) -> None: """Rebuild the site's record of cited source paths after a write. Each bump left website/src/data/source-paths.json behind its pins, and @@ -18,7 +36,7 @@ def refresh_source_paths(args: argparse.Namespace) -> None: --fetch by hand. A run that writes nothing, or makes no request, leaves it alone. """ - if not WRITTEN_PROFILES or args.dry_run or args.offline or os.environ.get("RETROBIOS_OFFLINE"): + if not written or args.dry_run or args.offline or os.environ.get("RETROBIOS_OFFLINE"): return from core.artifacts import ArtifactLockBusy from model.profiles import emulator_profiles_cache diff --git a/tests/test_profile_sync.py b/tests/test_profile_sync.py index 527c41898..e6a04e7f3 100644 --- a/tests/test_profile_sync.py +++ b/tests/test_profile_sync.py @@ -2734,7 +2734,8 @@ class TestWriteDryRun(unittest.TestCase): mock.patch.object(profiling_run, "realign_prose", side_effect=cold), \ contextlib.redirect_stderr(io.StringIO()) as err: profiling_run.read_one_profile( - self._args(rebase_refs=True), "p", yaml.safe_load(SAMPLE), reports, failed, True + self._args(rebase_refs=True), "p", yaml.safe_load(SAMPLE), reports, failed, True, + set(), ) self.assertEqual(reports, [skipped]) self.assertEqual(failed, {"p"}) @@ -5180,15 +5181,12 @@ class AWriteRefreshesTheSourcePaths(unittest.TestCase): mock.patch.object(profiling_sourcepaths, "load_emulator_profiles", return_value={}), \ mock.patch.object(sources, "write_if_changed") as written, \ contextlib.redirect_stderr(io.StringIO()): - profiling_run.WRITTEN_PROFILES.clear() - profiling_sourcepaths.refresh_source_paths(self._args()) + profiling_sourcepaths.refresh_source_paths(self._args(), set()) self.assertFalse(built.called) - profiling_run.WRITTEN_PROFILES.add("x") - profiling_sourcepaths.refresh_source_paths(self._args(dry_run=True)) + profiling_sourcepaths.refresh_source_paths(self._args(dry_run=True), {"x"}) self.assertFalse(built.called) - profiling_sourcepaths.refresh_source_paths(self._args()) + profiling_sourcepaths.refresh_source_paths(self._args(), {"x"}) self.assertTrue(built.called and written.called) - profiling_run.WRITTEN_PROFILES.clear() def test_the_record_reads_the_pins_just_written(self): @@ -5211,9 +5209,7 @@ class AWriteRefreshesTheSourcePaths(unittest.TestCase): mock.patch.object(sources, "write_if_changed"), \ contextlib.redirect_stderr(io.StringIO()), \ contextlib.redirect_stdout(io.StringIO()): - profiling_run.WRITTEN_PROFILES.add("p") - self.addCleanup(profiling_run.WRITTEN_PROFILES.clear) - profiling_sourcepaths.refresh_source_paths(self._args(emulators_dir=tmp)) + profiling_sourcepaths.refresh_source_paths(self._args(emulators_dir=tmp), {"p"}) self.assertEqual(built.call_args[0][0]["p"]["source_commit"], "new") def test_the_record_waits_for_a_run_holding_the_repository(self): @@ -5231,14 +5227,52 @@ class AWriteRefreshesTheSourcePaths(unittest.TestCase): mock.patch.dict(os.environ, {"RETROBIOS_OFFLINE": ""}), \ mock.patch.object(profiling_sourcepaths, "load_emulator_profiles", return_value={}), \ contextlib.redirect_stderr(io.StringIO()) as err: - profiling_run.WRITTEN_PROFILES.add("x") - self.addCleanup(profiling_run.WRITTEN_PROFILES.clear) - profiling_sourcepaths.refresh_source_paths(self._args()) + profiling_sourcepaths.refresh_source_paths(self._args(), {"x"}) lock.assert_called_once_with(str(sources.SOURCE_PATHS)) self.assertFalse(built.called) self.assertIn("sitesources.py --fetch", err.getvalue()) +class EveryWriterIsRecorded(unittest.TestCase): + """--backfill-commits wrote a pin without saying so: the record of cited + source paths then lacked the tree that pin names.""" + + def test_a_backfilled_pin_is_a_write(self): + from unittest import mock + + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "p.yml" + path.write_text('emulator: P\nprofiled_date: "2026-01-01"\n', encoding="utf-8") + args = argparse.Namespace( + emulators_dir=tmp, backfill_commits=True, rebase_refs=False, + bump_commit=False, dry_run=False, + ) + report = ProfileReport(name="p", entries=[], counts={}, pin="abcdef0") + written: set[str] = set() + with mock.patch.object(profiling_run, "_build_full_report", return_value=report), \ + contextlib.redirect_stdout(io.StringIO()): + profiling_run.read_one_profile( + args, "p", yaml.safe_load(path.read_text()), [], set(), True, written, + ) + self.assertIn('source_commit: "abcdef0"', path.read_text()) + self.assertEqual(written, {"p"}) + + def test_a_write_put_back_is_not_recorded(self): + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "p.yml" + path.write_text("emulator: P\n", encoding="utf-8") + written: set[str] = set() + with profiling_sourcepaths.record_write(path, "p", written): + path.write_text("emulator: Q\n", encoding="utf-8") + path.write_text("emulator: P\n", encoding="utf-8") + self.assertEqual(written, set()) + with self.assertRaises(YamlWriteError), \ + profiling_sourcepaths.record_write(path, "p", written): + path.write_text("emulator: Q\n", encoding="utf-8") + raise YamlWriteError("a later write refused") + self.assertEqual(written, {"p"}) + + class AnUnreadTreeKeepsItsRecord(unittest.TestCase): """sitesources --fetch, rate-limited by GitLab, dropped about twenty trees it never read from source-paths.json."""