From 67d843dc8244e3333d5615e5beb5f001a0f47c6a Mon Sep 17 00:00:00 2001 From: Connor Sheehan Date: Tue, 24 Nov 2026 22:10:07 -0500 Subject: [PATCH 1/3] reviewhelper: describe the patch stack to the review agent Only `expand_context` applied the patch stack, so the agent checked stacked patches against mozilla-central and flagged code added earlier in the stack as missing. The first message now lists the patches before and after the reviewed one, with the files the nearest ancestors touch, and the Searchfox tools warn that they do not see the stack. Refs #7350 --- bugbug/tools/code_review/agent.py | 29 +++- bugbug/tools/code_review/langchain_tools.py | 30 ++++ bugbug/tools/code_review/prompts.py | 10 ++ bugbug/tools/code_review/stack.py | 154 ++++++++++++++++++++ bugbug/tools/core/platforms/base.py | 20 ++- bugbug/tools/core/platforms/phabricator.py | 37 ++++- tests/test_code_review.py | 90 +++++++++++- tests/test_code_review_stack.py | 126 ++++++++++++++++ 8 files changed, 489 insertions(+), 7 deletions(-) create mode 100644 bugbug/tools/code_review/stack.py create mode 100644 tests/test_code_review_stack.py diff --git a/bugbug/tools/code_review/agent.py b/bugbug/tools/code_review/agent.py index bbe5efde80a..c9c3228d081 100644 --- a/bugbug/tools/code_review/agent.py +++ b/bugbug/tools/code_review/agent.py @@ -42,11 +42,17 @@ SYSTEM_PROMPT_TEMPLATE, TEMPLATE_COMMENT_EXAMPLE, TEMPLATE_PATCH_FROM_HUNK, + TEMPLATE_PATCH_STACK, ) from bugbug.tools.code_review.protocols import ( PatchSummarizer, SuggestionFilterer, ) +from bugbug.tools.code_review.stack import ( + PatchStack, + format_stack_context, + load_patch_stack, +) from bugbug.tools.code_review.utils import ( convert_generated_comments_to_inline, format_patch_set, @@ -210,21 +216,33 @@ def count_tokens(self, text): return len(self._tokenizer.encode(text)) def generate_initial_prompt( - self, patch: Patch, patch_summary: str, external_context: str = "" + self, + patch: Patch, + patch_summary: str, + external_context: str = "", + stack: Optional[PatchStack] = None, ) -> str: created_before = patch.date_created if self.is_experiment_env else None + if stack is None: + stack = load_patch_stack(patch) + stack_context = format_stack_context(stack) return FIRST_MESSAGE_TEMPLATE.format( current_date=current_date_for_prompt(), patch=format_patch_set(patch.patch_set), patch_summarization=patch_summary, external_context=external_context, + patch_stack=( + TEMPLATE_PATCH_STACK.format(stack_context=stack_context) + if stack_context + else "" + ), comment_examples=self._get_comment_examples(patch, created_before), approved_examples=self._get_generated_examples(patch, created_before), ) async def generate_review_comments( - self, patch: Patch, patch_summary: str + self, patch: Patch, patch_summary: str, stack: Optional[PatchStack] = None ) -> tuple[AgentResponse, list[dict]]: external_context = "" manifest: list[dict] = [] @@ -249,7 +267,9 @@ async def generate_review_comments( messages = [ HumanMessage( - self.generate_initial_prompt(patch, patch_summary, external_context) + self.generate_initial_prompt( + patch, patch_summary, external_context, stack + ) ) ] for attempt in range(2): @@ -307,9 +327,10 @@ async def run(self, patch: Patch) -> CodeReviewToolResponse: raise LargeDiffError("The diff is too large") patch_summary = self.patch_summarizer.run(patch) + stack = load_patch_stack(patch) agent_response, external_content_manifest = await self.generate_review_comments( - patch, patch_summary + patch, patch_summary, stack ) unfiltered_suggestions = agent_response.comments if not unfiltered_suggestions: diff --git a/bugbug/tools/code_review/langchain_tools.py b/bugbug/tools/code_review/langchain_tools.py index d1d4ce46bf0..e147e6d7b5e 100644 --- a/bugbug/tools/code_review/langchain_tools.py +++ b/bugbug/tools/code_review/langchain_tools.py @@ -193,6 +193,9 @@ async def search_text( ) -> str: """Search for text or patterns across the codebase. + Results come from mozilla-central, without this patch or its stack. Use + `expand_context` to read a file as the patch stack leaves it. + Args: query: Text or regular expression to search for. path_filter: Optional path prefix, e.g. 'dom/media'. @@ -242,6 +245,9 @@ async def get_field_layout( ) -> str: """Show the memory layout of a C++ class or struct, including field offsets and sizes. + Results come from mozilla-central, without this patch or its stack. Use + `expand_context` to read a file as the patch stack leaves it. + Args: class_name: Fully-qualified class name, e.g. 'mozilla::dom::AudioContext'. @@ -267,6 +273,9 @@ async def get_blame( ) -> str: """Get the commit that last modified each of the given lines in a file. + Results come from mozilla-central, without this patch or its stack. Use + `expand_context` to read a file as the patch stack leaves it. + Args: file_path: Repository-relative path, e.g. 'dom/media/webaudio/AudioNode.cpp'. lines: List of 1-based line numbers to look up. @@ -300,6 +309,9 @@ async def check_can_gc( ) -> str: """Check whether a C++ function can trigger garbage collection in SpiderMonkey. + Results come from mozilla-central, without this patch or its stack. Use + `expand_context` to read a file as the patch stack leaves it. + Accepts partial names (e.g. 'CreateGain') or fully-qualified names (e.g. 'mozilla::dom::AudioContext::CreateGain'). @@ -338,6 +350,9 @@ async def find_definition( ) -> str: """Find the definition of a function, method, class, or struct. + Results come from mozilla-central, without this patch or its stack. Use + `expand_context` to read a file as the patch stack leaves it. + Accepts partial names (e.g. 'AudioNode') or fully-qualified names (e.g. 'mozilla::dom::AudioNode' or 'AudioNode::Connect'). @@ -372,6 +387,9 @@ async def search_identifier( ) -> str: """Search for an exact identifier across the codebase. + Results come from mozilla-central, without this patch or its stack. Use + `expand_context` to read a file as the patch stack leaves it. + Args: identifier: Identifier to search for. path_filter: Optional path prefix, e.g. 'dom/media'. @@ -416,6 +434,9 @@ async def calls_from( ) -> str: """Find functions called by the given symbol (outgoing calls). + Results come from mozilla-central, without this patch or its stack. Use + `expand_context` to read a file as the patch stack leaves it. + Args: symbol: Fully-qualified function or method name, e.g. 'mozilla::dom::AudioNode::Connect'. depth: Levels of calls to traverse (default 2). @@ -444,6 +465,9 @@ async def calls_to( ) -> str: """Find functions that call the given symbol (incoming calls). + Results come from mozilla-central, without this patch or its stack. Use + `expand_context` to read a file as the patch stack leaves it. + Args: symbol: Fully-qualified function or method name, e.g. 'mozilla::dom::AudioNode::Connect'. depth: Levels of callers to traverse (default 2). @@ -473,6 +497,9 @@ async def calls_between( ) -> str: """Find call paths between two symbols or classes. + Results come from mozilla-central, without this patch or its stack. Use + `expand_context` to read a file as the patch stack leaves it. + Args: symbol_a: First fully-qualified symbol or class name, e.g. 'mozilla::dom::AudioContext'. symbol_b: Second fully-qualified symbol or class name. @@ -513,6 +540,9 @@ async def get_function_at_line( ) -> str: """Get the source of the innermost function enclosing a given line. + Results come from mozilla-central, without this patch or its stack. Use + `expand_context` to read a file as the patch stack leaves it. + Useful when you know a line number and want the full function body without having to know the function name. diff --git a/bugbug/tools/code_review/prompts.py b/bugbug/tools/code_review/prompts.py index 75348f9ed00..4bc0bc7eb9b 100644 --- a/bugbug/tools/code_review/prompts.py +++ b/bugbug/tools/code_review/prompts.py @@ -120,6 +120,7 @@ +{patch_stack} Here is the patch you need to review: @@ -128,6 +129,15 @@ """ +TEMPLATE_PATCH_STACK = """Here is the stack of patches this patch belongs to: + + +{stack_context} + + +""" + + TEMPLATE_COMMENT_EXAMPLE = """Patch example {example_number}: {patch} diff --git a/bugbug/tools/code_review/stack.py b/bugbug/tools/code_review/stack.py new file mode 100644 index 00000000000..69927ddf2ed --- /dev/null +++ b/bugbug/tools/code_review/stack.py @@ -0,0 +1,154 @@ +# -*- coding: utf-8 -*- +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this file, +# You can obtain one at http://mozilla.org/MPL/2.0/. + +"""Describe the stack of patches that a reviewed patch belongs to.""" + +from dataclasses import dataclass, field +from logging import getLogger +from typing import Optional + +from unidiff import PatchSet + +from bugbug.tools.core.platforms.base import Patch + +logger = getLogger(__name__) + +# The nearest ancestors are listed with the files they touch, older ones by +# title only, to keep deep stacks within a reasonable prompt size. +MAX_DETAILED_ANCESTORS = 15 +MAX_FILES_PER_ANCESTOR = 10 +MAX_LISTED_ANCESTORS = 60 +MAX_LISTED_DESCENDANTS = 15 + +STACK_TOOLS_WARNING = """\ +The Searchfox-backed tools (`find_definition`, `search_text`, `search_identifier`, +`get_blame`, `get_function_at_line`, `get_field_layout`, `calls_from`, `calls_to`, +`calls_between` and `check_can_gc`) index mozilla-central, so they do not see this +patch or any patch in its stack. Before reporting that a symbol does not exist, that a +caller was not updated, or that code is unchanged, read the files the ancestors touch +with `expand_context`, which applies the whole stack. + +Later patches may finish work that this patch starts. Do not report a missing +follow-up step that the title of a later patch says it covers.""" + + +@dataclass(frozen=True) +class StackEntry: + """One patch in the stack, other than the reviewed one.""" + + display_id: str + + title: str + + # The changes of the patch, or `None` when they were not loaded. + patch_set: Optional[PatchSet] = None + + +@dataclass(frozen=True) +class PatchStack: + """The patches around the reviewed patch in its stack.""" + + # The patches applied before the reviewed one, oldest first. + ancestors: list[StackEntry] = field(default_factory=list) + + # The patches that build on the reviewed one, nearest first. + descendants: list[StackEntry] = field(default_factory=list) + + # Problems that kept part of the stack from loading. + errors: list[str] = field(default_factory=list) + + @property + def is_stacked(self) -> bool: + return bool(self.ancestors or self.descendants or self.errors) + + +def load_patch_stack(patch: Patch) -> PatchStack: + """Load the titles and changes of the patches around `patch`. + + The stack is optional context, so a failure to load it is recorded in + `errors` rather than raised. + """ + ancestors: list[StackEntry] = [] + descendants: list[StackEntry] = [] + errors = [] + + logger.debug("Loading the ancestors of patch %s.", patch.patch_id) + try: + ancestors = [ + StackEntry(ancestor.display_id, ancestor.patch_title, ancestor.patch_set) + for ancestor in patch.stack_ancestors + ] + except Exception as error: + logger.warning("Could not load the ancestors of %s: %s", patch.patch_id, error) + errors.append(f"The patches before this one could not be loaded ({error}).") + + logger.debug("Loading the descendants of patch %s.", patch.patch_id) + try: + descendants = [ + StackEntry(descendant.display_id, descendant.patch_title) + for descendant in patch.stack_descendants + ] + except Exception as error: + logger.warning( + "Could not load the descendants of %s: %s", patch.patch_id, error + ) + errors.append(f"The patches after this one could not be loaded ({error}).") + + return PatchStack(ancestors, descendants, errors) + + +def format_file_changes(patch_set: PatchSet) -> list[str]: + """Return one line per file the patch touches, with its line counts.""" + lines = [ + f" - {patched_file.path} (+{patched_file.added} -{patched_file.removed})" + for patched_file in patch_set[:MAX_FILES_PER_ANCESTOR] + ] + if len(patch_set) > MAX_FILES_PER_ANCESTOR: + lines.append(f" - … and {len(patch_set) - MAX_FILES_PER_ANCESTOR} more files") + return lines + + +def format_ancestors(ancestors: list[StackEntry]) -> list[str]: + """List the ancestors nearest first, with the files the nearest ones touch.""" + nearest_first = list(reversed(ancestors)) + lines = [f"{len(ancestors)} patches come before this one, nearest first:"] + for position, ancestor in enumerate(nearest_first[:MAX_LISTED_ANCESTORS]): + lines.append(f"- {ancestor.display_id}: {ancestor.title}") + if position < MAX_DETAILED_ANCESTORS and ancestor.patch_set is not None: + lines.extend(format_file_changes(ancestor.patch_set)) + if len(nearest_first) > MAX_LISTED_ANCESTORS: + lines.append(f"- … and {len(nearest_first) - MAX_LISTED_ANCESTORS} older") + return lines + + +def format_descendants(descendants: list[StackEntry]) -> list[str]: + """List the descendants nearest first, by title only.""" + lines = [f"{len(descendants)} patches build on this one, nearest first:"] + lines.extend( + f"- {descendant.display_id}: {descendant.title}" + for descendant in descendants[:MAX_LISTED_DESCENDANTS] + ) + if len(descendants) > MAX_LISTED_DESCENDANTS: + lines.append(f"- … and {len(descendants) - MAX_LISTED_DESCENDANTS} more") + return lines + + +def format_stack_context(stack: PatchStack) -> str: + """Describe the stack for the review prompt, or return "" for a lone patch.""" + if not stack.is_stacked: + return "" + + sections = [ + "This patch is part of a stack of patches. The patches before it have not " + "landed, and this patch is written against the code as they leave it." + ] + if stack.ancestors: + sections.append("\n".join(format_ancestors(stack.ancestors))) + if stack.descendants: + sections.append("\n".join(format_descendants(stack.descendants))) + sections.extend(f"Warning: {error}" for error in stack.errors) + sections.append(STACK_TOOLS_WARNING) + + return "\n\n".join(sections) diff --git a/bugbug/tools/core/platforms/base.py b/bugbug/tools/core/platforms/base.py index c1ceeb43edb..1e0b60c5e4c 100644 --- a/bugbug/tools/core/platforms/base.py +++ b/bugbug/tools/core/platforms/base.py @@ -10,7 +10,7 @@ from datetime import datetime from functools import cached_property from logging import getLogger -from typing import Iterable, Optional +from typing import Iterable, Optional, Sequence from unidiff import Hunk, PatchedFile, PatchSet @@ -48,6 +48,24 @@ def stack_base_patch(self) -> Patch: """Return the patch whose base precedes the entire stack.""" return self + @property + def stack_ancestors(self) -> Sequence[Patch]: + """Return the patches applied before this one, oldest first. + + Raises `ValueError` when the stack cannot be determined. + """ + return [] + + @property + def stack_descendants(self) -> Sequence[Patch]: + """Return the patches that build on this one, nearest first.""" + return [] + + @property + def display_id(self) -> str: + """Return a short, human-readable identifier for the patch.""" + return self.patch_id + @property @abstractmethod def bug_title(self) -> str: diff --git a/bugbug/tools/core/platforms/phabricator.py b/bugbug/tools/core/platforms/phabricator.py index bdd51c29e6e..351c7a6e653 100644 --- a/bugbug/tools/core/platforms/phabricator.py +++ b/bugbug/tools/core/platforms/phabricator.py @@ -6,7 +6,7 @@ """Phabricator platform implementation for code review.""" import os -from collections import defaultdict +from collections import defaultdict, deque from datetime import UTC, datetime from functools import cache, cached_property from logging import getLogger @@ -888,6 +888,41 @@ def patch_stack(self) -> list[PatchSet]: def stack_base_patch(self) -> PhabricatorPatch: return self._stack_patches[0] + @property + def stack_ancestors(self) -> list[PhabricatorPatch]: + return self._stack_patches[:-1] + + @cached_property + def stack_descendants(self) -> list[PhabricatorPatch]: + """Return the revisions that depend on this one, nearest first. + + Unlike the ancestry, descendants may branch, so every revision that + transitively depends on this one is returned. + """ + stack_graph = self.stack_graph + children: defaultdict[str, list[str]] = defaultdict(list) + for phid, deps in stack_graph.items(): + for dep in deps: + children[dep].append(phid) + + current_phid = self._revision_metadata["phid"] + ordered_phids = [] + seen = {current_phid} + queue = deque(children[current_phid]) + while queue: + phid = queue.popleft() + if phid in seen: + continue + seen.add(phid) + ordered_phids.append(phid) + queue.extend(children[phid]) + + return [self.__class__(revision_phid=phid) for phid in ordered_phids] + + @property + def display_id(self) -> str: + return f"D{self.revision_id}" + @cached_property def _all_comments(self) -> list: return [c for c in self.get_comments() if c.is_renderable] diff --git a/tests/test_code_review.py b/tests/test_code_review.py index bed6675f35b..a9e184ef04a 100644 --- a/tests/test_code_review.py +++ b/tests/test_code_review.py @@ -46,6 +46,7 @@ from bugbug.tools.code_review.review_context_schema import ( main as validate_review_context_main, ) +from bugbug.tools.code_review.stack import PatchStack, StackEntry from bugbug.tools.code_review.utils import ( convert_generated_comments_to_inline, find_comment_scope, @@ -71,7 +72,13 @@ def make_patch(raw_diff): patch_set = PatchSet.from_string(raw_diff) - return SimpleNamespace(patch_set=patch_set, patch_stack=[patch_set]) + return SimpleNamespace( + patch_id="1", + patch_set=patch_set, + patch_stack=[patch_set], + stack_ancestors=[], + stack_descendants=[], + ) def make_patch_stack(*raw_diffs): @@ -303,6 +310,52 @@ def patch_set(self): assert len(stack) == 3 # A, C, E +def make_graph_patch_class(stack_graph): + """Build a `PhabricatorPatch` subclass whose revisions come from `stack_graph`.""" + + class FakeGraphPatch(phab_platform.PhabricatorPatch): + @property + def _revision_metadata(self): + return { + "phid": self._revision_phid, + "id": int(self._revision_phid.removeprefix("PHID-")), + "fields": {"stackGraph": stack_graph}, + } + + return FakeGraphPatch + + +def test_stack_ancestors_and_descendants(): + # 1 <- 2 <- 3 <- 4, and 5 also builds on 3. + stack_graph = { + "PHID-1": [], + "PHID-2": ["PHID-1"], + "PHID-3": ["PHID-2"], + "PHID-4": ["PHID-3"], + "PHID-5": ["PHID-3"], + } + patch_class = make_graph_patch_class(stack_graph) + middle = patch_class(revision_phid="PHID-2") + + assert [ancestor.display_id for ancestor in middle.stack_ancestors] == ["D1"], ( + "`stack_ancestors` should list the revisions below this one, oldest first." + ) + assert [descendant.display_id for descendant in middle.stack_descendants] == [ + "D3", + "D4", + "D5", + ], "`stack_descendants` should list every dependent revision, nearest first." + + +def test_stack_of_single_revision_is_empty(): + patch_class = make_graph_patch_class({}) + single = patch_class(revision_phid="PHID-7") + + assert single.stack_ancestors == [], "A lone revision should have no ancestors." + assert single.stack_descendants == [], "A lone revision should have no descendants." + assert single.display_id == "D7", "`display_id` should be the `D` revision ID." + + # --------------------------------------------------------------------------- # find_comment_scope # --------------------------------------------------------------------------- @@ -1912,8 +1965,11 @@ async def fake_astream(*args, **kwargs): def _make_review_patch(github_repo_ref_return=None): patch_set = PatchSet.from_string("--- a/f.txt\n+++ b/f.txt\n@@ -0,0 +1,1 @@\n+a\n") return SimpleNamespace( + patch_id="1", raw_diff="diff", patch_set=patch_set, + stack_ancestors=[], + stack_descendants=[], github_repo_ref=AsyncMock(return_value=github_repo_ref_return), ) @@ -2007,6 +2063,29 @@ async def fake_astream(input, **kwargs): asyncio.run(tool.generate_review_comments(fake_patch, "summary")) +def test_initial_prompt_describes_patch_stack(): + tool = _make_review_tool(review_context_repo=None) + fake_patch = _make_review_patch() + stack = PatchStack(ancestors=[StackEntry("D1", "Add `matcher`")]) + + prompt = tool.generate_initial_prompt(fake_patch, "summary", stack=stack) + + assert "" in prompt, "A stacked patch should get a stack section." + assert "- D1: Add `matcher`" in prompt, "The stack section should list ancestors." + assert prompt.index("") < prompt.index(""), ( + "The stack should be described before the patch under review." + ) + + +def test_initial_prompt_omits_stack_for_lone_patch(): + tool = _make_review_tool(review_context_repo=None) + fake_patch = _make_review_patch() + + prompt = tool.generate_initial_prompt(fake_patch, "summary") + + assert "patch_stack" not in prompt, "A lone patch should get no stack section." + + @pytest.mark.parametrize( "before_patch,expected", [(True, "1| deleted"), (False, "1| kept")] ) @@ -2087,3 +2166,12 @@ def test_expand_context_handles_renamed_file_views( else: assert result == expected assert len(requests) == 1 + + +def test_searchfox_tools_say_they_do_not_see_the_stack(): + for searchfox_tool in langchain_tools.SEARCHFOX_TOOLS: + if searchfox_tool is langchain_tools.expand_context: + continue + assert "without this patch or its stack" in searchfox_tool.description, ( + f"`{searchfox_tool.name}` should say that Searchfox does not see the stack." + ) diff --git a/tests/test_code_review_stack.py b/tests/test_code_review_stack.py new file mode 100644 index 00000000000..2bef6fc61a0 --- /dev/null +++ b/tests/test_code_review_stack.py @@ -0,0 +1,126 @@ +from types import SimpleNamespace + +from unidiff import PatchSet + +from bugbug.tools.code_review import stack as stack_module +from bugbug.tools.code_review.stack import ( + STACK_TOOLS_WARNING, + PatchStack, + StackEntry, + format_stack_context, + load_patch_stack, +) + + +def make_diff(path, added=1): + added_lines = "".join(f"+line {number}\n" for number in range(added)) + return PatchSet.from_string( + f"--- a/{path}\n+++ b/{path}\n@@ -1 +1,{added} @@\n-old\n{added_lines}" + ) + + +def make_stack_patch(display_id, title, patch_set=None): + return SimpleNamespace( + display_id=display_id, patch_title=title, patch_set=patch_set + ) + + +class BrokenStackPatch: + patch_id = "99" + stack_descendants: list = [] + + @property + def stack_ancestors(self): + raise ValueError("Patch stack is not linear") + + +def test_load_patch_stack_reads_titles_and_changes(): + ancestor_diff = make_diff("a.py") + patch = SimpleNamespace( + patch_id="3", + stack_ancestors=[make_stack_patch("D1", "Add `matcher`", ancestor_diff)], + stack_descendants=[make_stack_patch("D4", "Use `matcher`")], + ) + + stack = load_patch_stack(patch) + + assert stack.ancestors == [StackEntry("D1", "Add `matcher`", ancestor_diff)], ( + "Ancestors should keep their changes." + ) + assert stack.descendants == [StackEntry("D4", "Use `matcher`")], ( + "Descendants should be loaded by title only." + ) + assert stack.errors == [], "A healthy stack should report no errors." + + +def test_load_patch_stack_records_errors(): + stack = load_patch_stack(BrokenStackPatch()) + + assert stack.ancestors == [], "Unreadable ancestors should be left out." + assert stack.errors == [ + "The patches before this one could not be loaded (Patch stack is not linear)." + ], "The reason the ancestors could not be loaded should be recorded." + assert format_stack_context(stack).count("Warning:") == 1, ( + "The prompt should tell the model the stack is incomplete." + ) + + +def test_format_stack_context_is_empty_for_lone_patch(): + assert format_stack_context(PatchStack()) == "", ( + "A patch that is not in a stack should add nothing to the prompt." + ) + + +def test_format_stack_context_lists_ancestors_nearest_first(): + stack = PatchStack( + ancestors=[ + StackEntry("D1", "Bottom", make_diff("bottom.py")), + StackEntry("D2", "Add `matcher`", make_diff("python/path.py", added=3)), + ], + descendants=[StackEntry("D4", "Use `matcher` everywhere")], + ) + + context = format_stack_context(stack) + + assert context.index("D2: Add `matcher`") < context.index("D1: Bottom"), ( + "The nearest ancestor should be listed first." + ) + assert " - python/path.py (+3 -1)" in context, ( + "Each ancestor should list the files it touches with line counts." + ) + assert "1 patches build on this one" in context, "Descendants should be listed." + assert "D4: Use `matcher` everywhere" in context, ( + "Descendants should be listed by title." + ) + assert context.endswith(STACK_TOOLS_WARNING), ( + "The prompt should warn that Searchfox does not see the stack." + ) + + +def test_format_stack_context_truncates_deep_stacks(monkeypatch): + monkeypatch.setattr(stack_module, "MAX_DETAILED_ANCESTORS", 1) + monkeypatch.setattr(stack_module, "MAX_LISTED_ANCESTORS", 2) + monkeypatch.setattr(stack_module, "MAX_FILES_PER_ANCESTOR", 1) + two_files = PatchSet.from_string( + str(make_diff("first.py")) + str(make_diff("second.py")) + ) + stack = PatchStack( + ancestors=[ + StackEntry("D1", "Oldest", make_diff("oldest.py")), + StackEntry("D2", "Middle", make_diff("middle.py")), + StackEntry("D3", "Nearest", two_files), + ] + ) + + context = format_stack_context(stack) + + assert "first.py" in context, "The nearest ancestor should list its files." + assert "… and 1 more files" in context, "Long file lists should be truncated." + assert "middle.py" not in context, ( + "Ancestors past `MAX_DETAILED_ANCESTORS` should be listed by title only." + ) + assert "D2: Middle" in context, "Listed ancestors should keep their titles." + assert "Oldest" not in context, ( + "Ancestors past `MAX_LISTED_ANCESTORS` should be left out." + ) + assert "… and 1 older" in context, "The prompt should count omitted ancestors." From f94916905fd3cdf27dfa67e238a405b2a797e430 Mon Sep 17 00:00:00 2001 From: Connor Sheehan Date: Wed, 25 Nov 2026 22:41:02 -0500 Subject: [PATCH 2/3] reviewhelper: load the patch stack with batched Conduit calls One revision search per side of the stack and one diff query for the nearest ancestors' files replace two calls per patch. --- bugbug/tools/code_review/stack.py | 38 +++++---- bugbug/tools/core/platforms/base.py | 24 ++++++ bugbug/tools/core/platforms/phabricator.py | 74 +++++++++++++++-- tests/test_code_review.py | 94 +++++++++++++++++++--- tests/test_code_review_stack.py | 57 +++++++------ 5 files changed, 229 insertions(+), 58 deletions(-) diff --git a/bugbug/tools/code_review/stack.py b/bugbug/tools/code_review/stack.py index 69927ddf2ed..a607bbf4a23 100644 --- a/bugbug/tools/code_review/stack.py +++ b/bugbug/tools/code_review/stack.py @@ -9,9 +9,7 @@ from logging import getLogger from typing import Optional -from unidiff import PatchSet - -from bugbug.tools.core.platforms.base import Patch +from bugbug.tools.core.platforms.base import FileChange, Patch logger = getLogger(__name__) @@ -42,8 +40,8 @@ class StackEntry: title: str - # The changes of the patch, or `None` when they were not loaded. - patch_set: Optional[PatchSet] = None + # The files the patch touches, or `None` when they were not loaded. + file_changes: Optional[list[FileChange]] = None @dataclass(frozen=True) @@ -76,9 +74,17 @@ def load_patch_stack(patch: Patch) -> PatchStack: logger.debug("Loading the ancestors of patch %s.", patch.patch_id) try: + stack_ancestors = patch.stack_ancestors + file_changes = patch.load_stack_file_changes( + stack_ancestors[-MAX_DETAILED_ANCESTORS:] + ) ancestors = [ - StackEntry(ancestor.display_id, ancestor.patch_title, ancestor.patch_set) - for ancestor in patch.stack_ancestors + StackEntry( + ancestor.display_id, + ancestor.patch_title, + file_changes.get(ancestor.patch_id), + ) + for ancestor in stack_ancestors ] except Exception as error: logger.warning("Could not load the ancestors of %s: %s", patch.patch_id, error) @@ -99,14 +105,16 @@ def load_patch_stack(patch: Patch) -> PatchStack: return PatchStack(ancestors, descendants, errors) -def format_file_changes(patch_set: PatchSet) -> list[str]: +def format_file_changes(file_changes: list[FileChange]) -> list[str]: """Return one line per file the patch touches, with its line counts.""" lines = [ - f" - {patched_file.path} (+{patched_file.added} -{patched_file.removed})" - for patched_file in patch_set[:MAX_FILES_PER_ANCESTOR] + f" - {change.path} (+{change.added} -{change.removed})" + for change in file_changes[:MAX_FILES_PER_ANCESTOR] ] - if len(patch_set) > MAX_FILES_PER_ANCESTOR: - lines.append(f" - … and {len(patch_set) - MAX_FILES_PER_ANCESTOR} more files") + if len(file_changes) > MAX_FILES_PER_ANCESTOR: + lines.append( + f" - … and {len(file_changes) - MAX_FILES_PER_ANCESTOR} more files" + ) return lines @@ -114,10 +122,10 @@ def format_ancestors(ancestors: list[StackEntry]) -> list[str]: """List the ancestors nearest first, with the files the nearest ones touch.""" nearest_first = list(reversed(ancestors)) lines = [f"{len(ancestors)} patches come before this one, nearest first:"] - for position, ancestor in enumerate(nearest_first[:MAX_LISTED_ANCESTORS]): + for ancestor in nearest_first[:MAX_LISTED_ANCESTORS]: lines.append(f"- {ancestor.display_id}: {ancestor.title}") - if position < MAX_DETAILED_ANCESTORS and ancestor.patch_set is not None: - lines.extend(format_file_changes(ancestor.patch_set)) + if ancestor.file_changes is not None: + lines.extend(format_file_changes(ancestor.file_changes)) if len(nearest_first) > MAX_LISTED_ANCESTORS: lines.append(f"- … and {len(nearest_first) - MAX_LISTED_ANCESTORS} older") return lines diff --git a/bugbug/tools/core/platforms/base.py b/bugbug/tools/core/platforms/base.py index 1e0b60c5e4c..e79a4971f1b 100644 --- a/bugbug/tools/core/platforms/base.py +++ b/bugbug/tools/core/platforms/base.py @@ -7,6 +7,7 @@ import re from abc import ABC, abstractmethod +from dataclasses import dataclass from datetime import datetime from functools import cached_property from logging import getLogger @@ -19,6 +20,17 @@ logger = getLogger(__name__) +@dataclass(frozen=True) +class FileChange: + """A file touched by a patch, with its line counts.""" + + path: str + + added: int + + removed: int + + class Patch(ABC): """Abstract base class for code patches.""" @@ -61,6 +73,18 @@ def stack_descendants(self) -> Sequence[Patch]: """Return the patches that build on this one, nearest first.""" return [] + def load_stack_file_changes( + self, ancestors: Sequence[Patch] + ) -> dict[str, list[FileChange]]: + """Return the files each of `ancestors` touches, keyed by `patch_id`.""" + return { + ancestor.patch_id: [ + FileChange(patched_file.path, patched_file.added, patched_file.removed) + for patched_file in ancestor.patch_set + ] + for ancestor in ancestors + } + @property def display_id(self) -> str: """Return a short, human-readable identifier for the patch.""" diff --git a/bugbug/tools/core/platforms/phabricator.py b/bugbug/tools/core/platforms/phabricator.py index 351c7a6e653..643c20472a2 100644 --- a/bugbug/tools/core/platforms/phabricator.py +++ b/bugbug/tools/core/platforms/phabricator.py @@ -10,7 +10,7 @@ from datetime import UTC, datetime from functools import cache, cached_property from logging import getLogger -from typing import Iterable, Optional +from typing import Iterable, Optional, Sequence import tenacity from async_lru import alru_cache @@ -24,7 +24,7 @@ get_user_agent, ) from bugbug.tools.core.data_types import InlineComment -from bugbug.tools.core.platforms.base import Patch, ReviewData +from bugbug.tools.core.platforms.base import FileChange, Patch, ReviewData from bugbug.tools.core.platforms.bugzilla import Bug logger = getLogger(__name__) @@ -151,6 +151,27 @@ def _repo_callsign(repository_phid: str) -> Optional[str]: return data[0]["fields"].get("callsign") +# The most results `differential.revision.search` returns in one page. +REVISION_SEARCH_LIMIT = 100 + + +def search_revisions(revision_phids: list[str]) -> dict[str, dict]: + """Return the revisions for `revision_phids`, keyed by PHID, in pages of 100.""" + phabricator = get_phabricator_client() + revisions = {} + for start in range(0, len(revision_phids), REVISION_SEARCH_LIMIT): + logger.debug("Searching for %s revisions.", len(revision_phids) - start) + response = phabricator.request( + "differential.revision.search", + constraints={ + "phids": revision_phids[start : start + REVISION_SEARCH_LIMIT] + }, + limit=REVISION_SEARCH_LIMIT, + ) + revisions.update({revision["phid"]: revision for revision in response["data"]}) + return revisions + + @cache def get_project_members(project_phid: str) -> frozenset[str]: """Return the set of user PHIDs that are members of a Phabricator project. @@ -384,6 +405,7 @@ def __init__( diff_id: Optional[str | int] = None, revision_phid: Optional[str] = None, revision_id: Optional[int] = None, + revision_metadata: Optional[dict] = None, ) -> None: super().__init__() assert diff_id or revision_phid or revision_id, ( @@ -393,6 +415,7 @@ def __init__( self._diff_id = diff_id self._revision_phid = revision_phid self._revision_id = revision_id + self.preloaded_revision_metadata = revision_metadata @property def patch_url(self) -> str: @@ -673,6 +696,9 @@ def date_modified(self) -> datetime: @cached_property def _revision_metadata(self) -> dict: + if self.preloaded_revision_metadata is not None: + return self.preloaded_revision_metadata + phabricator = get_phabricator_client() # We pass either the revision PHID or the revision ID, not both. @@ -888,9 +914,17 @@ def patch_stack(self) -> list[PatchSet]: def stack_base_patch(self) -> PhabricatorPatch: return self._stack_patches[0] - @property + @cached_property def stack_ancestors(self) -> list[PhabricatorPatch]: - return self._stack_patches[:-1] + """Return the ancestors, with their revisions loaded in one search.""" + ancestors = self._stack_patches[:-1] + revisions = search_revisions([ancestor.revision_phid for ancestor in ancestors]) + for ancestor in ancestors: + if ancestor.preloaded_revision_metadata is None: + ancestor.preloaded_revision_metadata = revisions.get( + ancestor.revision_phid + ) + return ancestors @cached_property def stack_descendants(self) -> list[PhabricatorPatch]: @@ -917,7 +951,37 @@ def stack_descendants(self) -> list[PhabricatorPatch]: ordered_phids.append(phid) queue.extend(children[phid]) - return [self.__class__(revision_phid=phid) for phid in ordered_phids] + revisions = search_revisions(ordered_phids) + return [ + self.__class__(revision_phid=phid, revision_metadata=revisions[phid]) + for phid in ordered_phids + if phid in revisions + ] + + def load_stack_file_changes( + self, ancestors: Sequence[Patch] + ) -> dict[str, list[FileChange]]: + """Return the files each of `ancestors` touches with one diff query.""" + if not ancestors: + return {} + + phabricator = get_phabricator_client() + logger.debug("Loading the file changes of %s diffs.", len(ancestors)) + diffs = phabricator.request( + "differential.querydiffs", + ids=[int(ancestor.patch_id) for ancestor in ancestors], + ) + return { + str(diff_id): [ + FileChange( + path=change["currentPath"] or change["oldPath"], + added=int(change["addLines"]), + removed=int(change["delLines"]), + ) + for change in diff["changes"] + ] + for diff_id, diff in diffs.items() + } @property def display_id(self) -> str: diff --git a/tests/test_code_review.py b/tests/test_code_review.py index a9e184ef04a..43cbb74b436 100644 --- a/tests/test_code_review.py +++ b/tests/test_code_review.py @@ -56,6 +56,7 @@ CommentSeverity, ) from bugbug.tools.core.platforms import phabricator as phab_platform +from bugbug.tools.core.platforms.base import FileChange from bugbug.tools.core.platforms.patch_apply import ( apply_patched_file, get_file_after_stack, @@ -78,6 +79,7 @@ def make_patch(raw_diff): patch_stack=[patch_set], stack_ancestors=[], stack_descendants=[], + load_stack_file_changes=lambda ancestors: {}, ) @@ -316,16 +318,59 @@ def make_graph_patch_class(stack_graph): class FakeGraphPatch(phab_platform.PhabricatorPatch): @property def _revision_metadata(self): - return { - "phid": self._revision_phid, - "id": int(self._revision_phid.removeprefix("PHID-")), - "fields": {"stackGraph": stack_graph}, - } + if self.preloaded_revision_metadata is not None: + return self.preloaded_revision_metadata + return make_graph_revision(self._revision_phid, stack_graph) return FakeGraphPatch -def test_stack_ancestors_and_descendants(): +def make_graph_revision(phid, stack_graph=None): + number = int(phid.removeprefix("PHID-")) + return { + "phid": phid, + "id": number, + "fields": { + "title": f"Revision {number}", + "diffID": number * 10, + "stackGraph": stack_graph or {}, + }, + } + + +def fake_stack_conduit(monkeypatch): + """Answer revision searches and diff queries, recording each Conduit call.""" + calls = [] + + def request(method, **payload): + calls.append(method) + if method == "differential.revision.search": + phids = payload["constraints"]["phids"] + return {"data": [make_graph_revision(phid) for phid in phids]} + assert method == "differential.querydiffs", f"Unexpected `{method}` call." + return { + str(diff_id): { + "changes": [ + { + "currentPath": f"file{diff_id}.py", + "oldPath": None, + "addLines": "2", + "delLines": "1", + } + ] + } + for diff_id in payload["ids"] + } + + monkeypatch.setattr( + phab_platform, + "get_phabricator_client", + lambda: SimpleNamespace(request=request), + ) + return calls + + +def test_stack_ancestors_and_descendants(monkeypatch): # 1 <- 2 <- 3 <- 4, and 5 also builds on 3. stack_graph = { "PHID-1": [], @@ -334,20 +379,44 @@ def test_stack_ancestors_and_descendants(): "PHID-4": ["PHID-3"], "PHID-5": ["PHID-3"], } + calls = fake_stack_conduit(monkeypatch) patch_class = make_graph_patch_class(stack_graph) - middle = patch_class(revision_phid="PHID-2") + middle = patch_class(revision_phid="PHID-3") - assert [ancestor.display_id for ancestor in middle.stack_ancestors] == ["D1"], ( - "`stack_ancestors` should list the revisions below this one, oldest first." - ) + assert [ancestor.patch_title for ancestor in middle.stack_ancestors] == [ + "Revision 1", + "Revision 2", + ], "`stack_ancestors` should list the revisions below this one, oldest first." assert [descendant.display_id for descendant in middle.stack_descendants] == [ - "D3", "D4", "D5", ], "`stack_descendants` should list every dependent revision, nearest first." + assert calls == ["differential.revision.search"] * 2, ( + "Each side of the stack should load with one revision search." + ) + + +def test_load_stack_file_changes_uses_one_diff_query(monkeypatch): + calls = fake_stack_conduit(monkeypatch) + patch_class = make_graph_patch_class({}) + ancestors = [ + patch_class(revision_phid=phid, revision_metadata=make_graph_revision(phid)) + for phid in ["PHID-1", "PHID-2"] + ] + + file_changes = patch_class(revision_phid="PHID-3").load_stack_file_changes( + ancestors + ) + + assert file_changes == { + "10": [FileChange("file10.py", 2, 1)], + "20": [FileChange("file20.py", 2, 1)], + }, "File changes should be keyed by `patch_id`." + assert calls == ["differential.querydiffs"], "One diff query should load them." -def test_stack_of_single_revision_is_empty(): +def test_stack_of_single_revision_is_empty(monkeypatch): + fake_stack_conduit(monkeypatch) patch_class = make_graph_patch_class({}) single = patch_class(revision_phid="PHID-7") @@ -1970,6 +2039,7 @@ def _make_review_patch(github_repo_ref_return=None): patch_set=patch_set, stack_ancestors=[], stack_descendants=[], + load_stack_file_changes=lambda ancestors: {}, github_repo_ref=AsyncMock(return_value=github_repo_ref_return), ) diff --git a/tests/test_code_review_stack.py b/tests/test_code_review_stack.py index 2bef6fc61a0..8c27ab954ca 100644 --- a/tests/test_code_review_stack.py +++ b/tests/test_code_review_stack.py @@ -1,7 +1,5 @@ from types import SimpleNamespace -from unidiff import PatchSet - from bugbug.tools.code_review import stack as stack_module from bugbug.tools.code_review.stack import ( STACK_TOOLS_WARNING, @@ -10,18 +8,16 @@ format_stack_context, load_patch_stack, ) +from bugbug.tools.core.platforms.base import FileChange -def make_diff(path, added=1): - added_lines = "".join(f"+line {number}\n" for number in range(added)) - return PatchSet.from_string( - f"--- a/{path}\n+++ b/{path}\n@@ -1 +1,{added} @@\n-old\n{added_lines}" - ) +def make_changes(*paths, added=1): + return [FileChange(path, added, 1) for path in paths] -def make_stack_patch(display_id, title, patch_set=None): +def make_stack_patch(display_id, title): return SimpleNamespace( - display_id=display_id, patch_title=title, patch_set=patch_set + patch_id=display_id, display_id=display_id, patch_title=title ) @@ -34,19 +30,33 @@ def stack_ancestors(self): raise ValueError("Patch stack is not linear") -def test_load_patch_stack_reads_titles_and_changes(): - ancestor_diff = make_diff("a.py") +def test_load_patch_stack_reads_titles_and_changes(monkeypatch): + monkeypatch.setattr(stack_module, "MAX_DETAILED_ANCESTORS", 1) + requested = [] + + def load_stack_file_changes(ancestors): + requested.extend(ancestor.patch_id for ancestor in ancestors) + return {"D2": make_changes("a.py")} + patch = SimpleNamespace( patch_id="3", - stack_ancestors=[make_stack_patch("D1", "Add `matcher`", ancestor_diff)], + stack_ancestors=[ + make_stack_patch("D1", "Add `pattern`"), + make_stack_patch("D2", "Add `matcher`"), + ], stack_descendants=[make_stack_patch("D4", "Use `matcher`")], + load_stack_file_changes=load_stack_file_changes, ) stack = load_patch_stack(patch) - assert stack.ancestors == [StackEntry("D1", "Add `matcher`", ancestor_diff)], ( - "Ancestors should keep their changes." + assert requested == ["D2"], ( + "Only the nearest `MAX_DETAILED_ANCESTORS` should load their file changes." ) + assert stack.ancestors == [ + StackEntry("D1", "Add `pattern`"), + StackEntry("D2", "Add `matcher`", make_changes("a.py")), + ], "Ancestors should keep their file changes." assert stack.descendants == [StackEntry("D4", "Use `matcher`")], ( "Descendants should be loaded by title only." ) @@ -74,8 +84,8 @@ def test_format_stack_context_is_empty_for_lone_patch(): def test_format_stack_context_lists_ancestors_nearest_first(): stack = PatchStack( ancestors=[ - StackEntry("D1", "Bottom", make_diff("bottom.py")), - StackEntry("D2", "Add `matcher`", make_diff("python/path.py", added=3)), + StackEntry("D1", "Bottom", make_changes("bottom.py")), + StackEntry("D2", "Add `matcher`", make_changes("python/path.py", added=3)), ], descendants=[StackEntry("D4", "Use `matcher` everywhere")], ) @@ -98,17 +108,13 @@ def test_format_stack_context_lists_ancestors_nearest_first(): def test_format_stack_context_truncates_deep_stacks(monkeypatch): - monkeypatch.setattr(stack_module, "MAX_DETAILED_ANCESTORS", 1) monkeypatch.setattr(stack_module, "MAX_LISTED_ANCESTORS", 2) monkeypatch.setattr(stack_module, "MAX_FILES_PER_ANCESTOR", 1) - two_files = PatchSet.from_string( - str(make_diff("first.py")) + str(make_diff("second.py")) - ) stack = PatchStack( ancestors=[ - StackEntry("D1", "Oldest", make_diff("oldest.py")), - StackEntry("D2", "Middle", make_diff("middle.py")), - StackEntry("D3", "Nearest", two_files), + StackEntry("D1", "Oldest", make_changes("oldest.py")), + StackEntry("D2", "Middle"), + StackEntry("D3", "Nearest", make_changes("first.py", "second.py")), ] ) @@ -116,10 +122,9 @@ def test_format_stack_context_truncates_deep_stacks(monkeypatch): assert "first.py" in context, "The nearest ancestor should list its files." assert "… and 1 more files" in context, "Long file lists should be truncated." - assert "middle.py" not in context, ( - "Ancestors past `MAX_DETAILED_ANCESTORS` should be listed by title only." + assert "- D2: Middle\n- … and 1 older" in context, ( + "Ancestors without file changes should be listed by title only." ) - assert "D2: Middle" in context, "Listed ancestors should keep their titles." assert "Oldest" not in context, ( "Ancestors past `MAX_LISTED_ANCESTORS` should be left out." ) From 9cc7a781b4d9092b7088c23b68dc2cb4ff2bcc01 Mon Sep 17 00:00:00 2001 From: Connor Sheehan Date: Fri, 27 Nov 2026 15:23:40 -0500 Subject: [PATCH 3/3] reviewhelper: load the patch stack with the async Conduit client Ancestors reuse the cached `get_stack_patches`, so they load concurrently and are shared with `expand_context`. Descendants load with one revision search. --- bugbug/tools/code_review/agent.py | 8 +- bugbug/tools/code_review/stack.py | 78 +++++++++--------- bugbug/tools/core/platforms/base.py | 37 ++------- bugbug/tools/core/platforms/phabricator.py | 49 ++++++++++- services/mcp/src/bugbug_mcp/server.py | 2 +- services/mcp/tests/test_patch_review.py | 4 +- tests/test_code_review.py | 96 ++++++++++++++++++++-- tests/test_code_review_stack.py | 74 +++++++++-------- 8 files changed, 232 insertions(+), 116 deletions(-) diff --git a/bugbug/tools/code_review/agent.py b/bugbug/tools/code_review/agent.py index e1987ded387..e345683bae2 100644 --- a/bugbug/tools/code_review/agent.py +++ b/bugbug/tools/code_review/agent.py @@ -215,7 +215,7 @@ def create(cls, **kwargs): def count_tokens(self, text): return len(self._tokenizer.encode(text)) - def generate_initial_prompt( + async def generate_initial_prompt( self, patch: Patch, patch_summary: str, @@ -224,7 +224,7 @@ def generate_initial_prompt( ) -> str: created_before = patch.date_created if self.is_experiment_env else None if stack is None: - stack = load_patch_stack(patch) + stack = await load_patch_stack(patch) stack_context = format_stack_context(stack) return FIRST_MESSAGE_TEMPLATE.format( @@ -260,7 +260,7 @@ async def generate_review_comments( messages = [ HumanMessage( - self.generate_initial_prompt( + await self.generate_initial_prompt( patch, patch_summary, external_context, stack ) ) @@ -321,7 +321,7 @@ async def run(self, patch: Patch) -> CodeReviewToolResponse: raise LargeDiffError("The diff is too large") patch_summary = self.patch_summarizer.run(patch) - stack = load_patch_stack(patch) + stack = await load_patch_stack(patch) agent_response, external_content_manifest = await self.generate_review_comments( patch, patch_summary, stack diff --git a/bugbug/tools/code_review/stack.py b/bugbug/tools/code_review/stack.py index a607bbf4a23..5f7e4f9a572 100644 --- a/bugbug/tools/code_review/stack.py +++ b/bugbug/tools/code_review/stack.py @@ -5,11 +5,14 @@ """Describe the stack of patches that a reviewed patch belongs to.""" +import asyncio from dataclasses import dataclass, field from logging import getLogger from typing import Optional -from bugbug.tools.core.platforms.base import FileChange, Patch +from unidiff import PatchSet + +from bugbug.tools.core.platforms.base import Patch logger = getLogger(__name__) @@ -40,8 +43,8 @@ class StackEntry: title: str - # The files the patch touches, or `None` when they were not loaded. - file_changes: Optional[list[FileChange]] = None + # The changes of the patch, or `None` when they were not loaded. + patch_set: Optional[PatchSet] = None @dataclass(frozen=True) @@ -62,59 +65,60 @@ def is_stacked(self) -> bool: return bool(self.ancestors or self.descendants or self.errors) -def load_patch_stack(patch: Patch) -> PatchStack: - """Load the titles and changes of the patches around `patch`. +async def load_patch_stack(patch: Patch) -> PatchStack: + """Load the titles and changes of the patches around `patch`, concurrently. The stack is optional context, so a failure to load it is recorded in `errors` rather than raised. """ - ancestors: list[StackEntry] = [] - descendants: list[StackEntry] = [] - errors = [] + ( + (ancestors, ancestors_error), + (descendants, descendants_error), + ) = await asyncio.gather(load_ancestors(patch), load_descendants(patch)) + errors = [error for error in (ancestors_error, descendants_error) if error] + return PatchStack(ancestors, descendants, errors) + +async def load_ancestors(patch: Patch) -> tuple[list[StackEntry], Optional[str]]: + """Return the ancestors of `patch` with their changes, or the reason they failed.""" logger.debug("Loading the ancestors of patch %s.", patch.patch_id) try: - stack_ancestors = patch.stack_ancestors - file_changes = patch.load_stack_file_changes( - stack_ancestors[-MAX_DETAILED_ANCESTORS:] - ) - ancestors = [ - StackEntry( - ancestor.display_id, - ancestor.patch_title, - file_changes.get(ancestor.patch_id), - ) - for ancestor in stack_ancestors - ] + ancestors = await patch.get_stack_ancestors() except Exception as error: logger.warning("Could not load the ancestors of %s: %s", patch.patch_id, error) - errors.append(f"The patches before this one could not be loaded ({error}).") + return [], f"The patches before this one could not be loaded ({error})." + return [ + StackEntry(ancestor.display_id, ancestor.patch_title, ancestor.patch_set) + for ancestor in ancestors + ], None + + +async def load_descendants(patch: Patch) -> tuple[list[StackEntry], Optional[str]]: + """Return the descendants of `patch` by title, or the reason they failed.""" logger.debug("Loading the descendants of patch %s.", patch.patch_id) try: - descendants = [ - StackEntry(descendant.display_id, descendant.patch_title) - for descendant in patch.stack_descendants - ] + descendants = await patch.get_stack_descendants() except Exception as error: logger.warning( "Could not load the descendants of %s: %s", patch.patch_id, error ) - errors.append(f"The patches after this one could not be loaded ({error}).") + return [], f"The patches after this one could not be loaded ({error})." - return PatchStack(ancestors, descendants, errors) + return [ + StackEntry(descendant.display_id, descendant.patch_title) + for descendant in descendants + ], None -def format_file_changes(file_changes: list[FileChange]) -> list[str]: +def format_file_changes(patch_set: PatchSet) -> list[str]: """Return one line per file the patch touches, with its line counts.""" lines = [ - f" - {change.path} (+{change.added} -{change.removed})" - for change in file_changes[:MAX_FILES_PER_ANCESTOR] + f" - {patched_file.path} (+{patched_file.added} -{patched_file.removed})" + for patched_file in patch_set[:MAX_FILES_PER_ANCESTOR] ] - if len(file_changes) > MAX_FILES_PER_ANCESTOR: - lines.append( - f" - … and {len(file_changes) - MAX_FILES_PER_ANCESTOR} more files" - ) + if len(patch_set) > MAX_FILES_PER_ANCESTOR: + lines.append(f" - … and {len(patch_set) - MAX_FILES_PER_ANCESTOR} more files") return lines @@ -122,10 +126,10 @@ def format_ancestors(ancestors: list[StackEntry]) -> list[str]: """List the ancestors nearest first, with the files the nearest ones touch.""" nearest_first = list(reversed(ancestors)) lines = [f"{len(ancestors)} patches come before this one, nearest first:"] - for ancestor in nearest_first[:MAX_LISTED_ANCESTORS]: + for position, ancestor in enumerate(nearest_first[:MAX_LISTED_ANCESTORS]): lines.append(f"- {ancestor.display_id}: {ancestor.title}") - if ancestor.file_changes is not None: - lines.extend(format_file_changes(ancestor.file_changes)) + if position < MAX_DETAILED_ANCESTORS and ancestor.patch_set is not None: + lines.extend(format_file_changes(ancestor.patch_set)) if len(nearest_first) > MAX_LISTED_ANCESTORS: lines.append(f"- … and {len(nearest_first) - MAX_LISTED_ANCESTORS} older") return lines diff --git a/bugbug/tools/core/platforms/base.py b/bugbug/tools/core/platforms/base.py index 4b8a0fb543f..93949099e24 100644 --- a/bugbug/tools/core/platforms/base.py +++ b/bugbug/tools/core/platforms/base.py @@ -7,7 +7,6 @@ import re from abc import ABC, abstractmethod -from dataclasses import dataclass from datetime import datetime from functools import cached_property from logging import getLogger @@ -20,17 +19,6 @@ logger = getLogger(__name__) -@dataclass(frozen=True) -class FileChange: - """A file touched by a patch, with its line counts.""" - - path: str - - added: int - - removed: int - - class Patch(ABC): """Abstract base class for code patches.""" @@ -60,30 +48,19 @@ def stack_base_patch(self) -> Patch: """Return the patch whose base precedes the entire stack.""" return self - @property - def stack_ancestors(self) -> Sequence[Patch]: - """Return the patches applied before this one, oldest first. + async def get_stack_ancestors(self) -> Sequence[Patch]: + """Return the loaded patches applied before this one, oldest first. Raises `ValueError` when the stack cannot be determined. """ return [] - @property - def stack_descendants(self) -> Sequence[Patch]: - """Return the patches that build on this one, nearest first.""" - return [] + async def get_stack_descendants(self) -> Sequence[Patch]: + """Return the patches that build on this one, nearest first. - def load_stack_file_changes( - self, ancestors: Sequence[Patch] - ) -> dict[str, list[FileChange]]: - """Return the files each of `ancestors` touches, keyed by `patch_id`.""" - return { - ancestor.patch_id: [ - FileChange(patched_file.path, patched_file.added, patched_file.removed) - for patched_file in ancestor.patch_set - ] - for ancestor in ancestors - } + Only their titles and identifiers are guaranteed to be loaded. + """ + return [] @property def display_id(self) -> str: diff --git a/bugbug/tools/core/platforms/phabricator.py b/bugbug/tools/core/platforms/phabricator.py index 85309ed8e3b..7a285bde105 100644 --- a/bugbug/tools/core/platforms/phabricator.py +++ b/bugbug/tools/core/platforms/phabricator.py @@ -8,7 +8,7 @@ import asyncio import json import os -from collections import defaultdict +from collections import defaultdict, deque from datetime import UTC, datetime from functools import cache, cached_property from logging import getLogger @@ -929,6 +929,53 @@ async def get_stack_patches(self) -> list[PhabricatorPatch]: await asyncio.gather(*(patch.load() for patch in stack)) return stack + async def get_stack_ancestors(self) -> list[PhabricatorPatch]: + return (await self.get_stack_patches())[:-1] + + @alru_cache + async def get_stack_descendants(self) -> list[PhabricatorPatch]: + """Return the revisions that depend on this one, nearest first. + + Unlike the ancestry, descendants may branch, so every revision that + transitively depends on this one is returned. Their revisions are + loaded with one search, and their diffs are not loaded. + """ + stack_graph = self.stack_graph + children: defaultdict[str, list[str]] = defaultdict(list) + for phid, deps in stack_graph.items(): + for dep in deps: + children[dep].append(phid) + + current_phid = self._revision_metadata["phid"] + ordered_phids = [] + seen = {current_phid} + queue = deque(children[current_phid]) + while queue: + phid = queue.popleft() + if phid in seen: + continue + seen.add(phid) + ordered_phids.append(phid) + queue.extend(children[phid]) + + if not ordered_phids: + return [] + + logger.debug("Searching for %s descendant revisions.", len(ordered_phids)) + response = await _conduit( + "differential.revision.search", constraints={"phids": ordered_phids} + ) + revisions = {revision["phid"]: revision for revision in response["data"]} + + descendants = [] + for phid in ordered_phids: + if phid not in revisions: + continue + descendant = self.__class__(revision_phid=phid) + descendant._revision_metadata = revisions[phid] + descendants.append(descendant) + return descendants + @property def display_id(self) -> str: return f"D{self.revision_id}" diff --git a/services/mcp/src/bugbug_mcp/server.py b/services/mcp/src/bugbug_mcp/server.py index c61f495d3ef..777c2d1b91c 100644 --- a/services/mcp/src/bugbug_mcp/server.py +++ b/services/mcp/src/bugbug_mcp/server.py @@ -85,7 +85,7 @@ async def patch_review( extra_context_toml=extra_context_toml, content_overrides=overrides, ) - initial_prompt = tool.generate_initial_prompt( + initial_prompt = await tool.generate_initial_prompt( patch, patch_summary, external_context ) diff --git a/services/mcp/tests/test_patch_review.py b/services/mcp/tests/test_patch_review.py index 301c82d3f91..88892e77354 100644 --- a/services/mcp/tests/test_patch_review.py +++ b/services/mcp/tests/test_patch_review.py @@ -13,7 +13,9 @@ def review_dependencies(mocker): mocker.patch("bugbug_mcp.server.PhabricatorPatch", return_value=patch) tool = Mock(target_software="Firefox") tool.patch_summarizer.run.return_value = "summary" - tool.generate_initial_prompt.side_effect = lambda patch, summary, context: context + tool.generate_initial_prompt = AsyncMock( + side_effect=lambda patch, summary, context: context + ) mocker.patch("bugbug_mcp.server.get_code_review_tool", return_value=tool) loader = mocker.patch( "bugbug.tools.code_review.review_context.load_external_context_for_review", diff --git a/tests/test_code_review.py b/tests/test_code_review.py index b3bef75712d..da56ce22149 100644 --- a/tests/test_code_review.py +++ b/tests/test_code_review.py @@ -80,8 +80,8 @@ def make_patch(raw_diff): patch_id="1", patch_set=patch_set, patch_stack=[patch_set], - stack_ancestors=[], - stack_descendants=[], + get_stack_ancestors=AsyncMock(return_value=[]), + get_stack_descendants=AsyncMock(return_value=[]), load_stack_file_changes=lambda ancestors: {}, ) @@ -308,6 +308,88 @@ def stack_graph(self): assert len(stack) == 3 # A, C, E +def make_graph_revision(phid, stack_graph=None): + number = int(phid.removeprefix("PHID-")) + return { + "phid": phid, + "id": number, + "fields": {"title": f"Revision {number}", "stackGraph": stack_graph or {}}, + } + + +def make_graph_patch_class(stack_graph): + """Build a `PhabricatorPatch` subclass whose revisions come from `stack_graph`.""" + + class FakeGraphPatch(phab_platform.PhabricatorPatch): + async def load(self): + self._revision_metadata = make_graph_revision( + self._revision_phid, stack_graph + ) + + return FakeGraphPatch + + +def fake_revision_search(monkeypatch): + """Answer `differential.revision.search`, recording the PHIDs of each call.""" + searches = [] + + async def conduit(method, **params): + assert method == "differential.revision.search", f"Unexpected `{method}`." + phids = params["constraints"]["phids"] + searches.append(phids) + return {"data": [make_graph_revision(phid) for phid in phids]} + + monkeypatch.setattr(phab_platform, "_conduit", conduit) + return searches + + +def test_stack_ancestors_and_descendants(monkeypatch): + # 1 <- 2 <- 3 <- 4, and 5 also builds on 3. + stack_graph = { + "PHID-1": [], + "PHID-2": ["PHID-1"], + "PHID-3": ["PHID-2"], + "PHID-4": ["PHID-3"], + "PHID-5": ["PHID-3"], + } + searches = fake_revision_search(monkeypatch) + middle = make_graph_patch_class(stack_graph)(revision_phid="PHID-2") + asyncio.run(middle.load()) + + ancestors = asyncio.run(middle.get_stack_ancestors()) + descendants = asyncio.run(middle.get_stack_descendants()) + + assert [ancestor.display_id for ancestor in ancestors] == ["D1"], ( + "`get_stack_ancestors` should list the revisions below this one, oldest first." + ) + assert [descendant.display_id for descendant in descendants] == [ + "D3", + "D4", + "D5", + ], "`get_stack_descendants` should list every dependent revision, nearest first." + assert descendants[0].patch_title == "Revision 3", ( + "Descendants should have their titles loaded." + ) + assert searches == [["PHID-3", "PHID-4", "PHID-5"]], ( + "The descendants should load with one revision search." + ) + + +def test_stack_of_single_revision_is_empty(monkeypatch): + searches = fake_revision_search(monkeypatch) + single = make_graph_patch_class({})(revision_phid="PHID-7") + asyncio.run(single.load()) + + assert asyncio.run(single.get_stack_ancestors()) == [], ( + "A lone revision should have no ancestors." + ) + assert asyncio.run(single.get_stack_descendants()) == [], ( + "A lone revision should have no descendants." + ) + assert searches == [], "A lone revision should make no Conduit calls." + assert single.display_id == "D7", "`display_id` should be the `D` revision ID." + + # --------------------------------------------------------------------------- # find_comment_scope # --------------------------------------------------------------------------- @@ -2342,8 +2424,8 @@ def _make_review_patch(github_repo_ref_return=None): patch_id="1", raw_diff="diff", patch_set=patch_set, - stack_ancestors=[], - stack_descendants=[], + get_stack_ancestors=AsyncMock(return_value=[]), + get_stack_descendants=AsyncMock(return_value=[]), load_stack_file_changes=lambda ancestors: {}, github_repo_ref=AsyncMock(return_value=github_repo_ref_return), ) @@ -2443,7 +2525,9 @@ def test_initial_prompt_describes_patch_stack(): fake_patch = _make_review_patch() stack = PatchStack(ancestors=[StackEntry("D1", "Add `matcher`")]) - prompt = tool.generate_initial_prompt(fake_patch, "summary", stack=stack) + prompt = asyncio.run( + tool.generate_initial_prompt(fake_patch, "summary", stack=stack) + ) assert "" in prompt, "A stacked patch should get a stack section." assert "- D1: Add `matcher`" in prompt, "The stack section should list ancestors." @@ -2456,7 +2540,7 @@ def test_initial_prompt_omits_stack_for_lone_patch(): tool = _make_review_tool(review_context_repo=None) fake_patch = _make_review_patch() - prompt = tool.generate_initial_prompt(fake_patch, "summary") + prompt = asyncio.run(tool.generate_initial_prompt(fake_patch, "summary")) assert "patch_stack" not in prompt, "A lone patch should get no stack section." diff --git a/tests/test_code_review_stack.py b/tests/test_code_review_stack.py index 8c27ab954ca..b888a1a7080 100644 --- a/tests/test_code_review_stack.py +++ b/tests/test_code_review_stack.py @@ -1,4 +1,8 @@ +import asyncio from types import SimpleNamespace +from unittest.mock import AsyncMock + +from unidiff import PatchSet from bugbug.tools.code_review import stack as stack_module from bugbug.tools.code_review.stack import ( @@ -8,55 +12,48 @@ format_stack_context, load_patch_stack, ) -from bugbug.tools.core.platforms.base import FileChange -def make_changes(*paths, added=1): - return [FileChange(path, added, 1) for path in paths] +def make_diff(path, added=1): + added_lines = "".join(f"+line {number}\n" for number in range(added)) + return PatchSet.from_string( + f"--- a/{path}\n+++ b/{path}\n@@ -1 +1,{added} @@\n-old\n{added_lines}" + ) -def make_stack_patch(display_id, title): +def make_stack_patch(display_id, title, patch_set=None): return SimpleNamespace( - patch_id=display_id, display_id=display_id, patch_title=title + display_id=display_id, patch_title=title, patch_set=patch_set ) class BrokenStackPatch: patch_id = "99" - stack_descendants: list = [] - @property - def stack_ancestors(self): + async def get_stack_ancestors(self): raise ValueError("Patch stack is not linear") + async def get_stack_descendants(self): + return [] -def test_load_patch_stack_reads_titles_and_changes(monkeypatch): - monkeypatch.setattr(stack_module, "MAX_DETAILED_ANCESTORS", 1) - requested = [] - - def load_stack_file_changes(ancestors): - requested.extend(ancestor.patch_id for ancestor in ancestors) - return {"D2": make_changes("a.py")} +def test_load_patch_stack_reads_titles_and_changes(): + ancestor_diff = make_diff("a.py") patch = SimpleNamespace( patch_id="3", - stack_ancestors=[ - make_stack_patch("D1", "Add `pattern`"), - make_stack_patch("D2", "Add `matcher`"), - ], - stack_descendants=[make_stack_patch("D4", "Use `matcher`")], - load_stack_file_changes=load_stack_file_changes, + get_stack_ancestors=AsyncMock( + return_value=[make_stack_patch("D1", "Add `matcher`", ancestor_diff)] + ), + get_stack_descendants=AsyncMock( + return_value=[make_stack_patch("D4", "Use `matcher`")] + ), ) - stack = load_patch_stack(patch) + stack = asyncio.run(load_patch_stack(patch)) - assert requested == ["D2"], ( - "Only the nearest `MAX_DETAILED_ANCESTORS` should load their file changes." + assert stack.ancestors == [StackEntry("D1", "Add `matcher`", ancestor_diff)], ( + "Ancestors should keep their changes." ) - assert stack.ancestors == [ - StackEntry("D1", "Add `pattern`"), - StackEntry("D2", "Add `matcher`", make_changes("a.py")), - ], "Ancestors should keep their file changes." assert stack.descendants == [StackEntry("D4", "Use `matcher`")], ( "Descendants should be loaded by title only." ) @@ -64,7 +61,7 @@ def load_stack_file_changes(ancestors): def test_load_patch_stack_records_errors(): - stack = load_patch_stack(BrokenStackPatch()) + stack = asyncio.run(load_patch_stack(BrokenStackPatch())) assert stack.ancestors == [], "Unreadable ancestors should be left out." assert stack.errors == [ @@ -84,8 +81,8 @@ def test_format_stack_context_is_empty_for_lone_patch(): def test_format_stack_context_lists_ancestors_nearest_first(): stack = PatchStack( ancestors=[ - StackEntry("D1", "Bottom", make_changes("bottom.py")), - StackEntry("D2", "Add `matcher`", make_changes("python/path.py", added=3)), + StackEntry("D1", "Bottom", make_diff("bottom.py")), + StackEntry("D2", "Add `matcher`", make_diff("python/path.py", added=3)), ], descendants=[StackEntry("D4", "Use `matcher` everywhere")], ) @@ -108,13 +105,17 @@ def test_format_stack_context_lists_ancestors_nearest_first(): def test_format_stack_context_truncates_deep_stacks(monkeypatch): + monkeypatch.setattr(stack_module, "MAX_DETAILED_ANCESTORS", 1) monkeypatch.setattr(stack_module, "MAX_LISTED_ANCESTORS", 2) monkeypatch.setattr(stack_module, "MAX_FILES_PER_ANCESTOR", 1) + two_files = PatchSet.from_string( + str(make_diff("first.py")) + str(make_diff("second.py")) + ) stack = PatchStack( ancestors=[ - StackEntry("D1", "Oldest", make_changes("oldest.py")), - StackEntry("D2", "Middle"), - StackEntry("D3", "Nearest", make_changes("first.py", "second.py")), + StackEntry("D1", "Oldest", make_diff("oldest.py")), + StackEntry("D2", "Middle", make_diff("middle.py")), + StackEntry("D3", "Nearest", two_files), ] ) @@ -122,9 +123,10 @@ def test_format_stack_context_truncates_deep_stacks(monkeypatch): assert "first.py" in context, "The nearest ancestor should list its files." assert "… and 1 more files" in context, "Long file lists should be truncated." - assert "- D2: Middle\n- … and 1 older" in context, ( - "Ancestors without file changes should be listed by title only." + assert "middle.py" not in context, ( + "Ancestors past `MAX_DETAILED_ANCESTORS` should be listed by title only." ) + assert "D2: Middle" in context, "Listed ancestors should keep their titles." assert "Oldest" not in context, ( "Ancestors past `MAX_LISTED_ANCESTORS` should be left out." )