: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(devex): stop reviewhog fix commits on queued and stacked prs (#105310)
Julian Bezca37390f2c9e
diff --git a/posthog/github/README.md b/posthog/github/README.mdindex 8aa43f7ffa3e..541a57f2c850 100644--- a/posthog/github/README.md+++ b/posthog/github/README.md@@ -8,6 +8,7 @@ Both may import this package.- `attribution.py` resolves a GitHub login to an organization member, under a bounded statement timeout, so a slow lookup degrades to no attribution.- `pull_request_events.py` emits the canonical `pr_created`, `pr_closed`, `pr_merged` and `pr_reviewed` analytics events.- `metrics.py` holds the Prometheus counters for dropped events and attribution outcomes.+- `merge_queue.py` reads the Trunk merge queue state off the comment Trunk keeps on each pull request. A bot that pushes to pull request branches checks it first, because a push removes a queued pull request from the queue. `GitHubIntegration.get_pull_request_merge_queue_state` does the read.## PR analyticsdiff --git a/posthog/github/merge_queue.py b/posthog/github/merge_queue.pynew file mode 100644index 000000000000..c2153e390aa7--- /dev/null+++ b/posthog/github/merge_queue.py@@ -0,0 +1,143 @@+"""Read a pull request's Trunk merge queue state from the comment Trunk keeps on it.++Trunk publishes no check run. It posts one comment per pull request and edits that comment in place+through the whole lifecycle, so the comment is the only record of the queue state on GitHub.+Trunk's `trunk-*` status labels are not a substitute: Trunk applies them only sometimes, and merged+pull requests keep stale ones.+"""++import re+from collections.abc import Iterable, Mapping+from enum import StrEnum+from typing import Any++_TRUNK_LOGIN = "trunk-io[bot]"+_QUEUE_COMMENT_MARKER = "<!-- Trunk Merge -->"+_TEST_ANALYTICS_MARKER = "<!-- Trunk Test Analytics -->"+_CHECKBOX_START = "<!-- Start PR Submit Checkbox -->"+_CHECKBOX_END = "<!-- End PR Submit Checkbox -->"+# The path segment matters: Trunk's flaky-test comment on the same pull request links to+# `/flaky-tests/` and is full of the word "failed".+_QUEUE_LINK_HOST = "app.trunk.io"+_QUEUE_LINK_PATH = "/merge-queue/"+++class MergeQueueState(StrEnum):+ NOT_SUBMITTED = "not_submitted"+ # Trunk has the submission but waits for branch protection before it adds the pull request.+ NOT_READY = "not_ready"+ QUEUED = "queued"+ TESTING = "testing"+ PASSED = "passed"+ # A required check failed in the batch, but Trunk still has the pull request and waits for the+ # pull requests ahead of it, because one of them can be the real cause.+ PENDING_FAILURE = "pending_failure"+ FAILED = "failed"+ EJECTED = "ejected"+ CANCELLED = "cancelled"+ REJECTED = "rejected"+ MERGED = "merged"+ # Trunk's comment exists but its wording matches no known state. It counts as holding, because+ # a push into an unknown state can eject the pull request.+ UNKNOWN = "unknown"++ @property+ def holds_pull_request(self) -> bool:+ """Trunk has the pull request. A person submitted it, so it ships as it is."""+ return self in _HOLDING_STATES++ @property+ def push_would_eject(self) -> bool:+ """A push removes the pull request from the queue and resets every pull request testing behind it.++ `NOT_READY` is not here. Nothing tests the pull request yet, and Trunk waits for exactly the+ branch protection that a fix push can satisfy.+ """+ return self in _PUSH_EJECTS_STATES++ @classmethod+ def from_comments(cls, comments: Iterable[Mapping[str, Any]]) -> "MergeQueueState | None":+ """The state in the last Trunk queue comment, or None when Trunk does not manage the pull request.++ Takes GitHub REST issue comments. The last queue comment decides, because a recreated comment+ replaces the older one, and an older comment's state is stale.+ """+ last_body: str | None = None+ for comment in comments:+ body = comment.get("body")+ if isinstance(body, str) and _is_queue_comment(body, comment.get("user")):+ last_body = body+ return None if last_body is None else cls._from_body(last_body)++ @classmethod+ def _from_body(cls, body: str) -> "MergeQueueState":+ for pattern, state in _STATUS_PATTERNS:+ if pattern.search(body):+ return state+ # No status sentence means the comment is still the submit instruction, so the checkbox+ # is the whole answer.+ start = body.find(_CHECKBOX_START)+ if start == -1:+ return cls.UNKNOWN+ end = body.find(_CHECKBOX_END, start)+ checkbox = body[start + len(_CHECKBOX_START) : end if end != -1 else None]+ if re.search(r"\[x\]", checkbox, re.IGNORECASE):+ return cls.QUEUED+ if re.search(r"\[\s*\]", checkbox):+ return cls.NOT_SUBMITTED+ return cls.UNKNOWN+++_HOLDING_STATES = frozenset(+ {+ MergeQueueState.NOT_READY,+ MergeQueueState.QUEUED,+ MergeQueueState.TESTING,+ MergeQueueState.PASSED,+ MergeQueueState.PENDING_FAILURE,+ MergeQueueState.UNKNOWN,+ }+)+_PUSH_EJECTS_STATES = _HOLDING_STATES - {MergeQueueState.NOT_READY}++# Trunk's status sentences, most decisive first. The order matters. Every removal shares the+# "removed from the merge queue" prefix, so each known reason must match before the bare prefix.+# Several states where Trunk still has the pull request mention a failure, so they must match+# before the bare failure sentence.+_STATUS_PATTERNS: tuple[tuple[re.Pattern[str], MergeQueueState], ...] = tuple(+ (re.compile(pattern, re.IGNORECASE), state)+ for pattern, state in (+ (r"merged successfully", MergeQueueState.MERGED),+ (r"was merged into .* as part of stacked pr", MergeQueueState.MERGED),+ (r"removed from the merge queue because it failed tests", MergeQueueState.FAILED),+ (r"waiting to become mergeable for too long", MergeQueueState.EJECTED),+ (r"removed from the merge queue because it was pushed to", MergeQueueState.EJECTED),+ (r"removed from the merge queue", MergeQueueState.CANCELLED),+ (r"could not start testing", MergeQueueState.FAILED),+ (r"waiting for other pull requests to finish testing", MergeQueueState.PENDING_FAILURE),+ (r"will be merged soon", MergeQueueState.PASSED),+ (r"will re-enter the queue|re-entering the merge queue", MergeQueueState.QUEUED),+ (r"running tests on this (pull request|stack)", MergeQueueState.TESTING),+ (r"waiting to start tests|waiting for tests to start", MergeQueueState.QUEUED),+ (r"is queued for merge as part of", MergeQueueState.QUEUED),+ (r"has failed|failed tests", MergeQueueState.FAILED),+ (r"submitted to merge", MergeQueueState.NOT_READY),+ # Trunk appends this to the instruction when GitHub sees the pull request as part of a+ # stack, so it must match before the checkbox, which stays ticked while nothing happens.+ (r"unable to merge this pr", MergeQueueState.REJECTED),+ )+)+++def _is_queue_comment(body: str, user: object) -> bool:+ # Anyone can comment on a public pull request, so a lookalike account that posts Trunk's+ # wording must not change the state a bot pushes on.+ if not isinstance(user, Mapping) or user.get("login") != _TRUNK_LOGIN or user.get("type") != "Bot":+ return False+ if _TEST_ANALYTICS_MARKER in body:+ return False+ return (+ _QUEUE_COMMENT_MARKER in body+ or _CHECKBOX_START in body+ or (_QUEUE_LINK_HOST in body and _QUEUE_LINK_PATH in body)+ )diff --git a/posthog/github/test/test_merge_queue.py b/posthog/github/test/test_merge_queue.pynew file mode 100644index 000000000000..3d9dfead6ce0--- /dev/null+++ b/posthog/github/test/test_merge_queue.py@@ -0,0 +1,123 @@+from typing import Any++from django.test import SimpleTestCase++from parameterized import parameterized++from posthog.github.merge_queue import MergeQueueState++TRUNK = {"login": "trunk-io[bot]", "type": "Bot"}+LINK = "https://app.trunk.io/example-org/merge-queue/repo-id/4242"+++def trunk_comment(body: str) -> dict[str, Any]:+ return {"user": TRUNK, "body": body}+++class TestMergeQueueState(SimpleTestCase):+ @parameterized.expand(+ [+ (+ "pushed_to",+ f"🚫 This pull request was removed from the merge queue because it was pushed to by @someone. [details]({LINK})",+ MergeQueueState.EJECTED,+ ),+ (+ "failed_tests",+ f"❌ This pull request was removed from the merge queue because it failed tests. [details]({LINK})",+ MergeQueueState.FAILED,+ ),+ (+ "other_removal",+ f"🚫 This pull request was removed from the merge queue. [details]({LINK})",+ MergeQueueState.CANCELLED,+ ),+ (+ "pending_failure",+ f"⚠️ The required check `Backend CI` (Failure) has failed. Pull request failed tests and is waiting for other pull requests to finish testing. [details]({LINK})",+ MergeQueueState.PENDING_FAILURE,+ ),+ (+ "testing",+ f"🧪 Running tests on this pull request (testing on PR #4300). [details]({LINK})",+ MergeQueueState.TESTING,+ ),+ (+ "waiting",+ f"⏳ Waiting to start tests on this pull request because a pull request (#4299) ahead of it failed tests. [details]({LINK})",+ MergeQueueState.QUEUED,+ ),+ (+ "submitted",+ f"✨ Submitted to Merge by @someone. It will be added to the merge queue once all branch protection rules pass. [details]({LINK})",+ MergeQueueState.NOT_READY,+ ),+ ("merged", f"😎 Merged successfully - [details]({LINK})", MergeQueueState.MERGED),+ (+ "instruction_unticked",+ "<!-- Trunk Merge -->\n<!-- Start PR Submit Checkbox -->\n- [ ] <!-- End PR Submit Checkbox -->To merge this pull request, check the box or comment `/trunk merge` below.",+ MergeQueueState.NOT_SUBMITTED,+ ),+ (+ "instruction_ticked",+ "<!-- Trunk Merge -->\n<!-- Start PR Submit Checkbox -->\n- [x] <!-- End PR Submit Checkbox -->To merge this pull request, check the box or comment `/trunk merge` below.",+ MergeQueueState.QUEUED,+ ),+ ]+ )+ def test_reads_state_from_trunk_comment(self, _name: str, body: str, expected: MergeQueueState) -> None:+ assert MergeQueueState.from_comments([trunk_comment(body)]) == expected++ @parameterized.expand(+ [+ (+ "flaky_test_report",+ [+ trunk_comment(+ "<!-- Trunk Test Analytics -->\n2 failed tests. https://app.trunk.io/example-org/flaky-tests/pr/4242"+ )+ ],+ ),+ (+ "person_quoting_trunk",+ [{"user": {"login": "someone"}, "body": f"Running tests on this pull request, see {LINK}"}],+ ),+ ("no_trunk_comment", [{"user": {"login": "someone"}, "body": "LGTM"}]),+ (+ "lookalike_account",+ [{"user": {"login": "trunk-io-fan", "type": "User"}, "body": f"😎 Merged successfully - {LINK}"}],+ ),+ ("missing_user", [{"body": f"😎 Merged successfully - {LINK}"}]),+ ]+ )+ def test_ignores_comments_that_are_not_the_queue_comment(self, _name: str, comments: list[dict[str, Any]]) -> None:+ assert MergeQueueState.from_comments(comments) is None++ def test_unrecognized_latest_comment_fails_closed(self) -> None:+ comments = [+ trunk_comment(f"🧪 Running tests on this pull request. [details]({LINK})"),+ trunk_comment(f"🆕 A wording this reader has never seen. [details]({LINK})"),+ ]+ state = MergeQueueState.from_comments(comments)+ assert state == MergeQueueState.UNKNOWN+ assert state.holds_pull_request and state.push_would_eject++ def test_last_trunk_comment_wins(self) -> None:+ comments = [+ trunk_comment(f"😎 Merged successfully - [details]({LINK})"),+ trunk_comment(f"🧪 Running tests on this pull request. [details]({LINK})"),+ ]+ assert MergeQueueState.from_comments(comments) == MergeQueueState.TESTING++ @parameterized.expand(+ [+ (MergeQueueState.NOT_READY, True, False),+ (MergeQueueState.QUEUED, True, True),+ (MergeQueueState.PENDING_FAILURE, True, True),+ (MergeQueueState.EJECTED, False, False),+ (MergeQueueState.MERGED, False, False),+ ]+ )+ def test_push_guards(self, state: MergeQueueState, holds: bool, push_ejects: bool) -> None:+ assert state.holds_pull_request is holds+ assert state.push_would_eject is push_ejectsdiff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.pyindex dc9868d2b4e1..43c128dc4297 100644--- a/posthog/models/github_integration_base.py+++ b/posthog/models/github_integration_base.py@@ -5,6 +5,7 @@ operations that are shared between :class:`GitHubIntegration` (team-scoped) and:class:`UserGitHubIntegration` (user-scoped)."""+import reimport jsonimport timeimport uuid@@ -29,6 +30,7 @@ from posthog.dataclasses import frozenfrom posthog.egress.github.limiter import remember_observed_core_limitfrom posthog.egress.github.transport import GitHubRateLimitError, github_request, raise_if_github_rate_limitedfrom posthog.egress.limiter.policies import Priority+from posthog.github.merge_queue import MergeQueueStatefrom posthog.sync import database_sync_to_async_poolfrom posthog.utils import safe_cache_add, safe_cache_delete@@ -142,6 +144,16 @@ class PullRequestRef:return f"{self.owner}/{self.repo}"+# `owner/repo`, single slash, no traversal. Used to keep repo/ref/sha values out of GitHub API URL+# paths where a crafted value (e.g. `../../other-repo/contents/x?ref=y`) could redirect the+# authenticated request to a different endpoint.+_GITHUB_REPO_PATH_RE = re.compile(r"^[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$")+++def _is_safe_github_repo_path(repo_path: str) -> bool:+ return ".." not in repo_path and bool(_GITHUB_REPO_PATH_RE.fullmatch(repo_path))++class GitHubIntegrationError(Exception):"""A GitHub API call failed for a non-rate-limit reason (bad response, auth failure, networkerror after retry). Rate limits raise ``GitHubRateLimitError`` from ``posthog.egress.github``@@ -1631,14 +1643,17 @@ class GitHubIntegrationBase:"reactions": [],}- def has_pull_request_comment(self, repository: str, pr_number: int, marker: str) -> bool | None:- """Return None when an incomplete read cannot prove the marker is absent."""+ def _get_issue_comment_pages(self, repository: str, pr_number: int) -> tuple[list[requests.Response], bool]:repo_path = repository if "/" in repository else f"{self.organization()}/{repository}"- responses, complete = self._installation_authenticated_get_pages(+ return self._installation_authenticated_get_pages(f"https://api.github.com/repos/{repo_path}/issues/{pr_number}/comments",endpoint="/repos/{owner}/{repo}/issues/{issue_number}/comments",params={"per_page": 100},)++ def has_pull_request_comment(self, repository: str, pr_number: int, marker: str) -> bool | None:+ """Return None when an incomplete read cannot prove the marker is absent."""+ responses, complete = self._get_issue_comment_pages(repository, pr_number)for response in responses:if response.status_code != 200:return None@@ -1655,6 +1670,30 @@ class GitHubIntegrationBase:return Truereturn False if complete else None+ def get_pull_request_merge_queue_state(self, repository: str, pr_number: int) -> MergeQueueState | None:+ """Read the Trunk merge queue state off the pull request's comments; None when Trunk does not manage it.++ Raises GitHubIntegrationError on an incomplete read, because a missed Trunk comment reads as+ "not in the queue" and lets a caller push into it.+ """+ if not _is_safe_github_repo_path(repository):+ raise GitHubIntegrationError(f"Unsafe repository path: {repository!r}")+ responses, complete = self._get_issue_comment_pages(repository, pr_number)+ comments: list[Mapping[str, Any]] = []+ for response in responses:+ try:+ page = response.json() if response.status_code == 200 else None+ except ValueError:+ page = None+ if not isinstance(page, list):+ raise GitHubIntegrationError(+ f"Could not read the comments of {repository}#{pr_number}", status_code=response.status_code+ )+ comments.extend(comment for comment in page if isinstance(comment, dict))+ if not complete:+ raise GitHubIntegrationError(f"Could not read every comment of {repository}#{pr_number}")+ return MergeQueueState.from_comments(comments)+def get_pull_request_comments(self, repository: str, pr_number: int) -> dict[str, Any]:"""Fetch a PR's conversation comments and inline review comments, merged chronologically.@@ -1767,6 +1806,37 @@ class GitHubIntegrationBase:return []return [pr["html_url"] for pr in pulls if isinstance(pr, dict) and isinstance(pr.get("html_url"), str)]+ def has_open_pull_request_with_base(self, repository: str, branch: str) -> bool:+ """Whether an open pull request from the same repository uses ``branch`` as its base, which means pull requests are stacked on it.++ Fork pull requests do not count, because anyone can open one against any branch.+ Raises GitHubIntegrationError on a failed read, because a missed stacked pull request lets a+ caller commit under it.+ """+ if not _is_safe_github_repo_path(repository):+ raise GitHubIntegrationError(f"Unsafe repository path: {repository!r}")+ responses, complete = self._installation_authenticated_get_pages(+ f"https://api.github.com/repos/{repository}/pulls",+ endpoint="/repos/{owner}/{repo}/pulls",+ params={"base": branch, "state": "open", "per_page": 100},+ )+ for response in responses:+ try:+ pulls = response.json() if response.status_code == 200 else None+ except ValueError:+ pulls = None+ if not isinstance(pulls, list):+ raise GitHubIntegrationError(+ f"Could not list the pull requests based on {repository}:{branch}", status_code=response.status_code+ )+ for pull in pulls:+ head_repo = ((pull.get("head") or {}).get("repo") or {}) if isinstance(pull, dict) else {}+ if str(head_repo.get("full_name", "")).lower() == repository.lower():+ return True+ if not complete:+ raise GitHubIntegrationError(f"Could not list every pull request based on {repository}:{branch}")+ return False+def get_open_pull_request_for_head(self, repository: str, branch: str) -> dict[str, Any] | None:"""Return the OPEN pull request whose head is ``branch`` — its number, HTML url, and base ref.diff --git a/posthog/models/integration/github.py b/posthog/models/integration/github.pyindex a32402172bc6..b189647e9eed 100644--- a/posthog/models/integration/github.py+++ b/posthog/models/integration/github.py@@ -15,7 +15,11 @@ import structlogfrom posthog.egress.github.transport import github_requestfrom posthog.egress.limiter.policies import Priority-from posthog.models.github_integration_base import GitHubIntegrationBase, GitHubIntegrationError+from posthog.models.github_integration_base import (+ GitHubIntegrationBase,+ GitHubIntegrationError,+ _is_safe_github_repo_path,+)from posthog.models.user import Userfrom posthog.plugins.plugin_server_api import reload_integrations_on_workersfrom posthog.sync import database_sync_to_async@@ -25,11 +29,6 @@ from . import common, model, refresh_trackinglogger = structlog.get_logger(__name__)-# `owner/repo`, single slash, no traversal. Used to keep repo/ref/sha values out of GitHub API URL-# paths where a crafted value (e.g. `../../other-repo/contents/x?ref=y`) could redirect the-# authenticated request to a different endpoint.-_GITHUB_REPO_PATH_RE = re.compile(r"^[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$")-_GITHUB_REF_RE = re.compile(r"^[A-Za-z0-9._\-/]+$")_GITHUB_COMMIT_SHA_RE = re.compile(r"^[0-9a-fA-F]{7,40}$")@@ -44,10 +43,6 @@ _MAX_DIFF_CHARS = 1_000_000_MAX_FILE_CONTENTS_BYTES = 10 * 1024 * 1024-def _is_safe_github_repo_path(repo_path: str) -> bool:- return ".." not in repo_path and bool(_GITHUB_REPO_PATH_RE.fullmatch(repo_path))--def _is_safe_github_ref(ref: str) -> bool:"""A git ref safe to interpolate into a GitHub API URL path (no traversal / URL-control chars)."""return (diff --git a/posthog/models/test/integration/test_github.py b/posthog/models/test/integration/test_github.pyindex 1c96c6d269dc..0b2515ffda11 100644--- a/posthog/models/test/integration/test_github.py+++ b/posthog/models/test/integration/test_github.py@@ -25,6 +25,7 @@ from posthog.egress.github.transport import (raise_if_github_rate_limited,)from posthog.egress.limiter.policies import Priority+from posthog.github.merge_queue import MergeQueueStatefrom posthog.models.github_integration_base import (GITHUB_BRANCH_CACHE_TTL_SECONDS,GITHUB_REPOSITORY_CACHE_TTL_SECONDS,@@ -123,6 +124,72 @@ class TestPullRequestCommentMarker(SimpleTestCase):with patch.object(github, "_installation_authenticated_get_pages", return_value=([response], complete)):assert github.has_pull_request_comment("example/repo", 1, "<!-- replacement -->") is expected+ @parameterized.expand(+ [+ ("incomplete", 200, [], False),+ ("error_status", 502, {"message": "Bad gateway"}, True),+ ("malformed", 200, {"error": "unavailable"}, True),+ ]+ )+ def test_merge_queue_state_refuses_a_partial_read(self, _name, status_code, body, complete) -> None:+ github = GitHubIntegration(Integration(kind="github", config={}, sensitive_config={}))+ response = MagicMock(status_code=status_code)+ response.json.return_value = body+ with patch.object(github, "_installation_authenticated_get_pages", return_value=([response], complete)):+ with pytest.raises(GitHubIntegrationError):+ github.get_pull_request_merge_queue_state("example/repo", 1)++ @parameterized.expand(+ [+ ("stacked", 200, [{"head": {"repo": {"full_name": "Example/Repo"}}}], True),+ ("not_stacked", 200, [], False),+ ("fork_only", 200, [{"head": {"repo": {"full_name": "someone/repo"}}}], False),+ ("fork_only_page_then_incomplete", 200, [{"head": {"repo": {"full_name": "someone/repo"}}}], "partial"),+ ("error_status", 502, {"message": "Bad gateway"}, None),+ ]+ )+ def test_stacked_pull_request_read_never_guesses(self, _name, status_code, body, expected) -> None:+ github = GitHubIntegration(Integration(kind="github", config={}, sensitive_config={}))+ response = MagicMock(status_code=status_code)+ response.json.return_value = body+ complete = expected != "partial"+ with patch.object(github, "_installation_authenticated_get_pages", return_value=([response], complete)):+ if expected in (None, "partial"):+ with pytest.raises(GitHubIntegrationError):+ github.has_open_pull_request_with_base("example/repo", "feature")+ else:+ assert github.has_open_pull_request_with_base("example/repo", "feature") is expected++ @parameterized.expand(+ [+ ("merge_queue_state", lambda github: github.get_pull_request_merge_queue_state("../victim/repo", 1)),+ ("stacked_read", lambda github: github.has_open_pull_request_with_base("..%2Fvictim/repo", "feature")),+ ]+ )+ def test_unsafe_repository_never_reaches_github(self, _name, read) -> None:+ github = GitHubIntegration(Integration(kind="github", config={}, sensitive_config={}))+ with (+ patch.object(github, "_installation_authenticated_get") as single,+ patch.object(github, "_installation_authenticated_get_pages") as pages,+ ):+ with pytest.raises(GitHubIntegrationError):+ read(github)+ single.assert_not_called()+ pages.assert_not_called()++ def test_merge_queue_state_reads_the_trunk_comment(self) -> None:+ github = GitHubIntegration(Integration(kind="github", config={}, sensitive_config={}))+ response = MagicMock(status_code=200)+ response.json.return_value = [+ {"user": {"login": "someone"}, "body": "LGTM"},+ {+ "user": {"login": "trunk-io[bot]", "type": "Bot"},+ "body": "🧪 Running tests on this pull request. https://app.trunk.io/example-org/merge-queue/x/1",+ },+ ]+ with patch.object(github, "_installation_authenticated_get_pages", return_value=([response], True)):+ assert github.get_pull_request_merge_queue_state("example/repo", 1) == MergeQueueState.TESTING+class TestGitHubIntegrationModel(BaseTest):def setUp(self):diff --git a/products/review_hog/backend/reviewer/models/thread_resolution.py b/products/review_hog/backend/reviewer/models/thread_resolution.pyindex bc8f49572a71..332aa5f0854a 100644--- a/products/review_hog/backend/reviewer/models/thread_resolution.py+++ b/products/review_hog/backend/reviewer/models/thread_resolution.py@@ -1,4 +1,4 @@-from enum import Enum+from enum import Enum, StrEnumfrom pydantic import BaseModel, Field, field_validator, model_validator@@ -13,6 +13,17 @@ class ThreadOutcome(str, Enum):ESCALATE = "escalate"+class CommitHold(StrEnum):+ """Why the stage must not commit to the PR branch. The threads stay open for a person."""++ # Trunk removes a queued PR on any push and resets every PR testing behind it. A person+ # submitted the PR, so it ships as it is.+ MERGE_QUEUE = "pr_in_merge_queue"+ # The stage commits to the head branch only, so a fix here leaves every PR stacked on top+ # behind its base until someone restacks.+ STACKED = "pr_has_stacked_pull_requests"++class ThreadResolution(BaseModel):"""One resolution turn's validated output: the verdict on a single review thread.diff --git a/products/review_hog/backend/reviewer/status_comment.py b/products/review_hog/backend/reviewer/status_comment.pyindex f9c6002e1ee0..a4c277c0447c 100644--- a/products/review_hog/backend/reviewer/status_comment.py+++ b/products/review_hog/backend/reviewer/status_comment.py@@ -37,6 +37,7 @@ from products.review_hog.backend.reviewer.constants import (published_priorities_for,)from products.review_hog.backend.reviewer.models.issues_review import IssuePriority+from products.review_hog.backend.reviewer.models.thread_resolution import CommitHoldfrom products.review_hog.backend.reviewer.persistence import load_findings_bundle, load_valid_findingsfrom products.review_hog.backend.reviewer.progress import (SnapshotStats,@@ -274,6 +275,28 @@ def render_resolution_failed_section(*, done: int, total: int) -> str:)+def render_resolution_held_section(hold: CommitHold, *, done: int = 0, total: int = 0) -> str:+ """Why the stage did not commit fixes, so the author knows the open threads are theirs.++ `total` is set only when the run stopped part way.+ """+ if hold == CommitHold.STACKED:+ line = (+ f"Stopped resolving comments at {done}/{total}: another pull request is now stacked on this branch"+ if total+ else "Not resolving comments: other pull requests are stacked on this branch"+ )+ why = "A fix commit here would leave the stacked pull requests out of date"+ else:+ line = (+ f"Stopped resolving comments at {done}/{total}: this pull request was submitted to the merge queue"+ if total+ else "Not resolving comments: this pull request is submitted to the merge queue"+ )+ why = "A fix commit would change what was submitted, or remove it from the queue"+ return "\n".join([f"**{line}**", "", f"<sub>{why}, so the open threads stay with you.</sub>"])++def _splice_resolution_section(body: str, section: str) -> str:"""Replace (or append) the marker-delimited resolution section within a comment body."""block = f"{RESOLUTION_SECTION_START}\n{section}\n{RESOLUTION_SECTION_END}"diff --git a/products/review_hog/backend/temporal/resolution.py b/products/review_hog/backend/temporal/resolution.pyindex 15dfdb1ea89f..921b1d18ffbb 100644--- a/products/review_hog/backend/temporal/resolution.py+++ b/products/review_hog/backend/temporal/resolution.py@@ -29,6 +29,8 @@ from temporalio.common import RetryPolicyfrom temporalio.exceptions import ApplicationErrorfrom posthog.dataclasses import frozen+from posthog.egress.limiter.policies import Priority+from posthog.github.merge_queue import MergeQueueStatefrom posthog.models.integration import GitHubIntegration, Integrationfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.common.heartbeat import Heartbeater@@ -46,7 +48,7 @@ from products.review_hog.backend.reviewer.constants import (RESOLUTION_RUNTIME_ADAPTER,)from products.review_hog.backend.reviewer.models.github_meta import PRMetadata-from products.review_hog.backend.reviewer.models.thread_resolution import ThreadOutcome, ThreadResolution+from products.review_hog.backend.reviewer.models.thread_resolution import CommitHold, ThreadOutcome, ThreadResolutionfrom products.review_hog.backend.reviewer.persistence import (load_thread_verdicts,persist_thread_verdict,@@ -63,6 +65,7 @@ from products.review_hog.backend.reviewer.skill_loader import load_resolution_skfrom products.review_hog.backend.reviewer.status_comment import (render_resolution_failed_section,render_resolution_final_section,+ render_resolution_held_section,render_resolution_progress_section,update_resolution_status_comment,)@@ -136,8 +139,10 @@ class ResolutionRunResult:"""The run's summary — the same counts the persisted `note` artefact records."""report_id: str | None = None- # Deterministic no-op runs name their reason ("pr_not_open" / "no_unresolved_threads").+ # Deterministic no-op runs name their reason ("pr_not_open" / "no_unresolved_threads" / a CommitHold).skipped_reason: str | None = None+ # Set when the PR entered the merge queue mid-session; the run stopped before the next thread.+ stopped_reason: CommitHold | None = None# Threads that got an LLM turn this run, and their outcome counts (keyed by ThreadOutcome value).triaged: int = 0outcomes: dict[str, int] = field(default_factory=dict)@@ -174,6 +179,7 @@ class _PreparedRun:skill_name: strskill_version: intintegration_row_id: int+ queue_state_at_start: MergeQueueState | Nonedef _fetch_pr_metadata(input: ResolveThreadsInput, token: str, installation_id: str | None) -> PRMetadata:@@ -187,6 +193,48 @@ def _fetch_pr_metadata(input: ResolveThreadsInput, token: str, installation_id:return PRFetcher(input.owner, input.repo, input.pr_number, token, installation_id).fetch_pr_metadata(pr)+def _run_github(team_id: int, integration_row_id: int) -> GitHubIntegration:+ """The run-pinned installation, rebuilt from its row so every call mints a fresh token."""+ return GitHubIntegration(+ Integration.objects.get(id=integration_row_id, team_id=team_id), source="review_hog", priority=Priority.NORMAL+ )+++def _merge_queue_state(input: ResolveThreadsInput, github: GitHubIntegration) -> MergeQueueState | None:+ return github.get_pull_request_merge_queue_state(f"{input.owner}/{input.repo}", input.pr_number)+++def _commit_hold(+ input: ResolveThreadsInput,+ github: GitHubIntegration,+ head_branch: str,+ *,+ queue_state: MergeQueueState | None,+ queue_state_at_start: MergeQueueState | None,+) -> CommitHold | None:+ if queue_state is not None and queue_state.holds_pull_request:+ return CommitHold.MERGE_QUEUE+ # A turn's push ejects a PR that someone enqueued while the turn ran. The author meant to ship+ # it, so later turns must not push again. An ejection from before the session does not count,+ # or one old push would block the stage on this PR for good.+ if queue_state == MergeQueueState.EJECTED and queue_state_at_start != MergeQueueState.EJECTED:+ return CommitHold.MERGE_QUEUE+ if github.has_open_pull_request_with_base(f"{input.owner}/{input.repo}", head_branch):+ return CommitHold.STACKED+ return None+++def _commit_hold_for_run(input: ResolveThreadsInput, prepared: "_PreparedRun") -> CommitHold | None:+ github = _run_github(input.team_id, prepared.integration_row_id)+ return _commit_hold(+ input,+ github,+ prepared.pr_metadata.head_branch,+ queue_state=_merge_queue_state(input, github),+ queue_state_at_start=prepared.queue_state_at_start,+ )++def _prepare_run(input: ResolveThreadsInput) -> _PreparedRun | ResolutionRunResult:"""Fetch + gate + pre-filter; returns the prepared work-list, or the run result for a clean no-op."""# The run's one installation-selection probe — it doubles as the access gate. Deliveries reuse@@ -233,8 +281,25 @@ def _prepare_run(input: ResolveThreadsInput) -> _PreparedRun | ResolutionRunResutriage = order_threads(triage)overflow = max(0, len(triage) - MAX_THREADS_PER_RUN)triage = triage[:MAX_THREADS_PER_RUN]+ # Only triage turns commit. Redeliveries are replies and resolves, which are safe in the queue.+ queue_state = _merge_queue_state(input, github) if triage else None+ hold = (+ _commit_hold(input, github, pr_metadata.head_branch, queue_state=queue_state, queue_state_at_start=queue_state)+ if triage+ else None+ )+ if hold is not None:+ update_resolution_status_comment(+ input.team_id,+ report_id,+ render_resolution_held_section(hold),+ integration_row_id=github.integration.id,+ )+ triage, overflow = [], 0if not triage and not redeliver:- result = ResolutionRunResult(report_id=report_id, skipped_reason="no_unresolved_threads", skipped=skipped)+ result = ResolutionRunResult(+ report_id=report_id, skipped_reason=hold.value if hold else "no_unresolved_threads", skipped=skipped+ )_append_run_note(input, report_id, result)_idle_report(input.team_id, report_id)return result@@ -267,6 +332,7 @@ def _prepare_run(input: ResolveThreadsInput) -> _PreparedRun | ResolutionRunResuskill_name=skill.skill_name,skill_version=skill.version,integration_row_id=github.integration.id,+ queue_state_at_start=queue_state,)@@ -329,7 +395,7 @@ def _delivery_auth(team_id: int, integration_row_id: int) -> tuple[str, str | Nocall — so a mid-run revocation surfaces as a 401/404 on the write itself, the same per-threadundelivered accounting the probe failure used to produce."""- github = GitHubIntegration(Integration.objects.get(id=integration_row_id, team_id=team_id))+ github = _run_github(team_id, integration_row_id)return github.get_access_token(), github.github_installation_id@@ -541,6 +607,8 @@ def _append_run_note(input: ResolveThreadsInput, report_id: str, result: Resolutnote += f" {result.overflow} thread(s) remain beyond the {MAX_THREADS_PER_RUN}-thread run cap; the next run continues."if result.undelivered:note += f" {result.undelivered} thread(s) hit delivery failures; the next run redelivers them."+ if result.stopped_reason:+ note += f" Stopped early ({result.stopped_reason}); the remaining threads stay open."try:ReviewReportArtefact.add_log(team_id=input.team_id,@@ -645,6 +713,12 @@ async def resolve_threads_activity(input: ResolveThreadsInput) -> ResolutionRunRlogger.exception("Redelivery failed for thread %s; the next run will retry", verdict.thread_id)for thread in prepared.triage:+ # A person can enqueue the PR, or stack a PR on it, while earlier turns run. The check+ # sits outside the turn's try, so a failed read fails the run instead of committing blind.+ hold = await database_sync_to_async(_commit_hold_for_run, thread_sensitive=False)(input, prepared)+ if hold is not None:+ result.stopped_reason = hold+ breaktry:if session is None:session, resolution = await start_sandbox_session(@@ -764,9 +838,13 @@ async def resolve_threads_activity(input: ResolveThreadsInput) -> ResolutionRunRawait database_sync_to_async(update_resolution_status_comment, thread_sensitive=False)(input.team_id,prepared.report_id,+ render_resolution_held_section(+ result.stopped_reason, done=sum(result.delivered_outcomes.values()), total=total_queued+ )+ if result.stopped_reason# Undelivered threads (judged, or redelivered, without their GitHub writes landing) join# the couldn't-handle count: the tally must not claim an outcome the thread can't show.- render_resolution_final_section(+ else render_resolution_final_section(outcomes=result.delivered_outcomes, failed_turns=result.failed_turns + result.undelivered),integration_row_id=prepared.integration_row_id,diff --git a/products/review_hog/backend/tests/test_resolution_activity.py b/products/review_hog/backend/tests/test_resolution_activity.pyindex 91b68b246180..4d86fc02a4b4 100644--- a/products/review_hog/backend/tests/test_resolution_activity.py+++ b/products/review_hog/backend/tests/test_resolution_activity.py@@ -11,6 +11,7 @@ from asgiref.sync import async_to_syncfrom parameterized import parameterizedfrom social_django.models import UserSocialAuth+from posthog.github.merge_queue import MergeQueueStatefrom posthog.models.organization import Organizationfrom posthog.models.team import Teamfrom posthog.models.user import User@@ -101,6 +102,8 @@ def _mock_installation() -> Mock:github.get_access_token.return_value = "token"github.github_installation_id = "inst-1"github.integration.id = 42+ github.get_pull_request_merge_queue_state.return_value = None+ github.has_open_pull_request_with_base.return_value = Falsereturn github@@ -550,6 +553,45 @@ class TestResolutionPersistenceAndDelivery(BaseTest):assert content["skipped"] == 1assert eyes.call_args_list == [((), {"token": "token", "subject_id": "PRRC_1", "installation_id": "inst-1"})]+ @parameterized.expand(+ [+ (+ "submitted_to_merge_queue",+ MergeQueueState.NOT_READY,+ False,+ "pr_in_merge_queue",+ "submitted to the merge queue",+ ),+ ("stacked_pull_requests", None, True, "pr_has_stacked_pull_requests", "stacked on this branch"),+ ]+ )+ def test_held_pr_gets_no_turns_and_says_why(+ self, _name: str, queue_state: MergeQueueState | None, stacked: bool, reason: str, section_text: str+ ) -> None:+ self._report()+ installation = _mock_installation()+ installation.get_pull_request_merge_queue_state.return_value = queue_state+ installation.has_open_pull_request_with_base.return_value = stacked+ thread = ReviewThread(+ thread_id="PRRT_1",+ path="f.py",+ comments=[ThreadComment(id=1, node_id="PRRC_1", author_login="greptile", author_is_bot=True, body="b")],+ )+ eyes = Mock()+ with (+ patch(f"{_RESOLUTION}._installation_for", return_value=installation),+ patch(f"{_RESOLUTION}._fetch_pr_metadata", return_value=_pr_metadata()),+ patch(f"{_RESOLUTION}.fetch_unresolved_threads", return_value=[thread]),+ patch(f"{_RESOLUTION}.add_eyes_reaction", eyes),+ patch(f"{_RESOLUTION}.update_resolution_status_comment") as status_comment,+ ):+ result = _prepare_run(self._input())++ assert isinstance(result, ResolutionRunResult)+ assert result.skipped_reason == reason+ eyes.assert_not_called()+ assert section_text in status_comment.call_args.args[2]+def test_reaction_failure_never_fails_prepare(self) -> None:# A GitHub flake on the cosmetic queue marker must not cost the run (or the progress anchor,# which is written first).@@ -604,6 +646,7 @@ class TestFailedRunActivity(NonAtomicBaseTest):patch(f"{_RESOLUTION}._fetch_pr_metadata", return_value=_pr_metadata()),patch(f"{_RESOLUTION}.fetch_unresolved_threads", return_value=threads),patch(f"{_RESOLUTION}.add_eyes_reaction"),+ patch(f"{_RESOLUTION}._run_github", return_value=_mock_installation()),patch(f"{_RESOLUTION}.load_resolution_skill_for_run",return_value=Mock(skill_name="review-hog-resolution-criteria", version=1),@@ -689,3 +732,49 @@ class TestFailedRunActivity(NonAtomicBaseTest):final_section = status_comment.call_args.args[2]assert "couldn't handle 1" in final_sectionassert "declined" not in final_section++ @parameterized.expand(+ [+ ("enqueued", MergeQueueState.TESTING, False, "pr_in_merge_queue", "submitted to the merge queue"),+ (+ "ejected_by_the_turn_push",+ MergeQueueState.EJECTED,+ False,+ "pr_in_merge_queue",+ "submitted to the merge queue",+ ),+ ("stacked", None, True, "pr_has_stacked_pull_requests", "now stacked on this branch"),+ ]+ )+ def test_hold_appearing_mid_run_stops_the_session_before_the_next_turn(+ self, _name: str, queue_state: MergeQueueState | None, stacked: bool, reason: str, section_text: str+ ) -> None:+ run_github = _mock_installation()+ run_github.get_pull_request_merge_queue_state.side_effect = [None, queue_state]+ run_github.has_open_pull_request_with_base.side_effect = [False, stacked]+ mock_activity = Mock()+ mock_activity.info.return_value.attempt = 1+ session = Mock()+ session.task_run.task_id = "11111111-1111-1111-1111-111111111111"+ session.task_run.id = "run-1"+ res = ThreadResolution(thread_id="PRRT_A", outcome="wont_fix", reasoning="checked", reply="declined")+ continue_turn = AsyncMock()+ with ExitStack() as stack:+ for p in self._base_patches(mock_activity, [self._thread("PRRT_A"), self._thread("PRRT_B")]):+ stack.enter_context(p)+ stack.enter_context(patch(f"{_RESOLUTION}._run_github", return_value=run_github))+ stack.enter_context(patch(f"{_RESOLUTION}.start_sandbox_session", AsyncMock(return_value=(session, res))))+ stack.enter_context(patch(f"{_RESOLUTION}.continue_sandbox_session", continue_turn))+ stack.enter_context(patch(f"{_RESOLUTION}.end_sandbox_session", AsyncMock()))+ stack.enter_context(patch(f"{_RESOLUTION}.reply_to_thread", return_value=(555, None)))+ stack.enter_context(patch(f"{_RESOLUTION}.resolve_thread", return_value=True))+ status_comment = stack.enter_context(patch(f"{_RESOLUTION}.update_resolution_status_comment"))++ result = async_to_sync(resolve_threads_activity)(self._input())++ continue_turn.assert_not_called()+ assert result.triaged == 1+ assert result.stopped_reason == reason+ assert "Stopped resolving comments at 1/2" in status_comment.call_args.args[2]+ assert section_text in status_comment.call_args.args[2]+ assert self._report_status() == ReviewReport.Status.IDLE