: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(signals): check PR state before ticket replies (#126149)
Paul D'Ambra3774416caf71
diff --git a/products/signals/backend/report_assignments.py b/products/signals/backend/report_assignments.pyindex 91234eed5300..ecc1f522450a 100644--- a/products/signals/backend/report_assignments.py+++ b/products/signals/backend/report_assignments.py@@ -14,7 +14,7 @@ import structlogfrom posthog.dataclasses import frozenfrom posthog.egress.limiter.policies import Priorityfrom posthog.models.activity_logging.activity_log import Change, Detail, log_activity-from posthog.models.github_integration_base import GitHubIntegrationBase+from posthog.models.github_integration_base import GitHubIntegrationBase, GitHubIntegrationErrorfrom posthog.models.integration import GitHubIntegrationfrom posthog.models.user import User@@ -209,7 +209,7 @@ def claim_report_for_task(*, team_id: int, report_id: str, task_id: str) -> Reporeturn claim or create_claim(report, actor)-def _pull_request_details(team_id: int, pr_url: str) -> PullRequestDetails:+def _pull_request_details(team_id: int, pr_url: str, *, raise_on_error: bool = False) -> PullRequestDetails:parsed = GitHubIntegrationBase.parse_pull_request_url(pr_url)if parsed is None:raise InvalidPullRequestUrl("pr_url must be a GitHub pull request URL.")@@ -236,6 +236,8 @@ def _pull_request_details(team_id: int, pr_url: str) -> PullRequestDetails:team_id=team_id,repository=parsed.repository,)+ if raise_on_error:+ raisereturn detailsif github is None:return details@@ -249,6 +251,8 @@ def _pull_request_details(team_id: int, pr_url: str) -> PullRequestDetails:repository=parsed.repository,pr_number=parsed.number,)+ if raise_on_error:+ raisereturn detailsif not status.get("success"):logger.warning(@@ -258,6 +262,8 @@ def _pull_request_details(team_id: int, pr_url: str) -> PullRequestDetails:pr_number=parsed.number,error=status.get("error"),)+ if raise_on_error and status.get("status_code") != 404:+ raise GitHubIntegrationError("Unable to verify pull request state", status_code=status.get("status_code"))return detailsmerged = bool(status.get("merged"))diff --git a/products/signals/backend/tasks.py b/products/signals/backend/tasks.pyindex 26438978f4bb..0f7e96d5a621 100644--- a/products/signals/backend/tasks.py+++ b/products/signals/backend/tasks.py@@ -30,6 +30,7 @@ from posthog.ph_client import ph_scoped_capturefrom posthog.scoping_audit import skip_team_scope_auditfrom posthog.temporal.common.utils import is_stale_connection_read_only_error+from products.signals.backend import report_assignmentsfrom products.signals.backend.assignment_flags import assignment_side_effects_allowedfrom products.signals.backend.billing import current_billing_period_boundsfrom products.signals.backend.first_report_notification_tasks import (@@ -119,11 +120,17 @@ def refresh_report_implementation_pr_cache()-@shared_task(ignore_result=True, autoretry_for=(Exception,), retry_backoff=True, max_retries=5)+@shared_task(bind=True, ignore_result=True, autoretry_for=(Exception,), retry_backoff=True, max_retries=5)@with_team_scope()-def write_pull_request_to_support_tickets(team_id: int, report_id: str, pr_url: str, task_id: str) -> None:+def write_pull_request_to_support_tickets(self: Task, team_id: int, report_id: str, pr_url: str, task_id: str) -> None:if not task_can_write_support_ticket_update(team_id=team_id, report_id=report_id, task_id=task_id, pr_url=pr_url):return+ try:+ pr = report_assignments._pull_request_details(team_id, pr_url, raise_on_error=True)+ except GitHubRateLimitError as error:+ raise self.retry(exc=error, countdown=max(error.retry_after or 0, 60))+ if pr.state not in {SignalReportPullRequest.State.DRAFT, SignalReportPullRequest.State.OPEN}:+ returnteam = Team.objects.filter(id=team_id).first()if team is None:returndiff --git a/products/signals/backend/test/test_support_writeback.py b/products/signals/backend/test/test_support_writeback.pyindex 6237aa599f40..88f3f47564b9 100644--- a/products/signals/backend/test/test_support_writeback.py+++ b/products/signals/backend/test/test_support_writeback.py@@ -4,9 +4,12 @@ import pytestfrom posthog.test.base import BaseTestfrom unittest.mock import MagicMock, patch+from celery.exceptions import Retryfrom parameterized import parameterized+from posthog.egress.github.transport import GitHubRateLimitErrorfrom posthog.models.comment import Comment+from posthog.models.github_integration_base import GitHubIntegrationErrorfrom products.conversations.backend.facade import api as conversations_facadefrom products.conversations.backend.models import ConversationDelivery, TeamConversationsSlackConfig, Ticket@@ -245,23 +248,109 @@ class TestPostReportFindingsToTickets(BaseTest):)send_note.assert_not_called()- def test_worker_rechecks_verified_task_pr_before_ticket_write(self):+ @parameterized.expand(+ [+ ("open", "open", 1),+ ("draft", "draft", 1),+ ("merged", "merged", 0),+ ("closed", "closed", 0),+ ("unavailable", "unknown", 0),+ ]+ )+ def test_worker_rechecks_verified_task_pr_before_ticket_write(self, _name, pr_state, expected_replies):from products.signals.backend.tasks import write_pull_request_to_support_ticketspr_url = "https://github.com/PostHog/posthog/pull/123"task = Task.objects.create(team=self.team, created_by=self.user)SignalReportTask.objects.create(team=self.team, report=self.report, task=task, relationship="implementation")run = TaskRun.objects.create(team=self.team, task=task, state={})+ self.team.conversations_settings = {"automated_update_slack_channel_ids": ["C123"]}+ self.team.save(update_fields=["conversations_settings"])+ TeamConversationsSlackConfig.objects.update_or_create(+ team=self.team, defaults={"slack_team_id": "T123", "slack_bot_token": "xoxb-test"}+ )+ ticket = Ticket.objects.create_with_number(+ team=self.team,+ widget_session_id="",+ distinct_id="slack-user",+ channel_source="slack",+ slack_channel_id="C123",+ slack_thread_ts="1700000000.000100",+ )+ signal = {"source_product": "conversations", "source_id": str(ticket.id)}+ client = MagicMock()+ client.conversations_info.return_value = {"channel": {"is_channel": True}}- with patch("products.signals.backend.tasks.fetch_signals_for_report_sync", return_value=[self.signal]):+ details = PullRequestDetails(+ url=pr_url, repository="PostHog/posthog", number=123, state=pr_state, merged=pr_state == "merged"+ )+ with (+ patch("products.signals.backend.tasks.fetch_signals_for_report_sync", return_value=[signal]),+ patch("products.signals.backend.report_assignments._pull_request_details", return_value=details),+ patch("products.conversations.backend.facade.api.get_slack_client", return_value=client),+ ):write_pull_request_to_support_tickets.run(self.team.pk, str(self.report.id), pr_url, str(task.id))- assert not _ticket_notes(self.team, self.ticket).exists()+ assert not _ticket_notes(self.team, ticket).exists()run.state = {"verified_pr_urls": [pr_url]}run.save(update_fields=["state"])write_pull_request_to_support_tickets.run(self.team.pk, str(self.report.id), pr_url, str(task.id))- assert _ticket_notes(self.team, self.ticket).count() == 1+ replies = _ticket_notes(self.team, ticket)+ assert replies.count() == expected_replies+ assert (+ ConversationDelivery.objects.for_team(self.team.id).filter(comment_id__in=replies.values("id")).count()+ == expected_replies+ )++ @parameterized.expand(+ [+ ("integration_lookup", True, False),+ ("pull_request_fetch", False, False),+ ("pull_request_exception", False, True),+ ]+ )+ def test_worker_retries_transient_pull_request_lookup_errors(self, _name, integration_lookup_fails, fetch_raises):+ from products.signals.backend.tasks import write_pull_request_to_support_tickets++ github = MagicMock()+ github.get_pull_request.return_value = {"success": False, "error": "Network error fetching pull request"}+ if fetch_raises:+ github.get_pull_request.side_effect = TimeoutError("GitHub unavailable")+ with (+ patch("products.signals.backend.tasks.task_can_write_support_ticket_update", return_value=True),+ patch("products.signals.backend.tasks.fetch_signals_for_report_sync", return_value=[self.signal]),+ patch(+ "products.signals.backend.report_assignments.GitHubIntegration.first_for_team_repository",+ return_value=github,+ side_effect=TimeoutError("GitHub unavailable") if integration_lookup_fails else None,+ ),+ pytest.raises((TimeoutError, GitHubIntegrationError)),+ ):+ write_pull_request_to_support_tickets.run(+ self.team.pk, str(self.report.id), "https://github.com/example/app/pull/123", "task-id"+ )++ assert not _ticket_notes(self.team, self.ticket).exists()++ @parameterized.expand([(120, 120), (None, 60), (5, 60)])+ def test_worker_honors_github_retry_delay(self, retry_after, expected_countdown):+ from products.signals.backend.tasks import write_pull_request_to_support_tickets++ error = GitHubRateLimitError("rate limited", retry_after=retry_after)+ with (+ patch("products.signals.backend.tasks.task_can_write_support_ticket_update", return_value=True),+ patch("products.signals.backend.report_assignments._pull_request_details", side_effect=error),+ patch("products.signals.backend.tasks.post_pull_request_to_tickets") as post_update,+ patch.object(write_pull_request_to_support_tickets, "retry", side_effect=Retry()) as retry,+ pytest.raises(Retry),+ ):+ write_pull_request_to_support_tickets._orig_run(+ self.team.pk, str(self.report.id), "https://github.com/example/app/pull/123", "task-id"+ )++ retry.assert_called_once_with(exc=error, countdown=expected_countdown)+ post_update.assert_not_called()def test_ignores_signals_from_other_products(self):error_signal = {"source_product": "error_tracking", "source_id": "issue-1"}