diff --git a/scripts/profiling/detection.py b/scripts/profiling/detection.py index e7a003dec..c6826f2d4 100644 --- a/scripts/profiling/detection.py +++ b/scripts/profiling/detection.py @@ -12,8 +12,7 @@ import sys from core import upstream from core.upstream import CompareResult from profiling.citations import collect_tokens -from profiling.reports import ProfileReport -from profiling.repos import select_repo +from profiling.reports import CitedSource, ProfileReport FILE_EXTENSIONS = ( @@ -194,56 +193,77 @@ def tree_diff(result: CompareResult, ref_dirs: set[str]) -> list[str]: return lines -def cited_paths(report: ProfileReport) -> list[str]: - return sorted( - {part.new_path or part.part.path for e in report.entries for part in e.parts} - ) +def _scan_source( + source: CitedSource, names: set[str], known: set[str], + cache_dir: str, offline: bool, files: bool, hashes: bool, +) -> tuple[list[dict], int, list[dict]] | None: + """Undeclared names and added hash literals of one cited file, None when + its repository does not carry it at HEAD.""" + path = source.path + head_lines = upstream.fetch_file(source.repo, source.head, path, cache_dir, offline) + if head_lines is None: + return None + pin_lines = upstream.fetch_file(source.repo, source.pin, path, cache_dir, offline) or [] + found_files: list[dict] = [] + elided = 0 + found_hashes: list[dict] = [] + if files: + found, elided = detect_new_files(head_lines, names, path=path) + at_pin = { + name.casefold() + for _, name in detect_new_files( + pin_lines, names, cap=sys.maxsize, path=path + )[0] + } + found_files = [ + {"path": path, "line": number, "name": name, + "since_pin": name.casefold() not in at_pin} + for number, name in found + ] + if hashes: + added = [ + line + for line in difflib.unified_diff(pin_lines, head_lines, n=0) + if line.startswith("+") and not line.startswith("+++") + ] + found_hashes = [ + {"path": path, "kind": kind, "value": value} + for kind, value in watch_hashes(added, known) + ] + return found_files, elided, found_hashes def detect_upstream_changes( - profile: dict, report: ProfileReport, repo: upstream.Repo, + profile: dict, report: ProfileReport, cache_dir: str, offline: bool, files: bool, hashes: bool, ) -> None: """Record on the report the undeclared names (files) and the hash - literals added since the pin (hashes) of the cited files at HEAD.""" + literals added since the pin (hashes) of the cited files at HEAD, each + read in the repository the resolver settled it in.""" names, known = declared_names(profile), declared_hashes(profile) found_files: list[dict] = [] found_hashes: list[dict] = [] - for path in cited_paths(report): - head_lines = upstream.fetch_file( - repo, report.head, path, cache_dir, offline - ) - if head_lines is None: + # A path two repositories carry is read in both: a name or a hash the + # first already listed for that path is not listed again. + listed_files: set[tuple[str, str]] = set() + listed_hashes: set[tuple[str, str, str]] = set() + for source in report.cited_sources: + scanned = _scan_source(source, names, known, cache_dir, offline, files, hashes) + if scanned is None: continue - pin_lines = ( - upstream.fetch_file(repo, report.pin, path, cache_dir, offline) - or [] + new_files, elided, new_hashes = scanned + found_files.extend( + item for item in new_files + if (item["path"], item["name"].casefold()) not in listed_files ) - if files: - found, elided = detect_new_files(head_lines, names, path=path) - at_pin = { - name.casefold() - for _, name in detect_new_files( - pin_lines, names, cap=sys.maxsize, path=path - )[0] - } - found_files.extend( - {"path": path, "line": number, "name": name, - "since_pin": name.casefold() not in at_pin} - for number, name in found - ) - if elided: - report.new_files_elided[path] = elided - if hashes: - added = [ - line - for line in difflib.unified_diff(pin_lines, head_lines, n=0) - if line.startswith("+") and not line.startswith("+++") - ] - found_hashes.extend( - {"path": path, "kind": kind, "value": value} - for kind, value in watch_hashes(added, known) - ) + found_hashes.extend( + item for item in new_hashes + if (item["path"], item["kind"], item["value"]) not in listed_hashes + ) + listed_files.update((item["path"], item["name"].casefold()) for item in new_files) + listed_hashes.update((item["path"], item["kind"], item["value"]) for item in new_hashes) + if elided: + report.new_files_elided.setdefault(source.path, elided) if files: report.new_files = found_files if hashes: @@ -251,7 +271,7 @@ def detect_upstream_changes( def print_extras( - args: argparse.Namespace, profile: dict, report: ProfileReport + args: argparse.Namespace, report: ProfileReport ) -> None: """--full-diff and --tree-diff, read from the forge after the ref report. @@ -260,48 +280,44 @@ def print_extras( instead of ending a pass over every profile. A quota signal still ends the profile. """ - if not (args.full_diff or args.tree_diff) or not report.head: - return - repo = select_repo(profile) - if repo is None: + if not (args.full_diff or args.tree_diff) or not report.cited_sources: return try: - _print_extras_from(args, profile, report, repo) + _print_extras_from(args, report) except upstream.RateLimitError: raise except upstream.UpstreamError as exc: print(f" extras skipped: {exc}") -def _print_extras_from( - args: argparse.Namespace, profile: dict, report: ProfileReport, - repo: upstream.Repo, -) -> None: +def _print_extras_from(args: argparse.Namespace, report: ProfileReport) -> None: if args.full_diff: - for path in cited_paths(report): - if args.ref and args.ref not in path: + for source in report.cited_sources: + if args.ref and args.ref not in source.path: continue - pin_lines = ( - upstream.fetch_file( - repo, report.pin, path, args.cache_dir, args.offline - ) - or [] - ) - head_lines = ( - upstream.fetch_file( - repo, report.head, path, args.cache_dir, args.offline - ) - or [] - ) - text = unified_for_path(pin_lines, head_lines, path, args.context) + pin_lines = upstream.fetch_file( + source.repo, source.pin, source.path, args.cache_dir, args.offline + ) or [] + head_lines = upstream.fetch_file( + source.repo, source.head, source.path, args.cache_dir, args.offline + ) or [] + text = unified_for_path(pin_lines, head_lines, source.path, args.context) if text: print(text) if args.tree_diff: - comparison = upstream.compare( - repo, report.pin, report.head, args.cache_dir, args.offline - ) - # The repository root is a directory like any other: dropping the - # empty dirname would turn the filter off and list the whole tree. - ref_dirs = {posixpath.dirname(p) for p in cited_paths(report)} - for line in tree_diff(comparison, ref_dirs): - print(f" {line}") + by_repo: dict[tuple[str, str], list[CitedSource]] = {} + for source in report.cited_sources: + by_repo.setdefault((source.repo.host, source.repo.slug), []).append(source) + for sources in by_repo.values(): + first = sources[0] + comparison = upstream.compare( + first.repo, first.pin, first.head, args.cache_dir, args.offline + ) + if len(by_repo) > 1: + print(f" {first.repo.slug}:") + # The repository root is a directory like any other: dropping + # the empty dirname would turn the filter off and list the + # whole tree. + ref_dirs = {posixpath.dirname(source.path) for source in sources} + for line in tree_diff(comparison, ref_dirs): + print(f" {line}") diff --git a/scripts/profiling/reports.py b/scripts/profiling/reports.py index 5d1807c75..958a17075 100644 --- a/scripts/profiling/reports.py +++ b/scripts/profiling/reports.py @@ -20,6 +20,24 @@ class EntryReport: field: str = "" +@dataclass(frozen=True) +class CitedSource: + """A cited path in the repository the resolver settled it in, and the + two revisions that repository is compared at.""" + + path: str + repo: upstream.Repo + pin: str + head: str + # Read at its own revision: on HEAD, or held on the release tag the + # profile documents. A bump does not move such a repository. + own_revision: bool = False + + def advances(self) -> bool: + """Whether a bump moves this repository's pin past what was cited.""" + return self.pin != self.head and not self.own_revision + + @dataclass class ProfileReport: name: str @@ -91,6 +109,11 @@ class ProfileReport: # revision, ref, status, detail}. A status other than BUILD_OK is review # work. build_refs: list[dict] = field(default_factory=list) + # Each cited path with the repository holding it, as the resolver + # settled it: detection, the extras and the triage read the files + # there. geolith cites jg.c in its GitLab upstream, which the port the + # profile was read from does not carry. Not part of the JSON form. + cited_sources: list[CitedSource] = field(default_factory=list) # Skips that say the profile cannot be checked as written: a repository # that no longer answers, no pin to read, a death the forge contradicts. @@ -297,6 +320,7 @@ def format_report(report: ProfileReport, changed_only: bool = False) -> str: def report_to_dict(report: ProfileReport) -> dict: """Serialisable form of one report.""" payload = asdict(report) + del payload["cited_sources"] payload["needs_review"] = report.needs_review() return payload diff --git a/scripts/profiling/resolver.py b/scripts/profiling/resolver.py index 1bcc0e948..8ec72aa1a 100644 --- a/scripts/profiling/resolver.py +++ b/scripts/profiling/resolver.py @@ -38,7 +38,7 @@ from profiling.citations import ( strip_repo_word, symlink_target, ) -from profiling.reports import EntryReport, ProfileReport +from profiling.reports import CitedSource, EntryReport, ProfileReport from model.profilerepos import declared_repositories from profiling.repos import ( PIN, @@ -565,6 +565,24 @@ class _Resolver: self.owners[key] = self.locate(path, start, tokens, role) return self.owners[key] + def cited_source( + self, result: PartResult, tokens: Sequence[str] + ) -> CitedSource | None: + """Where a judged part's file was settled, None when it never was. + + A part annotated for another version is not looked up: no revision + of the pinned repositories holds that program. + """ + part = result.part + owner = self.owners.get((part.path, part.start, tuple(tokens), self.role_of(part))) + if owner is None: + return None + view, actual = owner + return CitedSource( + result.new_path or actual, view.repo, view.pin, view.head, + self.on_own_revision(view), + ) + def pin_tree_for(self, view: RepoView) -> list[str]: """Tree at the revision the refs were written against, memoised.""" key = view.repo.slug @@ -856,13 +874,23 @@ class _Resolver: def _judge_refs(resolver: _Resolver, refs: list, report: ProfileReport) -> None: """Judge every ref and put its entry on the report.""" staged = [] + sources: dict[tuple[str, str, str], CitedSource] = {} for entry_name, ref, tokens, hashes, ref_parts, citation in refs: flags = [resolver.self_checked(part, tokens) for part in ref_parts] judged = [ resolver.judge(part, flag, tokens, hashes) for part, flag in zip(ref_parts, flags) ] + for result in judged: + source = resolver.cited_source(result, tokens) + if source is not None: + sources.setdefault((source.path, source.repo.host, source.repo.slug), source) staged.append((entry_name, ref, citation, reconcile_self_check(judged, flags))) + order = {(v.repo.host, v.repo.slug): n for n, v in enumerate(resolver.views)} + report.cited_sources = sorted( + sources.values(), + key=lambda s: (s.path, order.get((s.repo.host, s.repo.slug), len(order))), + ) shifts = dominant_shifts([p for _, _, _, parts in staged for p in parts]) for entry_name, ref, citation, parts in staged: diff --git a/scripts/profiling/run.py b/scripts/profiling/run.py index 0f8da0c8a..9283b00c7 100644 --- a/scripts/profiling/run.py +++ b/scripts/profiling/run.py @@ -215,16 +215,23 @@ def _gained_since_pin( mame2003_plus gained two Taito G-NET BIOS sets in a zn.c whose cited lines only shifted. A bump past that would document a file set the code no longer has. --accept-changed says the additions were read. + Decided per repository: an upstream that moved while the port sits on + HEAD is read before a bump advances upstream_commit, and a repository + held on its tag, which the bump leaves there, is not. """ - if args.accept_changed or not report.head or report.pin == report.head: + advancing = {s.path for s in report.cited_sources if s.advances()} + if args.accept_changed or not advancing: return False if report.pinned_tag: # A held pin is not advanced at all: bump_commit says so itself. return False if report.new_files is None and report.new_hashes is None: _attach_detection(profile, report, args.cache_dir, args.offline, True, True) - gained = sorted({item["name"] for item in report.new_files or () if item.get("since_pin")}) - added = report.new_hashes or [] + gained = sorted({ + item["name"] for item in report.new_files or () + if item.get("since_pin") and item["path"] in advancing + }) + added = [item for item in report.new_hashes or () if item["path"] in advancing] if not (gained or added or report.detection_skipped): return False detail = ", ".join(gained[:5]) + (f", {len(added)} hash literal(s)" if added else "") @@ -251,11 +258,8 @@ def _attach_detection( """ if not report.head or not (files or hashes): return - repo = select_repo(profile) - if repo is None: - return try: - detect_upstream_changes(profile, report, repo, cache_dir, offline, files, hashes) + detect_upstream_changes(profile, report, cache_dir, offline, files, hashes) except upstream.RateLimitError: raise except upstream.UpstreamError as exc: @@ -466,7 +470,7 @@ def emit_reports( return print_triage(args, selected, shown) for report in shown: print(format_report(report, args.changed_only)) - print_extras(args, selected[report.name], report) + print_extras(args, report) print() if args.changed_only: _print_elided(reports, len(shown), frozenset(report.name for report in shown)) diff --git a/scripts/profiling/triage.py b/scripts/profiling/triage.py index bfcdaf2ab..127759164 100644 --- a/scripts/profiling/triage.py +++ b/scripts/profiling/triage.py @@ -7,7 +7,6 @@ import sys import time from core import upstream -from profiling.detection import cited_paths from profiling.reports import ProfileReport, triage_state from profiling.repos import select_repo from profiling.versions import VersionReport, check_version @@ -117,19 +116,21 @@ def _score( sampled = False repo = select_repo(profile) if report.head and repo is not None: - paths = cited_paths(report) + # Each cited path counted in the repository the resolver settled it + # in, between that repository's own pin and HEAD. + sources = report.cited_sources try: version = check_version(profile, repo, args.cache_dir, args.offline) - for path in paths[:TRIAGE_PATH_SAMPLE]: + for source in sources[:TRIAGE_PATH_SAMPLE]: commits += upstream.commits_touching( - repo, path, report.pin, args.cache_dir, args.offline, - head=report.head, + source.repo, source.path, source.pin, args.cache_dir, args.offline, + head=source.head, ) except upstream.UpstreamError as exc: # One forge refusing a request (Eden's answers 403 to commit # lookups) leaves this profile unscored, not the whole ranking. refused = "commit history unreachable" print(f"{report.name}: {exc}", file=sys.stderr) - sampled = len(paths) > TRIAGE_PATH_SAMPLE and not refused + sampled = len(sources) > TRIAGE_PATH_SAMPLE and not refused ranked.append((drift_score(report, version, commits), report, refused)) return sampled diff --git a/tests/test_profile_sync.py b/tests/test_profile_sync.py index a57bc574b..734e56def 100644 --- a/tests/test_profile_sync.py +++ b/tests/test_profile_sync.py @@ -38,6 +38,7 @@ from profiling import selection as profiling_selection from model import profiles as model_profiles from model import sourceref from profiling.reports import ( + CitedSource, EntryReport, ProfileReport, fetch_plan, @@ -1713,6 +1714,36 @@ class TestBuildReport(unittest.TestCase): report = build_report("mame", profile, self.dir) self.assertEqual(report.entries[0].status, "ANCHORED") + def test_each_cited_path_keeps_the_repository_it_was_settled_in(self): + # geolith cites jg.c in its GitLab upstream and src/geo.c in the + # port: detection read every path in the port and skipped jg.c. + self.files[("portpin", "src/geo.c")] = ["x", "load bios.bin"] + self.files[("porthead", "src/geo.c")] = ["x", "load bios.bin"] + self.files[("uppin", "jg.c")] = ["y", "load bios.bin"] + self.files[("uphead", "jg.c")] = ["pad", "y", "load bios.bin"] + heads = {"o/port": "porthead", "o/up": "uphead"} + upstream.resolve_head = ( + lambda repo, cache, offline=False, branch=None: heads[repo.slug] + ) + profile = { + "emulator": "Geolith", + "source": "https://github.com/o/port", + "upstream": "https://github.com/o/up", + "source_commit": "portpin", + "upstream_commit": "uppin", + "files": [ + {"name": "bios.bin", "source_ref": "src/geo.c:2"}, + {"name": "bios.bin", "source_ref": "jg.c:2"}, + ], + } + report = build_report("geolith", profile, self.dir) + self.assertEqual( + [(s.path, s.repo.slug, s.pin, s.head) for s in report.cited_sources], + [("jg.c", "o/up", "uppin", "uphead"), + ("src/geo.c", "o/port", "portpin", "porthead")], + ) + self.assertNotIn("cited_sources", report_to_dict(report)) + def test_self_check_reads_every_repository_before_calling_a_range_gone(self): # hatari: the port's src/paths.c runs 365 lines, the upstream's 345, # and a source_ref attributes the path to the upstream. With both on @@ -1923,9 +1954,17 @@ def _sample_report(): EntryReport("f1.bin", "b.c:5", "CHANGED", [changed]), ], counts={"SHIFTED": 1, "CHANGED": 1}, + cited_sources=[ + CitedSource(path, _SAMPLE_REPO, "pinsha0000", "headsha000") + for path in ("a.c", "b.c") + ], ) +_SAMPLE_REPO = upstream.parse_repo("https://github.com/o/n") +_UPSTREAM_REPO = upstream.parse_repo("https://gitlab.com/u/n") + + class TestDeclaredDeadUpstream(TestBuildReport): """A forge that is gone can be stated, which closes the question. @@ -2658,7 +2697,7 @@ class TestWriteDryRun(unittest.TestCase): from unittest import mock def gained(profile, report, *_): - report.new_files = [{"path": "zn.c", "name": "coh3002t.zip", "since_pin": True}] + report.new_files = [{"path": "a.c", "name": "coh3002t.zip", "since_pin": True}] report.new_hashes = [] before = self.path.read_text() @@ -2671,6 +2710,49 @@ class TestWriteDryRun(unittest.TestCase): self._run(self._args(rebase_refs=True, dry_run=False, accept_changed=True), self._shifted()) self.assertIn('source_commit: "newhead"', self.path.read_text()) + def test_an_upstream_that_moved_is_read_while_the_port_sits_on_head(self): + """geolith cites jg.c in its upstream: with the port on HEAD the guard + looked at the port alone and let upstream_commit move unread.""" + from unittest import mock + + seen = [] + + def gained(profile, report, *_): + seen.append(True) + report.new_files = [{"path": "jg.c", "name": "new.rom", "since_pin": True}] + report.new_hashes = [] + + report = self._shifted() + report.head = report.pin + report.cited_sources = [ + CitedSource("a.c", _SAMPLE_REPO, "pin", "pin", True), + CitedSource("jg.c", _UPSTREAM_REPO, "uppin", "uphead"), + ] + args = self._args(rebase_refs=True, dry_run=False) + with mock.patch.object(profiling_run, "_attach_detection", side_effect=gained), \ + contextlib.redirect_stderr(io.StringIO()) as err: + self.assertTrue(profiling_run._gained_since_pin(args, "p", {}, report)) + self.assertEqual(seen, [True]) + self.assertIn("new.rom", err.getvalue()) + + def test_a_repository_held_on_its_tag_does_not_hold_the_bump(self): + """GroovyMAME's upstream sits on mame0289 and the bump leaves it there: + what mamedev HEAD added to a cited driver is no reason to refuse.""" + from unittest import mock + + def gained(profile, report, *_): + report.new_files = [{"path": "neogeo.cpp", "name": "x.zip", "since_pin": True}] + report.new_hashes = [{"path": "neogeo.cpp", "kind": "md5", "value": "0" * 32}] + + report = self._shifted() + report.cited_sources = [ + CitedSource("a.c", _SAMPLE_REPO, "pin", "newhead"), + CitedSource("neogeo.cpp", _UPSTREAM_REPO, "tag", "uphead", True), + ] + args = self._args(rebase_refs=True, dry_run=False) + with mock.patch.object(profiling_run, "_attach_detection", side_effect=gained): + self.assertFalse(profiling_run._gained_since_pin(args, "p", {}, report)) + def _args(self, **over): base = dict( emulators_dir=str(self.dir), backfill_commits=False, @@ -2696,6 +2778,7 @@ class TestWriteDryRun(unittest.TestCase): name="p", repo="o/n", pin="pin", head="newhead", entries=[EntryReport("a.bin", "a.c:10-12", "SHIFTED", [part])], counts={"SHIFTED": 1}, + cited_sources=[CitedSource("a.c", _SAMPLE_REPO, "pin", "newhead")], ) def test_a_prose_read_that_fails_leaves_the_profile_as_it_was(self): @@ -6315,6 +6398,9 @@ class TheTriageCountsWhatBlocksThePin(unittest.TestCase): return ProfileReport( name=name, pin="p", head="h", entries=entries, counts={"ANCHORED": paths}, stale_prose=stale, + cited_sources=[ + CitedSource(f"d/{i}.c", _SAMPLE_REPO, "p", "h") for i in range(paths) + ], ) def test_stale_prose_is_review_work(self):