Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 26 additions & 5 deletions bugbug/tools/code_review/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand All @@ -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):
Expand Down Expand Up @@ -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:
Expand Down
30 changes: 30 additions & 0 deletions bugbug/tools/code_review/langchain_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'.
Expand Down Expand Up @@ -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'.

Expand All @@ -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.
Expand Down Expand 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').

Expand Down Expand Up @@ -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').

Expand Down Expand Up @@ -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'.
Expand Down Expand Up @@ -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).
Expand Down Expand Up @@ -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).
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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.

Expand Down
10 changes: 10 additions & 0 deletions bugbug/tools/code_review/prompts.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@
</examples>


{patch_stack}
Here is the patch you need to review:

<patch>
Expand All @@ -128,6 +129,15 @@
"""


TEMPLATE_PATCH_STACK = """Here is the stack of patches this patch belongs to:

<patch_stack>
{stack_context}
</patch_stack>

"""


TEMPLATE_COMMENT_EXAMPLE = """Patch example {example_number}:

{patch}
Expand Down
166 changes: 166 additions & 0 deletions bugbug/tools/code_review/stack.py
Original file line number Diff line number Diff line change
@@ -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)
Loading