Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(review_hog): derive the bot login from GITHUB_APP_SLUG (#115378)

Julian Bez842d3440e2e6
diff --git a/posthog/settings/access.py b/posthog/settings/access.py
index 52cddbfbc3cc..4f0b9e9881af 100644
--- a/posthog/settings/access.py
+++ b/posthog/settings/access.py
@@ -150,12 +150,6 @@ TASKS_AGENT_PROXY_INTERNAL_URL: str | None = os.getenv("TASKS_AGENT_PROXY_INTERN
# agent-proxy in production; unset (local/CI) disables the check.
AGENT_PROXY_CALLBACK_SECRET: str | None = os.getenv("AGENT_PROXY_CALLBACK_SECRET") or None
-# The GitHub App's bot login (`<app slug>[bot]`) ReviewHog posts as. When set, the marker-based
-# idempotency scans only trust comments/reviews authored by this exact identity — otherwise any
-# installed bot could paste a public marker and suppress a publish (or get its comment PATCHed).
-# Unset trusts no author in production, and any Bot-typed author in local development and tests.
-REVIEWHOG_GITHUB_BOT_LOGIN: str = get_from_env("REVIEWHOG_GITHUB_BOT_LOGIN", "")
-
# These are legacy values only kept around for backwards compatibility with self hosted versions
SALT_KEY = get_list(os.getenv("SALT_KEY", "0123456789abcdefghijklmnopqrstuvwxyz"))
# We provide a default as it is needed for hobby deployments. Each entry must be exactly 32 bytes
diff --git a/products/review_hog/ARCHITECTURE.md b/products/review_hog/ARCHITECTURE.md
index 8f4192de141c..2bbf9e36b973 100644
--- a/products/review_hog/ARCHITECTURE.md
+++ b/products/review_hog/ARCHITECTURE.md
@@ -871,7 +871,8 @@ See [DECISIONS.md](./DECISIONS.md) for the "reuse the leaf, own the model" bound
- **One feature flag.** `review-hog` is the only ReviewHog flag. Automatic Flash reviews, the label trigger,
resolution, manual Flash, Inbox reviews, the Stamphog Inbox switch, and the tiered review arms are available
wherever it is on. DECISIONS.md records why the separate `review-hog-internal` gate went away.
-- **`REVIEWHOG_GITHUB_BOT_LOGIN`** (`posthog/settings/access.py`) names the app's `<slug>[bot]` login per region.
+- **`GITHUB_APP_SLUG`** (instance setting) names the app, and `posthog_app_login()` in
+ `products/review_hog/backend/app_identity.py` derives its `<slug>[bot]` login.
`is_app_bot_author` trusts only that login; unset, it trusts no author in production (local development and tests
fall back to any `Bot`-typed author).
diff --git a/products/review_hog/backend/app_identity.py b/products/review_hog/backend/app_identity.py
new file mode 100644
index 000000000000..e2d3ce3c6c8d
--- /dev/null
+++ b/products/review_hog/backend/app_identity.py
@@ -0,0 +1,11 @@
+from posthog.models.instance_setting import get_instance_setting
+
+
+def posthog_app_login() -> str | None:
+ """The lowercased login GitHub gives the PostHog GitHub App (`<slug>[bot]`), or None when no slug is set.
+
+ ReviewHog posts as this App, so it is also the only author whose markers and comments ReviewHog trusts.
+ Compare logins in lowercase, because GitHub treats them as case-insensitive.
+ """
+ slug = get_instance_setting("GITHUB_APP_SLUG")
+ return f"{slug}[bot]".lower() if slug else None
diff --git a/products/review_hog/backend/pr_owner.py b/products/review_hog/backend/pr_owner.py
index 3f361848973b..e07b2c36ceba 100644
--- a/products/review_hog/backend/pr_owner.py
+++ b/products/review_hog/backend/pr_owner.py
@@ -13,9 +13,9 @@ the Inbox link matches on it.
from typing import Literal
from posthog.dataclasses import frozen
-from posthog.models.instance_setting import get_instance_setting
from posthog.models.organization import OrganizationMembership
+from products.review_hog.backend.app_identity import posthog_app_login
from products.review_hog.backend.receivers import pick_reviewer, resolve_assigned_reviewers
PullRequestOwnerSource = Literal["author", "inbox_reviewer", "none"]
@@ -43,12 +43,6 @@ def is_active_member(*, team_id: int, user_id: int) -> bool:
).exists()
-def posthog_app_login() -> str | None:
- """The login GitHub gives the PostHog GitHub App, which opens self-driving pull requests."""
- slug = get_instance_setting("GITHUB_APP_SLUG")
- return f"{slug}[bot]".lower() if slug else None
-
-
class PullRequestOwnerResolver:
@staticmethod
def active_author_id(team_id: int, author_login: str) -> int | None:
diff --git a/products/review_hog/backend/reviewer/outcomes/classify.py b/products/review_hog/backend/reviewer/outcomes/classify.py
index 8f87e76469c8..d2077bed23cd 100644
--- a/products/review_hog/backend/reviewer/outcomes/classify.py
+++ b/products/review_hog/backend/reviewer/outcomes/classify.py
@@ -33,6 +33,7 @@ from posthog.sync import database_sync_to_async
from products.engineering_analytics.backend.facade.api import list_recently_merged_pull_requests
from products.engineering_analytics.backend.facade.contracts import GitHubSourceNotConnectedError
+from products.review_hog.backend.app_identity import posthog_app_login
from products.review_hog.backend.models import ReviewReport, ReviewReportArtefact, ReviewUserSettings
from products.review_hog.backend.reviewer.artefact_content import (
ArtefactContentValidationError,
@@ -455,6 +456,7 @@ async def classify_report(
inputs = await database_sync_to_async(_gather_report_inputs, thread_sensitive=False)(
team_id=team_id, report=report, final_head=final_head
)
+ app_login = await database_sync_to_async(posthog_app_login, thread_sensitive=False)()
compared_by_head = {head: parse_compare_files(files) for head, files in inputs.compares.items()}
outcomes: list[_ClassifiedOutcome] = []
@@ -482,6 +484,7 @@ async def classify_report(
comment=pf.comment,
review_comments=inputs.review_comments,
reactions=inputs.reactions_by_comment.get(pf.comment["id"], []),
+ app_login=app_login,
)
if pf.comment
else None
diff --git a/products/review_hog/backend/reviewer/outcomes/comment_signal.py b/products/review_hog/backend/reviewer/outcomes/comment_signal.py
index bd66c3d2e4a5..602e647a04ae 100644
--- a/products/review_hog/backend/reviewer/outcomes/comment_signal.py
+++ b/products/review_hog/backend/reviewer/outcomes/comment_signal.py
@@ -16,7 +16,7 @@ from products.review_hog.backend.reviewer.constants import (
REPORTED_LEVELS,
finding_heading,
)
-from products.review_hog.backend.reviewer.tools.github_client import is_app_bot_author
+from products.review_hog.backend.reviewer.tools.github_client import matches_app_bot
def _is_bot(user: dict[str, Any] | None) -> bool:
@@ -49,7 +49,11 @@ def find_finding_comment(
def engagement_method(
- *, comment: dict[str, Any], review_comments: list[dict[str, Any]], reactions: list[dict[str, Any]]
+ *,
+ comment: dict[str, Any],
+ review_comments: list[dict[str, Any]],
+ reactions: list[dict[str, Any]],
+ app_login: str | None,
) -> str | None:
"""How the finding's thread was engaged, or None if it wasn't. All results map to `reacted`.
@@ -62,8 +66,8 @@ def engagement_method(
ReviewHog's own replies are the exception and never count: it publishes the finding comment, so
treating its own follow-up as engagement would let the feature grade its own homework. A fix it
lands itself still shows up, as a commit in the post-review compare that the judge rules on —
- engagement is not where that belongs. Note `is_app_bot_author` can only single out our bot when
- `REVIEWHOG_GITHUB_BOT_LOGIN` is set. Unset, local runs fall back to "any bot", which ignores
+ engagement is not where that belongs. Note `matches_app_bot` can only single out our bot when
+ the `GITHUB_APP_SLUG` instance setting is set. Unset, local runs fall back to "any bot", which ignores
every bot reply, and production trusts no bot, which counts our own replies as agent replies.
A human reply beats an agent one when both are present, and a reaction beats both: it is the
@@ -72,7 +76,7 @@ def engagement_method(
thread it queues, so counting it would mark each of those findings ``reacted`` and keep the judge
from ruling on the fix that followed.
"""
- if any(not is_app_bot_author(reaction.get("user")) for reaction in reactions):
+ if any(not matches_app_bot(reaction.get("user"), app_login) for reaction in reactions):
return "comment_reaction"
comment_id = comment.get("id")
if comment_id is None:
@@ -80,6 +84,6 @@ def engagement_method(
replies = [rc for rc in review_comments if rc.get("in_reply_to_id") == comment_id]
if any(not _is_bot(rc.get("user")) for rc in replies):
return "comment_reply"
- if any(not is_app_bot_author(rc.get("user")) for rc in replies):
+ if any(not matches_app_bot(rc.get("user"), app_login) for rc in replies):
return "comment_reply_agent"
return None
diff --git a/products/review_hog/backend/reviewer/push_gate.py b/products/review_hog/backend/reviewer/push_gate.py
index acb45d13e837..0fee79038829 100644
--- a/products/review_hog/backend/reviewer/push_gate.py
+++ b/products/review_hog/backend/reviewer/push_gate.py
@@ -33,11 +33,8 @@ from posthog.egress.github.transport import GitHubRateLimitError
from posthog.llm.system_one import NoulAnswer, NoulQuestion, SystemOneNotConfigured, SystemOneRequestFailed
from posthog.llm.system_one_client import build_system_one_client
-from products.review_hog.backend.reviewer.tools.github_client import (
- GitHubAPIError,
- github_api_request,
- is_app_bot_author,
-)
+from products.review_hog.backend.app_identity import posthog_app_login
+from products.review_hog.backend.reviewer.tools.github_client import GitHubAPIError, github_api_request, matches_app_bot
from products.review_hog.backend.reviewer.tools.github_meta import GITHUB_COMPARE_FILES_CAP, PRParser
logger = logging.getLogger(__name__)
@@ -203,6 +200,17 @@ def _same_full_diff(previous: _PRDiff, current: _PRDiff) -> bool:
return previous_lines is not None and previous_lines == _own_lines(current.files)
+def _is_own_commit(commit: dict[str, Any], app_login: str | None) -> bool:
+ # Anyone can put the app's noreply email on a commit, so only a GitHub-verified commit with the
+ # app as both author and committer counts. Those are the commits the app creates through the API.
+ verified = bool(((commit.get("commit") or {}).get("verification") or {}).get("verified"))
+ return (
+ verified
+ and matches_app_bot(commit.get("author"), app_login)
+ and matches_app_bot(commit.get("committer"), app_login)
+ )
+
+
class PushGate:
def __init__(self, *, team_id: int, repository: str, token: str, installation_id: str | None) -> None:
self.team_id = team_id
@@ -234,6 +242,7 @@ class PushGate:
if comparison is None:
return None
commits: list[dict[str, Any]] = comparison.get("commits") or []
+ app_login = posthog_app_login()
files = _changed_files(comparison)
if comparison.get("total_commits", 0) > len(commits) or len(files) >= GITHUB_COMPARE_FILES_CAP:
return None
@@ -241,7 +250,7 @@ class PushGate:
commit_shas=[commit["sha"] for commit in commits],
merge_shas={commit["sha"] for commit in commits if len(commit.get("parents") or []) > 1},
files=files,
- reviewhog_shas={commit["sha"] for commit in commits if is_app_bot_author(commit.get("author"))},
+ reviewhog_shas={commit["sha"] for commit in commits if _is_own_commit(commit, app_login)},
)
def _commit_files(self, shas: list[str]) -> list[_ChangedFile] | None:
diff --git a/products/review_hog/backend/reviewer/tests/test_github_threads.py b/products/review_hog/backend/reviewer/tests/test_github_threads.py
index 428a5a3eb450..8932af2b380d 100644
--- a/products/review_hog/backend/reviewer/tests/test_github_threads.py
+++ b/products/review_hog/backend/reviewer/tests/test_github_threads.py
@@ -85,6 +85,7 @@ def _commit_payload(
}
class TestGitHubThreads:
@parameterized.expand(
[
diff --git a/products/review_hog/backend/reviewer/tests/test_issue_deduplicator.py b/products/review_hog/backend/reviewer/tests/test_issue_deduplicator.py
index 2272161f77f0..6ea3d97c6650 100644
--- a/products/review_hog/backend/reviewer/tests/test_issue_deduplicator.py
+++ b/products/review_hog/backend/reviewer/tests/test_issue_deduplicator.py
@@ -467,7 +467,7 @@ def test_already_raised_lists_each_other_reviewers_comment_once() -> None:
Duplicate(issue=_issue("1-5", "a.py", 5, 5), duplicate_of="3"),
]
- raised = already_raised(duplicates, comments)
+ raised = already_raised(duplicates, comments, None)
assert raised == [
AlreadyRaised(title="Issue 1-4", level="P1", comment_id=1, commenter="greptile-apps[bot]"),
diff --git a/products/review_hog/backend/reviewer/tests/test_outcome_comment_signal.py b/products/review_hog/backend/reviewer/tests/test_outcome_comment_signal.py
index 3e0e5bf987dd..0d8dc28a46e3 100644
--- a/products/review_hog/backend/reviewer/tests/test_outcome_comment_signal.py
+++ b/products/review_hog/backend/reviewer/tests/test_outcome_comment_signal.py
@@ -1,7 +1,5 @@
from typing import Any
-from django.test import override_settings
-
from parameterized import parameterized
from products.review_hog.backend.reviewer.artefact_content import ReviewIssueFinding
@@ -57,6 +55,7 @@ class TestFindFindingComment:
_OUR_BOT: dict[str, Any] = {"login": "reviewhog[bot]", "type": "Bot"}
_OTHER_BOT: dict[str, Any] = {"login": "greptile-apps[bot]", "type": "Bot"}
+_OUR_LOGIN = "reviewhog[bot]"
class TestEngagementMethod:
@@ -67,36 +66,42 @@ class TestEngagementMethod:
("our_own_queue_marker", _OUR_BOT, None),
]
)
- @override_settings(REVIEWHOG_GITHUB_BOT_LOGIN=_OUR_BOT["login"])
def test_a_reaction_counts_unless_it_is_ours(self, _name: str, user: dict[str, Any], expected: str | None):
comment: dict[str, Any] = {"id": 1}
reactions = [{"user": user, "content": "eyes"}]
- assert engagement_method(comment=comment, review_comments=[comment], reactions=reactions) == expected
+ assert (
+ engagement_method(comment=comment, review_comments=[comment], reactions=reactions, app_login=_OUR_LOGIN)
+ == expected
+ )
def test_reply_counts_as_engagement(self):
comment: dict[str, Any] = {"id": 1}
reply: dict[str, Any] = {"id": 2, "in_reply_to_id": 1, "user": {"login": "alice", "type": "User"}}
- assert engagement_method(comment=comment, review_comments=[comment, reply], reactions=[]) == "comment_reply"
+ assert (
+ engagement_method(comment=comment, review_comments=[comment, reply], reactions=[], app_login=None)
+ == "comment_reply"
+ )
- @override_settings(REVIEWHOG_GITHUB_BOT_LOGIN=_OUR_BOT["login"])
def test_our_own_reply_is_never_engagement(self):
# ReviewHog posts the finding comment itself, so counting its own follow-up would let the
# feature grade its own homework. A fix it lands is captured as a commit the judge rules on.
comment: dict[str, Any] = {"id": 1}
reply: dict[str, Any] = {"id": 2, "in_reply_to_id": 1, "user": _OUR_BOT}
- assert engagement_method(comment=comment, review_comments=[comment, reply], reactions=[]) is None
+ assert (
+ engagement_method(comment=comment, review_comments=[comment, reply], reactions=[], app_login=_OUR_LOGIN)
+ is None
+ )
- @override_settings(REVIEWHOG_GITHUB_BOT_LOGIN=_OUR_BOT["login"])
def test_another_agents_reply_is_engagement_tagged_as_agent(self):
# A reviewer's own bot answering on their behalf is a real response to the finding. Dropping
# it under-reports engagement, so the actor rides in the method instead of being filtered out.
comment: dict[str, Any] = {"id": 1}
reply: dict[str, Any] = {"id": 2, "in_reply_to_id": 1, "user": _OTHER_BOT}
assert (
- engagement_method(comment=comment, review_comments=[comment, reply], reactions=[]) == "comment_reply_agent"
+ engagement_method(comment=comment, review_comments=[comment, reply], reactions=[], app_login=_OUR_LOGIN)
+ == "comment_reply_agent"
)
- @override_settings(REVIEWHOG_GITHUB_BOT_LOGIN=_OUR_BOT["login"])
def test_human_reply_wins_over_an_agent_reply(self):
# Both are engagement, but "a human responded" has to stay answerable once agents do more of
# the replying, so the human actor takes the thread.
@@ -104,26 +109,31 @@ class TestEngagementMethod:
agent: dict[str, Any] = {"id": 2, "in_reply_to_id": 1, "user": _OTHER_BOT}
human: dict[str, Any] = {"id": 3, "in_reply_to_id": 1, "user": {"login": "alice", "type": "User"}}
assert (
- engagement_method(comment=comment, review_comments=[comment, agent, human], reactions=[]) == "comment_reply"
+ engagement_method(
+ comment=comment, review_comments=[comment, agent, human], reactions=[], app_login=_OUR_LOGIN
+ )
+ == "comment_reply"
)
def test_agent_replies_are_ignored_when_our_bot_login_is_unconfigured(self):
- # Outside production `is_app_bot_author` falls back to "any bot" without REVIEWHOG_GITHUB_BOT_LOGIN,
+ # Outside production `matches_app_bot` falls back to "any bot" without GITHUB_APP_SLUG,
# so a stranger's bot is never credited as engagement on a deployment that cannot tell it from
# ours — the signal degrades to the old ignore-every-bot behaviour rather than misattributing.
comment: dict[str, Any] = {"id": 1}
reply: dict[str, Any] = {"id": 2, "in_reply_to_id": 1, "user": _OTHER_BOT}
- assert engagement_method(comment=comment, review_comments=[comment, reply], reactions=[]) is None
+ assert (
+ engagement_method(comment=comment, review_comments=[comment, reply], reactions=[], app_login=None) is None
+ )
def test_reaction_wins_over_reply(self):
comment: dict[str, Any] = {"id": 1}
reply: dict[str, Any] = {"id": 2, "in_reply_to_id": 1}
reactions = [{"user": {"login": "alice", "type": "User"}, "content": "+1"}]
assert (
- engagement_method(comment=comment, review_comments=[comment, reply], reactions=reactions)
+ engagement_method(comment=comment, review_comments=[comment, reply], reactions=reactions, app_login=None)
== "comment_reaction"
)
def test_no_reaction_no_reply_is_none(self):
comment: dict[str, Any] = {"id": 1}
- assert engagement_method(comment=comment, review_comments=[comment], reactions=[]) is None
+ assert engagement_method(comment=comment, review_comments=[comment], reactions=[], app_login=None) is None
diff --git a/products/review_hog/backend/reviewer/tests/test_publish_review.py b/products/review_hog/backend/reviewer/tests/test_publish_review.py
index 50bea37cc834..9543e1022256 100644
--- a/products/review_hog/backend/reviewer/tests/test_publish_review.py
+++ b/products/review_hog/backend/reviewer/tests/test_publish_review.py
@@ -61,6 +61,7 @@ def _commit_probes(mock_request: MagicMock) -> list[str]:
@patch(_PAGINATED)
@patch(_REQUEST)
class TestPostGithubReview:
def test_uses_passed_token_and_pins_review_to_head_sha(
self, mock_request: MagicMock, mock_paginated: MagicMock
diff --git a/products/review_hog/backend/reviewer/tools/github_client.py b/products/review_hog/backend/reviewer/tools/github_client.py
index 4346de92a1c5..59c1c03d1639 100644
--- a/products/review_hog/backend/reviewer/tools/github_client.py
+++ b/products/review_hog/backend/reviewer/tools/github_client.py
@@ -22,31 +22,40 @@ from posthog.egress.github.transport import (
)
from posthog.egress.limiter.policies import Priority
+from products.review_hog.backend.app_identity import posthog_app_login
+
logger = logging.getLogger(__name__)
-def is_app_bot_author(user: dict[str, Any] | None) -> bool:
- """Whether a GitHub review/comment author is OUR app's bot identity.
+def matches_app_bot(user: dict[str, Any] | None, app_login: str | None) -> bool:
+ """Whether a GitHub review/comment author is OUR app's bot identity, given `posthog_app_login()`.
Guards the marker-based idempotency scans: on a public repo anyone can paste a marker, and a
spoofed match suppresses a publish or gets a stranger's comment PATCHed. `type == "Bot"` blocks
- human spoofers; when `REVIEWHOG_GITHUB_BOT_LOGIN` is configured (the app's `<slug>[bot]` login),
+ human spoofers; when the `GITHUB_APP_SLUG` instance setting is set (the app's `<slug>[bot]` login),
markers pasted by OTHER installed bots are rejected too. Unset, it fails closed in production,
because any installed bot would pass. Local development and tests fall back to the type check:
the app's own login isn't derivable from an installation token without extra API calls.
+
+ Async callers resolve `app_login` once through `database_sync_to_async` and pass it in, because
+ reading the instance setting can query the database, which Django refuses on an event loop.
"""
author = user or {}
if author.get("type") != "Bot":
return False
- expected = settings.REVIEWHOG_GITHUB_BOT_LOGIN
- if expected:
- return author.get("login") == expected
+ if app_login:
+ return str(author.get("login") or "").lower() == app_login
if settings.DEBUG or settings.TEST:
return True
- logger.warning("REVIEWHOG_GITHUB_BOT_LOGIN is not set; no GitHub author counts as the ReviewHog app")
+ logger.warning("GITHUB_APP_SLUG is not set; no GitHub author counts as the ReviewHog app")
return False
+def is_app_bot_author(user: dict[str, Any] | None) -> bool:
+ """`matches_app_bot` against the configured app login, for sync callers only."""
+ return matches_app_bot(user, posthog_app_login())
+
+
GITHUB_API_BASE = "https://api.github.com"
_SOURCE = "review_hog"
diff --git a/products/review_hog/backend/reviewer/tools/github_threads.py b/products/review_hog/backend/reviewer/tools/github_threads.py
index 715055243af1..ec4465a8281a 100644
--- a/products/review_hog/backend/reviewer/tools/github_threads.py
+++ b/products/review_hog/backend/reviewer/tools/github_threads.py
@@ -434,7 +434,7 @@ def inspect_fix_commit(
Fails closed on GitHub's 300-file cap: a files list that may be truncated reports the commit as
unverifiable rather than clean — a comment-driven fix that big deserves human eyes anyway.
Provenance: signed-commit fixes are authored as the app's bot (`is_app_bot_author`, which fails
- closed in production when `REVIEWHOG_GITHUB_BOT_LOGIN` is unset) and carry a verified web-flow signature; a
+ closed in production when `GITHUB_APP_SLUG` is unset) and carry a verified web-flow signature; a
reachable SHA failing either is not provably this run's fix. The residual — echoing one of the
bot's own earlier commits — stays with the recorded session-provenance follow-up.
"""
diff --git a/products/review_hog/backend/reviewer/tools/issue_deduplicator.py b/products/review_hog/backend/reviewer/tools/issue_deduplicator.py
index ba88836e1ece..324d3d8bb762 100644
--- a/products/review_hog/backend/reviewer/tools/issue_deduplicator.py
+++ b/products/review_hog/backend/reviewer/tools/issue_deduplicator.py
@@ -2,8 +2,6 @@ import json
import logging
from collections.abc import Collection, Sequence
-from django.conf import settings
-
from temporalio.exceptions import ApplicationError
from posthog.dataclasses import frozen
@@ -49,24 +47,26 @@ class AlreadyRaised:
commenter: str
-def _is_review_hog_finding(comment: PRComment) -> bool:
+def _is_review_hog_finding(comment: PRComment, app_login: str | None) -> bool:
"""ReviewHog's own finding comment. The marker is public, so it only counts on a bot's comment, and on
ReviewHog's own app when its login is configured; otherwise anyone could paste it to leave the list."""
- expected = settings.REVIEWHOG_GITHUB_BOT_LOGIN
- by_review_hog = comment.user == expected if expected else comment.user.endswith("[bot]")
+ by_review_hog = comment.user.lower() == app_login if app_login else comment.user.endswith("[bot]")
return by_review_hog and REVIEW_HOG_FINDING_MARKER in comment.body
-def already_raised(duplicates: Sequence[Duplicate], pr_comments: Sequence[PRComment]) -> list[AlreadyRaised]:
+def already_raised(
+ duplicates: Sequence[Duplicate], pr_comments: Sequence[PRComment], app_login: str | None
+) -> list[AlreadyRaised]:
"""The other reviewers' PR comments that a turn's findings repeat.
One entry per comment, at the most severe level any of its repeating findings gave it, because several
- perspectives often find the same problem.
+ perspectives often find the same problem. `app_login` is `posthog_app_login()`, which the async caller
+ resolves off the event loop.
"""
others = {
str(comment.id): comment
for comment in pr_comments
- if comment.id is not None and not _is_review_hog_finding(comment)
+ if comment.id is not None and not _is_review_hog_finding(comment, app_login)
}
by_comment: dict[int, AlreadyRaised] = {}
for duplicate in duplicates:
diff --git a/products/review_hog/backend/temporal/activities.py b/products/review_hog/backend/temporal/activities.py
index 3d438d65f525..5a9c8c33a08c 100644
--- a/products/review_hog/backend/temporal/activities.py
+++ b/products/review_hog/backend/temporal/activities.py
@@ -34,6 +34,7 @@ from posthog.sync import database_sync_to_async
from posthog.temporal.common.scoped import scoped_temporal
from posthog.temporal.common.utils import close_db_connections
+from products.review_hog.backend.app_identity import posthog_app_login
from products.review_hog.backend.automatic_reviews import automatic_flash_allowed, observe_dispatch
from products.review_hog.backend.models import ReviewProjectSettings, ReviewReport, ReviewUserSettings
from products.review_hog.backend.pr_owner import PullRequestOwnerResolver
@@ -1619,7 +1620,8 @@ async def dedup_activity(input: SandboxStageInput) -> DedupResult:
workflow_id_prefix=_sandbox_workflow_id_prefix("dedup"),
)
survivors = outcome.kept
- raised_elsewhere = already_raised(outcome.duplicates, pr_comments)
+ app_login = await database_sync_to_async(posthog_app_login, thread_sensitive=False)()
+ raised_elsewhere = already_raised(outcome.duplicates, pr_comments, app_login)
issue_ids = await database_sync_to_async(replace_deduplicated_findings, thread_sensitive=False)(
team_id=input.team_id,
report_id=input.report_id,
diff --git a/products/review_hog/backend/tests/test_outcome_classify.py b/products/review_hog/backend/tests/test_outcome_classify.py
index 6be2e2b97a93..469dc9b925c9 100644
--- a/products/review_hog/backend/tests/test_outcome_classify.py
+++ b/products/review_hog/backend/tests/test_outcome_classify.py
@@ -10,13 +10,13 @@ import pytest
from posthog.test.base import BaseTest
from unittest.mock import AsyncMock, patch
-from django.test import override_settings
from django.utils import timezone
from asgiref.sync import async_to_sync
from parameterized import parameterized
from temporalio.exceptions import ApplicationError
+from posthog.models.instance_setting import _clear_instance_setting_cache
from posthog.models.team import Team
from products.review_hog.backend.models import ReviewReport, ReviewReportArtefact
@@ -93,6 +93,11 @@ def _verdict(issue_key: str = _ISSUE_KEY) -> ValidationVerdict:
class TestClassifyReportDecision:
"""The precedence + emit logic, with the DB helpers mocked so no database or thread is involved."""
+ @pytest.fixture(autouse=True)
+ def _our_app_login(self):
+ with patch(f"{_CLASSIFY}.posthog_app_login", return_value="reviewhog[bot]"):
+ yield
+
def _inputs(
self,
*,
@@ -133,7 +138,6 @@ class TestClassifyReportDecision:
("only_our_queue_marker", {"login": "reviewhog[bot]", "type": "Bot"}, "addressed", "judge_confirmed"),
]
)
- @override_settings(REVIEWHOG_GITHUB_BOT_LOGIN="reviewhog[bot]")
def test_a_reaction_takes_precedence_unless_it_is_ours(
self, _name: str, reactor: dict[str, Any], outcome: str, method: str
):
@@ -513,6 +517,35 @@ class TestClassifyReportDecision:
assert props["final_head"] == "head_sha"
+def test_our_reaction_is_ignored_when_the_app_login_is_not_cached() -> None:
+ _clear_instance_setting_cache()
+ comment = {"id": 1, "path": "f.py", "body": "### Off-by-one\n\nbody", "reactions": {"total_count": 1}}
+ inputs = _ReportInputs(
+ compares={"base_sha": _FAR},
+ review_comments=[comment],
+ reactions_by_comment={1: [{"user": {"login": "reviewhog[bot]", "type": "Bot"}, "content": "eyes"}]},
+ published=[
+ _PublishedFinding(finding=_finding(), verdict=_verdict(), comment=comment, reviewed_head="base_sha")
+ ],
+ distinct_id="user-distinct",
+ judge_user_id=0,
+ )
+ captured: list[dict[str, Any]] = []
+ with (
+ patch(f"{_CLASSIFY}._gather_report_inputs", return_value=inputs),
+ patch(f"{_CLASSIFY}._persist_outcomes"),
+ patch(f"{_CLASSIFY}._mark_outcomes_emitted"),
+ ):
+ async_to_sync(classify_report)(
+ team_id=1,
+ report=ReviewReport(repository="o/r", pr_number=7),
+ final_head="head_sha",
+ capture=lambda **kw: captured.append(kw),
+ )
+ assert captured[0]["properties"]["outcome"] == "ignored"
+
+
class TestGatherAndIdempotency(BaseTest):
"""`_gather_report_inputs` and the artefact idempotency guard, against a real DB, synchronously."""
diff --git a/products/review_hog/backend/tests/test_publish_idempotency.py b/products/review_hog/backend/tests/test_publish_idempotency.py
index 5b517605636b..27e88299921b 100644
--- a/products/review_hog/backend/tests/test_publish_idempotency.py
+++ b/products/review_hog/backend/tests/test_publish_idempotency.py
@@ -14,6 +14,7 @@ from temporalio.exceptions import ApplicationError
from temporalio.testing import ActivityEnvironment
from posthog.egress.github.transport import GitHubRateLimitError
+from posthog.models.instance_setting import override_instance_config
from products.review_hog.backend.models import ReviewReport
from products.review_hog.backend.reviewer.constants import LEGACY_FLASH_MODE_MESSAGE_PREFIX
@@ -32,6 +33,8 @@ from products.review_hog.backend.temporal.activities import PublishInput, _publi
_PUBLISH = "products.review_hog.backend.reviewer.tools.publish_review.publish_review"
_SNAPSHOT = "products.review_hog.backend.reviewer.tools.publish_review.load_pr_snapshot"
_AUTH = "products.review_hog.backend.temporal.activities._installation_auth"
+pytestmark = pytest.mark.django_db
+
_PAGINATED = "products.review_hog.backend.reviewer.tools.publish_review.github_api_get_paginated"
_ACTIVITIES = "products.review_hog.backend.temporal.activities"
@@ -69,11 +72,11 @@ def test_review_already_posted_detects_our_own_markered_review() -> None:
)
assert _review_posted(marker, [{"body": f"no user field: {marker}"}]) is False
# With the app's bot login configured, another installed bot's pasted marker must not match either.
- with override_settings(REVIEWHOG_GITHUB_BOT_LOGIN="posthog[bot]"):
+ with override_instance_config("GITHUB_APP_SLUG", "posthog"):
assert _review_posted(marker, [{"body": marker, **bot}]) is True
assert _review_posted(marker, [{"body": marker, "user": {"login": "rogue[bot]", "type": "Bot"}}]) is False
# Unconfigured in production, no bot is trusted, because any installed bot could paste the marker.
- with override_settings(REVIEWHOG_GITHUB_BOT_LOGIN="", DEBUG=False, TEST=False):
+ with override_instance_config("GITHUB_APP_SLUG", ""), override_settings(DEBUG=False, TEST=False):
assert _review_posted(marker, [{"body": marker, **bot}]) is False
diff --git a/products/review_hog/backend/tests/test_push_gate.py b/products/review_hog/backend/tests/test_push_gate.py
index f72474924e11..826bd146f5ce 100644
--- a/products/review_hog/backend/tests/test_push_gate.py
+++ b/products/review_hog/backend/tests/test_push_gate.py
@@ -22,14 +22,27 @@ def _file(filename: str, patch: str | None = "@@ -1 +1 @@\n-a\n+b") -> dict[str,
_REVIEWHOG_BOT = {"login": "reviewhog[bot]", "type": "Bot"}
-def _commit(sha: str, *, merge: bool = False, author: dict[str, str] | None = None) -> dict[str, Any]:
+def _commit(
+ sha: str,
+ *,
+ merge: bool = False,
+ author: dict[str, str] | None = None,
+ committer: dict[str, str] | None = None,
+ verified: bool = False,
+) -> dict[str, Any]:
return {
"sha": sha,
"parents": [{"sha": "p1"}, {"sha": "p2"}] if merge else [{"sha": "p1"}],
"author": author or {"login": "octocat", "type": "User"},
+ "committer": committer or author or {"login": "octocat", "type": "User"},
+ "commit": {"verification": {"verified": verified}},
}
+def _own_commit(sha: str) -> dict[str, Any]:
+ return _commit(sha, author=_REVIEWHOG_BOT, committer=_REVIEWHOG_BOT, verified=True)
+
+
def _pr(commits: list[dict[str, Any]], files: list[dict[str, Any]]) -> dict[str, Any]:
return {"total_commits": len(commits), "commits": commits, "files": files}
@@ -61,6 +74,7 @@ def _decide(responses: dict[str, dict[str, Any] | None], system_one: MagicMock |
with (
patch(f"{_MODULE}.github_api_request", side_effect=_github(responses)),
patch(f"{_MODULE}.build_system_one_client", MagicMock(return_value=system_one or MagicMock())),
+ patch(f"{_MODULE}.posthog_app_login", return_value="reviewhog[bot]"),
):
return PushGate(team_id=1, repository="PostHog/posthog", token="t", installation_id="9").decide(
previous_head_sha="old", head_sha="new", base_branch="master"
@@ -110,7 +124,7 @@ _CODE_PUSH = _push(
(
"reviewhog_fix_commits",
_push(
- new_commits=[_commit("a"), _commit("c", author=_REVIEWHOG_BOT)],
+ new_commits=[_commit("a"), _own_commit("c")],
pr_files=[_file("posthog/billing.py", _BILLING_FIX)],
own_commit_files=[_file("posthog/billing.py", _BILLING_FIX)],
),
@@ -177,7 +191,7 @@ def test_push_gate_asks_system_one_about_own_code_commits(
def test_push_gate_reviews_a_push_that_mixes_reviewhog_and_author_commits() -> None:
push = _push(
- new_commits=[_commit("a"), _commit("r", author=_REVIEWHOG_BOT), _commit("c")],
+ new_commits=[_commit("a"), _own_commit("r"), _commit("c")],
pr_files=[_file("posthog/billing.py", _BILLING_FIX)],
own_commit_files=[_file("posthog/billing.py", _BILLING_FIX)],
)
@@ -185,6 +199,24 @@ def test_push_gate_reviews_a_push_that_mixes_reviewhog_and_author_commits() -> N
assert (decision.skip, decision.reason) == (False, "system_one_above_threshold")
+ [
+ ("unsigned", _commit("s", author=_REVIEWHOG_BOT)),
+ (
+ "signed_by_a_person",
+ _commit("s", author=_REVIEWHOG_BOT, committer={"login": "mallory", "type": "User"}, verified=True),
+ ),
+ ]
+)
+def test_push_gate_reviews_commits_that_only_claim_the_app_as_author(_name: str, spoofed: dict[str, Any]) -> None:
+ push = _push(
+ new_commits=[_commit("a"), spoofed],
+ pr_files=[_file("posthog/billing.py", _BILLING_FIX)],
+ )
+ decision = _decide({**push, "commits/s": {"files": [_file("posthog/billing.py", _BILLING_FIX)]}}, _system_one(0.99))
+ assert decision.reason != "reviewhog_commits_only"
+
+
@parameterized.expand(
[
("not_configured", SystemOneNotConfigured("no gateway")),
diff --git a/products/review_hog/backend/tests/test_review_activity.py b/products/review_hog/backend/tests/test_review_activity.py
index c849f1c73842..5fa086808b87 100644
--- a/products/review_hog/backend/tests/test_review_activity.py
+++ b/products/review_hog/backend/tests/test_review_activity.py
@@ -9,6 +9,8 @@ from unittest.mock import AsyncMock, MagicMock, patch
from temporalio.exceptions import ApplicationError
from temporalio.testing import ActivityEnvironment
+from posthog.models.instance_setting import _clear_instance_setting_cache
+
from products.review_hog.backend.reviewer.artefact_content import PRSnapshotArtefact
from products.review_hog.backend.reviewer.constants import (
CHUNKING_MODEL,
@@ -17,7 +19,9 @@ from products.review_hog.backend.reviewer.constants import (
CHUNKING_RUNTIME_ADAPTER,
DEFAULT_REVIEW_ARM,
FLASH_ARM,
+ REVIEW_HOG_FINDING_MARKER,
REVIEW_MODE_FLASH,
+ REVIEW_MODE_FULL,
ReviewArm,
review_arm_for_mode,
)
@@ -29,7 +33,8 @@ from products.review_hog.backend.reviewer.models.perspective_selection import (
)
from products.review_hog.backend.reviewer.models.single_agent_review import SingleAgentFinding, SingleAgentReview
from products.review_hog.backend.reviewer.models.split_pr_into_chunks import Chunk, ChunksList, FileInfo
-from products.review_hog.backend.reviewer.review_design import REVIEW_DESIGN_SINGLE_AGENT
+from products.review_hog.backend.reviewer.review_design import REVIEW_DESIGN_PIPELINE, REVIEW_DESIGN_SINGLE_AGENT
+from products.review_hog.backend.reviewer.tools.issue_deduplicator import AlreadyRaised, DedupOutcome, Duplicate
from products.review_hog.backend.reviewer.tools.select_perspectives import PerspectiveSelectionDTO
from products.review_hog.backend.temporal.activities import (
LensReviewInput,
@@ -38,6 +43,7 @@ from products.review_hog.backend.temporal.activities import (
SandboxStageInput,
SelectPerspectivesInput,
_current_pr_comments,
+ dedup_activity,
lens_review_activity,
review_chunk_activity,
select_perspectives_activity,
@@ -628,3 +634,38 @@ def test_full_dedup_reads_current_comments_without_outdated_ones(
comments = _current_pr_comments(SandboxStageInput(**_single_agent_stage()), snapshot)
assert [comment.id for comment in comments] == expected_ids
+
+
+async def test_full_dedup_lists_other_reviewers_comments_when_the_app_login_is_not_cached() -> None:
+ _clear_instance_setting_cache()
+ ours = PRComment(
+ id=1, path="a.py", line=1, body=REVIEW_HOG_FINDING_MARKER, diff_hunk="", user="reviewhog[bot]", created_at="c"
+ )
+ theirs = PRComment(id=2, path="a.py", line=1, body="x", diff_hunk="", user="alice", created_at="c")
+ outcome = DedupOutcome(
+ kept=[],
+ duplicates=[
+ Duplicate(issue=_wave_issue("Mine again"), duplicate_of="1"),
+ Duplicate(issue=_wave_issue("Already said"), duplicate_of="2"),
+ ],
+ )
+ with (
+ patch(f"{_MODULE}.ReviewActivityHeartbeater"),
+ patch(f"{_MODULE}.load_review_arm", return_value=DEFAULT_REVIEW_ARM),
+ patch(f"{_MODULE}._combine_and_clean", return_value=[]),
+ patch(f"{_MODULE}.load_pr_snapshot", return_value=_snapshot()),
+ patch(f"{_MODULE}.load_prior_findings_with_verdicts", return_value=[]),
+ patch(f"{_MODULE}._current_pr_comments", return_value=[ours, theirs]),
+ patch(f"{_MODULE}.deduplicate_issues", AsyncMock(return_value=outcome)),
+ patch(f"{_MODULE}.replace_deduplicated_findings", return_value=[]),
+ patch(f"{_MODULE}._refresh_status_comment", AsyncMock()),
+ ):
+ result = await ActivityEnvironment().run(
+ dedup_activity,
+ SandboxStageInput(
+ **_single_agent_stage(review_mode=REVIEW_MODE_FULL, review_design=REVIEW_DESIGN_PIPELINE)
+ ),
+ )
+
+ assert result.raised_elsewhere == [AlreadyRaised(title="Already said", level="P2", comment_id=2, commenter="alice")]