diff --git a/bugbug/tools/code_review/agent.py b/bugbug/tools/code_review/agent.py index b424feffbb..e345683bae 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, @@ -209,22 +215,34 @@ def create(cls, **kwargs): def count_tokens(self, text): return len(self._tokenizer.encode(text)) - def generate_initial_prompt( - self, patch: Patch, patch_summary: str, external_context: str = "" + async def generate_initial_prompt( + 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 = await 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]]: from bugbug.tools.code_review.review_context import ( resolve_external_context_for_review, @@ -242,7 +260,9 @@ async def generate_review_comments( messages = [ HumanMessage( - self.generate_initial_prompt(patch, patch_summary, external_context) + await self.generate_initial_prompt( + patch, patch_summary, external_context, stack + ) ) ] for attempt in range(2): @@ -301,9 +321,10 @@ async def run(self, patch: Patch) -> CodeReviewToolResponse: raise LargeDiffError("The diff is too large") patch_summary = self.patch_summarizer.run(patch) + stack = await 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 ff4400e15c..4f72646f50 100644 --- a/bugbug/tools/code_review/langchain_tools.py +++ b/bugbug/tools/code_review/langchain_tools.py @@ -188,6 +188,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'. @@ -237,6 +240,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'. @@ -262,6 +268,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. @@ -295,6 +304,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'). @@ -333,6 +345,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'). @@ -367,6 +382,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'. @@ -411,6 +429,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). @@ -439,6 +460,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). @@ -468,6 +492,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. @@ -508,6 +535,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 75348f9ed0..4bc0bc7eb9 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 0000000000..5f7e4f9a57 --- /dev/null +++ b/bugbug/tools/code_review/stack.py @@ -0,0 +1,166 @@ +# -*- 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.""" + +import asyncio +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) + + +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, 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: + ancestors = await patch.get_stack_ancestors() + except Exception as error: + logger.warning("Could not load the ancestors of %s: %s", patch.patch_id, 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 = await patch.get_stack_descendants() + except Exception as error: + logger.warning( + "Could not load the descendants of %s: %s", patch.patch_id, error + ) + return [], f"The patches after this one could not be loaded ({error})." + + return [ + StackEntry(descendant.display_id, descendant.patch_title) + for descendant in descendants + ], None + + +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 b7a7461071..93949099e2 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,25 @@ def stack_base_patch(self) -> Patch: """Return the patch whose base precedes the entire stack.""" return self + 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 [] + + async def get_stack_descendants(self) -> Sequence[Patch]: + """Return the patches that build on this one, nearest first. + + Only their titles and identifiers are guaranteed to be loaded. + """ + 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 906d2fc2a5..7a285bde10 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,57 @@ 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}" + async def _load_comments(self) -> None: """Fetch the comments, and the users who wrote them, rendered by to_md().""" self._all_comments = [c for c in await self.get_comments() if c.is_renderable] diff --git a/services/mcp/src/bugbug_mcp/server.py b/services/mcp/src/bugbug_mcp/server.py index c61f495d3e..777c2d1b91 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 301c82d3f9..88892e7735 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 b936510318..da56ce2214 100644 --- a/tests/test_code_review.py +++ b/tests/test_code_review.py @@ -50,6 +50,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, @@ -75,7 +76,14 @@ 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], + get_stack_ancestors=AsyncMock(return_value=[]), + get_stack_descendants=AsyncMock(return_value=[]), + load_stack_file_changes=lambda ancestors: {}, + ) def make_patch_stack(*raw_diffs): @@ -300,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 # --------------------------------------------------------------------------- @@ -2331,8 +2421,12 @@ 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, + 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), ) @@ -2426,6 +2520,31 @@ 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 = 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." + 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 = asyncio.run(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")] ) @@ -2506,3 +2625,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 0000000000..b888a1a708 --- /dev/null +++ b/tests/test_code_review_stack.py @@ -0,0 +1,133 @@ +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 ( + 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" + + 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(): + ancestor_diff = make_diff("a.py") + patch = SimpleNamespace( + patch_id="3", + 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 = asyncio.run(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 = asyncio.run(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."