-
-
Notifications
You must be signed in to change notification settings - Fork 4
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: Store Bot Comment Embeddings from Closed PRs #2100
Open
RulaKhaled
wants to merge
12
commits into
main
Choose a base branch
from
rola/ai-comments-improvements
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
0e4f7ba
create a new celery periodic job to fetch github reactions
RulaKhaled 1c031e8
feat: Update with ground work for or closed type
RulaKhaled 8d73fa2
Update with saving comments embeddings
RulaKhaled 011071a
rename the review_comments table in the db
RulaKhaled 10caf77
:hammer_and_wrench: apply pre-commit fixes
getsantry[bot] 2940acc
delete old code
RulaKhaled 5d309f6
remove unused imports
RulaKhaled 9239bee
fix some tests
RulaKhaled 4ec1636
:hammer_and_wrench: apply pre-commit fixes
getsantry[bot] 7803f69
fix types
RulaKhaled ffb173c
add tests to pr closed step
RulaKhaled 160e29d
:hammer_and_wrench: apply pre-commit fixes
getsantry[bot] File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,70 @@ | ||
"""Migration | ||
|
||
Revision ID: ee9136e6ff84 | ||
Revises: e0fcdc14251c | ||
Create Date: 2025-03-06 14:31:33.084873 | ||
|
||
""" | ||
|
||
import sqlalchemy as sa | ||
from alembic import op | ||
from pgvector.sqlalchemy import Vector # type: ignore | ||
from sqlalchemy.dialects import postgresql | ||
|
||
# revision identifiers, used by Alembic. | ||
revision = "ee9136e6ff84" | ||
down_revision = "e0fcdc14251c" | ||
branch_labels = None | ||
depends_on = None | ||
|
||
|
||
def upgrade(): | ||
# ### commands auto generated by Alembic - please adjust! ### | ||
op.create_table( | ||
"review_comments_embedding", | ||
sa.Column("id", sa.Integer(), nullable=False), | ||
sa.Column("provider", sa.String(), nullable=False), | ||
sa.Column("owner", sa.String(), nullable=False), | ||
sa.Column("repo", sa.String(), nullable=False), | ||
sa.Column("pr_id", sa.BigInteger(), nullable=False), | ||
sa.Column("body", sa.String(), nullable=False), | ||
sa.Column("is_good_pattern", sa.Boolean(), nullable=False), | ||
sa.Column("embedding", Vector(dim=768), nullable=False), | ||
sa.Column("comment_metadata", postgresql.JSONB(astext_type=sa.Text()), nullable=False), | ||
sa.Column("created_at", sa.DateTime(), nullable=False), | ||
sa.PrimaryKeyConstraint("id"), | ||
sa.UniqueConstraint("provider", "pr_id", "repo", "owner"), | ||
) | ||
with op.batch_alter_table("review_comments_embedding", schema=None) as batch_op: | ||
batch_op.create_index( | ||
"ix_review_comments_embedding_hnsw", | ||
["embedding"], | ||
unique=False, | ||
postgresql_using="hnsw", | ||
postgresql_with={"m": 16, "ef_construction": 200}, | ||
postgresql_ops={"embedding": "vector_cosine_ops"}, | ||
) | ||
batch_op.create_index( | ||
"ix_review_comments_is_good_pattern", ["is_good_pattern"], unique=False | ||
) | ||
batch_op.create_index( | ||
"ix_review_comments_repo_owner_pr", ["owner", "repo", "pr_id"], unique=False | ||
) | ||
|
||
# ### end Alembic commands ### | ||
|
||
|
||
def downgrade(): | ||
# ### commands auto generated by Alembic - please adjust! ### | ||
with op.batch_alter_table("review_comments_embedding", schema=None) as batch_op: | ||
batch_op.drop_index("ix_review_comments_repo_owner_pr") | ||
batch_op.drop_index("ix_review_comments_is_good_pattern") | ||
batch_op.drop_index( | ||
"ix_review_comments_embedding_hnsw", | ||
postgresql_using="hnsw", | ||
postgresql_with={"m": 16, "ef_construction": 200}, | ||
postgresql_ops={"embedding": "vector_cosine_ops"}, | ||
) | ||
|
||
op.drop_table("review_comments_embedding") | ||
# ### end Alembic commands ### |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,154 @@ | ||
from asyncio.log import logger | ||
from typing import Any | ||
|
||
from github.PullRequestComment import PullRequestComment | ||
from langfuse.decorators import observe | ||
from sentry_sdk.ai.monitoring import ai_track | ||
from sqlalchemy.dialects.postgresql import insert | ||
|
||
from celery_app.app import celery_app | ||
from seer.automation.agent.embeddings import GoogleProviderEmbeddings | ||
from seer.automation.autofix.config import ( | ||
AUTOFIX_EXECUTION_HARD_TIME_LIMIT_SECS, | ||
AUTOFIX_EXECUTION_SOFT_TIME_LIMIT_SECS, | ||
) | ||
from seer.automation.codebase.repo_client import RepoClientType | ||
from seer.automation.codegen.step import CodegenStep | ||
from seer.automation.models import RepoDefinition | ||
from seer.automation.pipeline import PipelineStepTaskRequest | ||
from seer.automation.state import DbStateRunTypes | ||
from seer.db import DbReviewCommentEmbedding, Session | ||
|
||
|
||
class PrClosedStepRequest(PipelineStepTaskRequest): | ||
pr_id: int | ||
repo_definition: RepoDefinition | ||
|
||
|
||
class CommentAnalyzer: | ||
""" | ||
Handles comment analysis logic | ||
""" | ||
|
||
def __init__(self, bot_username: str = "codecov-ai-reviewer[bot]"): | ||
self.bot_username = bot_username | ||
|
||
def is_bot_comment(self, comment: PullRequestComment) -> bool: | ||
"""Check if comment is authored by bot""" | ||
return comment.user.login == self.bot_username | ||
|
||
def analyze_reactions(self, comment: PullRequestComment) -> tuple[bool, bool]: | ||
""" | ||
Analyze reactions on a comment | ||
Returns: (is_good_pattern, is_bad_pattern) | ||
""" | ||
reactions = comment.get_reactions() | ||
upvotes = sum(1 for r in reactions if r.content == "+1") | ||
downvotes = sum(1 for r in reactions if r.content == "-1") | ||
|
||
is_good_pattern = upvotes >= downvotes | ||
is_bad_pattern = downvotes > upvotes | ||
return is_good_pattern, is_bad_pattern | ||
|
||
|
||
@celery_app.task( | ||
time_limit=AUTOFIX_EXECUTION_HARD_TIME_LIMIT_SECS, | ||
soft_time_limit=AUTOFIX_EXECUTION_SOFT_TIME_LIMIT_SECS, | ||
) | ||
def pr_closed_task(*args, request: dict[str, Any]): | ||
PrClosedStep(request, DbStateRunTypes.PR_CLOSED).invoke() | ||
|
||
|
||
class PrClosedStep(CodegenStep): | ||
""" | ||
This class represents the PR Closed step in the codegen pipeline. It is responsible for | ||
processing a closed or merged PR, including gathering and analyzing comment reactions. | ||
""" | ||
|
||
name = "PrClosedStep" | ||
max_retries = 2 | ||
|
||
@staticmethod | ||
def _instantiate_request(request: dict[str, Any]) -> PrClosedStepRequest: | ||
return PrClosedStepRequest.model_validate(request) | ||
|
||
@staticmethod | ||
def get_task(): | ||
return pr_closed_task | ||
|
||
def __init__(self, request: dict[str, Any], type: DbStateRunTypes): | ||
super().__init__(request, type) | ||
self.analyzer = CommentAnalyzer() | ||
|
||
def _process_comment(self, comment: PullRequestComment, pr): | ||
try: | ||
is_good_pattern, is_bad_pattern = self.analyzer.analyze_reactions(comment) | ||
|
||
logger.info( | ||
f"Processing bot comment id {comment.id} on PR {pr.url}: " | ||
f"good_pattern={is_good_pattern}, " | ||
f"bad_pattern={is_bad_pattern}" | ||
) | ||
|
||
model = GoogleProviderEmbeddings.model( | ||
"text-embedding-005", task_type="CODE_RETRIEVAL_QUERY" | ||
) | ||
# encode() expects list[str], returns 2D array | ||
embedding = model.encode([comment.body])[0] | ||
|
||
with Session() as session: | ||
insert_stmt = insert(DbReviewCommentEmbedding).values( | ||
provider="github", | ||
owner=pr.base.repo.owner.login, | ||
repo=pr.base.repo.name, | ||
pr_id=pr.number, | ||
body=comment.body, | ||
is_good_pattern=is_good_pattern, | ||
comment_metadata={ | ||
"url": comment.html_url, | ||
"comment_id": comment.id, | ||
"location": ( | ||
{"file_path": comment.path, "line_number": comment.position} | ||
if hasattr(comment, "path") | ||
else None | ||
), | ||
"timestamps": { | ||
"created_at": comment.created_at.isoformat(), | ||
"updated_at": comment.updated_at.isoformat(), | ||
}, | ||
}, | ||
embedding=embedding, | ||
) | ||
|
||
session.execute( | ||
insert_stmt.on_conflict_do_nothing( | ||
index_elements=["provider", "pr_id", "repo", "owner"] | ||
) | ||
) | ||
session.commit() | ||
|
||
except Exception as e: | ||
self.logger.error(f"Error processing comment {comment.id} on PR {pr.url}: {e}") | ||
raise | ||
|
||
@observe(name="Codegen - PR Closed") | ||
@ai_track(description="Codegen - PR Closed Step") | ||
def _invoke(self, **kwargs): | ||
self.logger.info("Executing Codegen - PR Closed Step") | ||
self.context.event_manager.mark_running() | ||
|
||
repo_client = self.context.get_repo_client(type=RepoClientType.CODECOV_PR_CLOSED) | ||
pr = repo_client.repo.get_pull(self.request.pr_id) | ||
|
||
try: | ||
review_comments = pr.get_review_comments() | ||
|
||
for comment in review_comments: | ||
if self.analyzer.is_bot_comment(comment): | ||
self._process_comment(comment, pr) | ||
|
||
self.context.event_manager.mark_completed() | ||
|
||
except Exception as e: | ||
self.logger.error(f"Error processing closed PR {pr.url}: {e}") | ||
raise |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think we can just use PR review credentials. That way we don't have to add additional env values