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.

feat(signals): close linked PR when a report is dismissed (#68039)

Rafael Audiberte2963dbdf390
diff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.py
index 25bfb707df3b..70242fbdfa9c 100644
--- a/posthog/models/github_integration_base.py
+++ b/posthog/models/github_integration_base.py
@@ -439,6 +439,40 @@ class GitHubIntegrationBase:
logger.warning("GitHubIntegration: installation GET failed", url=url, exc_info=True)
return None
+ def _installation_authenticated_patch(
+ self,
+ url: str,
+ *,
+ endpoint: str,
+ json_body: Mapping[str, object],
+ timeout: int = 10,
+ ) -> requests.Response | None:
+ """PATCH with installation token via :meth:`api_request`; ``None`` instead of raising, for the
+ success/error-dict verbs built on top."""
+ path = url.removeprefix("https://api.github.com")
+ try:
+ return self.api_request("PATCH", path, endpoint=endpoint, json_body=json_body, timeout=timeout)
+ except GitHubIntegrationError:
+ logger.warning("GitHubIntegration: installation PATCH failed", url=url, exc_info=True)
+ return None
+
+ def _installation_authenticated_post(
+ self,
+ url: str,
+ *,
+ endpoint: str,
+ json_body: Mapping[str, object],
+ timeout: int = 10,
+ ) -> requests.Response | None:
+ """POST with installation token via :meth:`api_request`; ``None`` instead of raising, for the
+ success/error-dict verbs built on top."""
+ path = url.removeprefix("https://api.github.com")
+ try:
+ return self.api_request("POST", path, endpoint=endpoint, json_body=json_body, timeout=timeout)
+ except GitHubIntegrationError:
+ logger.warning("GitHubIntegration: installation POST failed", url=url, exc_info=True)
+ return None
+
def installation_can_access_repository(self, repository: str) -> bool:
"""Whether this installation token can access the repo (``GET /repos/{owner}/{repo}`` returns 200)."""
response = self._installation_authenticated_get(
@@ -650,6 +684,73 @@ class GitHubIntegrationBase:
owner, repo, pr_number = parsed
return self.get_pull_request(f"{owner}/{repo}", pr_number)
+ def close_pull_request(self, repository: str, pr_number: int) -> dict[str, Any]:
+ """Close a pull request (``PATCH`` state=closed). ``repository`` is ``owner/repo`` or a bare repo.
+
+ Idempotent: an already-closed or merged PR reports success without reopening it (GitHub
+ ignores a closed→closed transition, and closing a merged PR is a no-op).
+ """
+ repo_path = repository if "/" in repository else f"{self.organization()}/{repository}"
+
+ response = self._installation_authenticated_patch(
+ f"https://api.github.com/repos/{repo_path}/pulls/{pr_number}",
+ endpoint="/repos/{owner}/{repo}/pulls/{pull_number}",
+ json_body={"state": "closed"},
+ )
+ if response is None:
+ return {"success": False, "error": "Network error closing pull request"}
+ if response.status_code != 200:
+ return {
+ "success": False,
+ "error": f"Failed to close pull request: {response.text}",
+ "status_code": response.status_code,
+ }
+
+ try:
+ pr = response.json()
+ except Exception:
+ pr = {}
+
+ return {"success": True, "number": pr.get("number", pr_number), "state": pr.get("state")}
+
+ def close_pull_request_from_url(self, pr_url: str) -> dict[str, Any]:
+ """Close a pull request by its HTML URL (e.g. ``https://github.com/owner/repo/pull/123``)."""
+ parsed = self.parse_pull_request_url(pr_url)
+ if parsed is None:
+ return {"success": False, "error": f"Invalid GitHub pull request URL: {pr_url}"}
+ owner, repo, pr_number = parsed
+ return self.close_pull_request(f"{owner}/{repo}", pr_number)
+
+ def comment_on_pull_request(self, repository: str, pr_number: int, body: str) -> dict[str, Any]:
+ """Post a comment on a pull request. ``repository`` is ``owner/repo`` or a bare repo.
+
+ PR comments use the issues endpoint (a PR is an issue for commenting purposes).
+ """
+ repo_path = repository if "/" in repository else f"{self.organization()}/{repository}"
+
+ response = self._installation_authenticated_post(
+ f"https://api.github.com/repos/{repo_path}/issues/{pr_number}/comments",
+ endpoint="/repos/{owner}/{repo}/issues/{issue_number}/comments",
+ json_body={"body": body},
+ )
+ if response is None:
+ return {"success": False, "error": "Network error commenting on pull request"}
+ if response.status_code != 201:
+ return {
+ "success": False,
+ "error": f"Failed to comment on pull request: {response.text}",
+ "status_code": response.status_code,
+ }
+ return {"success": True}
+
+ def comment_on_pull_request_from_url(self, pr_url: str, body: str) -> dict[str, Any]:
+ """Post a comment on a pull request by its HTML URL."""
+ parsed = self.parse_pull_request_url(pr_url)
+ if parsed is None:
+ return {"success": False, "error": f"Invalid GitHub pull request URL: {pr_url}"}
+ owner, repo, pr_number = parsed
+ return self.comment_on_pull_request(f"{owner}/{repo}", pr_number, body)
+
def find_pull_request_urls_for_branch(self, repository: str, branch: str) -> list[str]:
"""Return the HTML URLs of open or closed PRs whose head is ``branch`` in ``repository``.
diff --git a/posthog/models/test/test_integration_model.py b/posthog/models/test/test_integration_model.py
index 631bbfb04ae5..1fdd3f07bf53 100644
--- a/posthog/models/test/test_integration_model.py
+++ b/posthog/models/test/test_integration_model.py
@@ -1097,6 +1097,72 @@ class TestGitHubIntegrationModel(BaseTest):
assert result is not None
mock_access.assert_called_once_with("PostHog/posthog")
+ @parameterized.expand(
+ [
+ ("owner_repo", "PostHog/posthog", "https://api.github.com/repos/PostHog/posthog/pulls/123"),
+ ("bare_repo", "posthog", "https://api.github.com/repos/PostHog/posthog/pulls/123"),
+ ]
+ )
+ def test_close_pull_request_patches_state_closed(self, _name, repository, expected_url):
+ # account.name lets a bare repo name resolve to {org}/{repo} via organization().
+ integration = self.create_integration(
+ config={"account": {"name": "PostHog"}}, sensitive_config={"access_token": "ACCESS_TOKEN"}
+ )
+ github = GitHubIntegration(integration)
+ mock_response = MagicMock(status_code=200)
+ mock_response.json.return_value = {"number": 123, "state": "closed"}
+ with patch.object(github, "_installation_authenticated_patch", return_value=mock_response) as mock_patch:
+ result = github.close_pull_request(repository, 123)
+ assert result == {"success": True, "number": 123, "state": "closed"}
+ assert mock_patch.call_args.args[0] == expected_url
+ assert mock_patch.call_args.kwargs["json_body"] == {"state": "closed"}
+
+ def test_close_pull_request_maps_upstream_error(self):
+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
+ github = GitHubIntegration(integration)
+ mock_response = MagicMock(status_code=404, text="Not Found")
+ with patch.object(github, "_installation_authenticated_patch", return_value=mock_response):
+ result = github.close_pull_request("PostHog/posthog", 123)
+ assert result == {"success": False, "error": "Failed to close pull request: Not Found", "status_code": 404}
+
+ def test_close_pull_request_from_url_parses_and_closes(self):
+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
+ github = GitHubIntegration(integration)
+ mock_response = MagicMock(status_code=200)
+ mock_response.json.return_value = {"number": 42, "state": "closed"}
+ with patch.object(github, "_installation_authenticated_patch", return_value=mock_response) as mock_patch:
+ result = github.close_pull_request_from_url("https://github.com/PostHog/posthog/pull/42")
+ assert result["success"] is True
+ assert mock_patch.call_args.args[0] == "https://api.github.com/repos/PostHog/posthog/pulls/42"
+
+ def test_close_pull_request_from_url_rejects_non_pr_url(self):
+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
+ github = GitHubIntegration(integration)
+ with patch.object(github, "_installation_authenticated_patch") as mock_patch:
+ result = github.close_pull_request_from_url("https://github.com/PostHog/posthog/issues/42")
+ assert result["success"] is False
+ mock_patch.assert_not_called()
+
+ def test_comment_on_pull_request_posts_to_issues_endpoint(self):
+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
+ github = GitHubIntegration(integration)
+ mock_response = MagicMock(status_code=201)
+ with patch.object(github, "_installation_authenticated_post", return_value=mock_response) as mock_post:
+ result = github.comment_on_pull_request("PostHog/posthog", 123, "hello")
+ assert result == {"success": True}
+ # PR comments go through the issues endpoint, not /pulls.
+ assert mock_post.call_args.args[0] == "https://api.github.com/repos/PostHog/posthog/issues/123/comments"
+ assert mock_post.call_args.kwargs["json_body"] == {"body": "hello"}
+
+ def test_comment_on_pull_request_from_url_parses_and_posts(self):
+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
+ github = GitHubIntegration(integration)
+ mock_response = MagicMock(status_code=201)
+ with patch.object(github, "_installation_authenticated_post", return_value=mock_response) as mock_post:
+ result = github.comment_on_pull_request_from_url("https://github.com/PostHog/posthog/pull/42", "note")
+ assert result["success"] is True
+ assert mock_post.call_args.args[0] == "https://api.github.com/repos/PostHog/posthog/issues/42/comments"
+
@parameterized.expand(
[
(
diff --git a/posthog/test/setup_receivers_baseline.txt b/posthog/test/setup_receivers_baseline.txt
index 6ad75c701924..8deb81194c26 100644
--- a/posthog/test/setup_receivers_baseline.txt
+++ b/posthog/test/setup_receivers_baseline.txt
@@ -169,6 +169,7 @@ post_save:products.product_analytics.backend.models.insight_caching_state.sync_d
post_save:products.product_analytics.backend.models.insight_caching_state.sync_dashboard_updated
post_save:products.product_analytics.backend.models.insight_caching_state.sync_insight
post_save:products.product_analytics.backend.models.insight_caching_state.sync_sharing_configuration
+post_save:products.signals.backend.receivers.close_pr_when_report_dismissed
post_save:products.slack_app.backend.signals.invalidate_repo_list_on_user_github_change
post_save:products.slack_app.backend.signals.onboard_slack_inbox_on_install
post_save:products.surveys.backend.models.survey_changed
@@ -206,6 +207,7 @@ pre_save:posthog.storage.team_access_cache_signal_handlers.team_pre_save_auth_ca
pre_save:posthog.storage.team_llm_gateway_policy_signal_handlers._capture_old_state_if_deferred
pre_save:products.cohorts.backend.models.dependencies.cohort_pre_save
pre_save:products.conversations.backend.signals.handle_comment_soft_delete
+pre_save:products.signals.backend.receivers.capture_prior_status_for_pr_close
pre_save:products.customer_analytics.backend.models.account._enforce_account_group_type_index_drift_policy
pre_save:products.event_definitions.backend.models.event_definition._capture_event_definition_old_name
pre_save:products.surveys.backend.models.pre_save_survey
diff --git a/products/signals/backend/apps.py b/products/signals/backend/apps.py
index d0d95e961d83..a63ce20dd96d 100644
--- a/products/signals/backend/apps.py
+++ b/products/signals/backend/apps.py
@@ -7,9 +7,13 @@ class SignalsConfig(AppConfig):
label = "signals"
def ready(self) -> None:
- # Registers the model_activity_signal receiver that persists SignalScoutConfig
- # audit-log entries. ModelActivityMixin only emits the signal; this is the consumer.
- from . import activity_logging # noqa: F401
+ # activity_logging: consumes model_activity_signal to persist SignalScoutConfig audit-log
+ # entries (ModelActivityMixin only emits the signal; this is the consumer).
+ # receivers: post_save receiver that closes a report's implementation PR on suppression/snooze.
+ from . import (
+ activity_logging, # noqa: F401
+ receivers, # noqa: F401
+ )
self._register_signal_emission_gate()
diff --git a/products/signals/backend/implementation_pr.py b/products/signals/backend/implementation_pr.py
index de8459ae3e4e..f141896786b7 100644
--- a/products/signals/backend/implementation_pr.py
+++ b/products/signals/backend/implementation_pr.py
@@ -1,9 +1,18 @@
"""Resolve implementation PR URLs linked to signal reports."""
+from typing import Literal, cast
+
+import structlog
+
+from posthog.models.github_integration_base import GitHubIntegrationBase
+from posthog.models.integration import GitHubIntegration
+
from products.signals.backend.models import SignalReport
from products.signals.backend.task_run_artefacts import SIGNALS_PRODUCT, TASK_RUN_TYPE_IMPLEMENTATION
from products.tasks.backend.facade import api as tasks_facade
+logger = structlog.get_logger(__name__)
+
def fetch_implementation_pr_urls_for_reports(report_ids: list[str]) -> dict[str, str]:
"""PR URL from the latest implementation task run for each report, when available.
@@ -37,3 +46,73 @@ def fetch_implementation_pr_urls_for_reports(report_ids: list[str]) -> dict[str,
if pr_url and report_id not in result:
result[report_id] = pr_url
return result
+
+
+PrCloseReason = Literal["suppressed", "snoozed"]
+
+# Left on the PR before it's closed, so anyone looking at the PR sees why it was closed and how to undo it.
+_PR_CLOSE_COMMENT_TEMPLATE = (
+ "🔕 Closing this PR because the linked PostHog report was {action}.\n\n"
+ "If that wasn't intended, restore the report in PostHog and reopen this PR."
+)
+_PR_CLOSE_COMMENTS: dict[PrCloseReason, str] = {
+ reason: _PR_CLOSE_COMMENT_TEMPLATE.format(action=reason)
+ for reason in cast(tuple[PrCloseReason, ...], ("suppressed", "snoozed"))
+}
+
+
+def close_implementation_pr_for_report(
+ team_id: int,
+ report_id: str,
+ *,
+ reason: PrCloseReason = "suppressed",
+) -> bool:
+ """Best-effort: comment on and close the GitHub PR opened for this report's implementation task.
+
+ Called when a report is suppressed or snoozed — the open PR shouldn't linger. Leaves an
+ explanatory comment, then closes the PR. Returns True when the PR was closed, False when there
+ was nothing to close or the close couldn't be completed. Never raises: the state transition
+ must succeed regardless.
+ """
+ try:
+ pr_url = fetch_implementation_pr_urls_for_reports([str(report_id)]).get(str(report_id))
+ if not pr_url:
+ return False
+
+ parsed = GitHubIntegrationBase.parse_pull_request_url(pr_url)
+ if parsed is None:
+ logger.warning("close_implementation_pr_unparseable_url", report_id=str(report_id), pr_url=pr_url)
+ return False
+ owner, repo, pr_number = parsed
+ repository = f"{owner}/{repo}"
+
+ github = GitHubIntegration.first_for_team_repository(team_id, repository)
+ if github is None:
+ logger.info("close_implementation_pr_no_integration", report_id=str(report_id), repository=repository)
+ return False
+
+ # Explain first, close second — a failed comment shouldn't stop the close.
+ comment_outcome = github.comment_on_pull_request(repository, pr_number, _PR_CLOSE_COMMENTS[reason])
+ if not comment_outcome.get("success"):
+ logger.warning(
+ "close_implementation_pr_comment_failed",
+ report_id=str(report_id),
+ pr_url=pr_url,
+ error=comment_outcome.get("error"),
+ status_code=comment_outcome.get("status_code"),
+ )
+
+ outcome = github.close_pull_request(repository, pr_number)
+ if not outcome.get("success"):
+ logger.warning(
+ "close_implementation_pr_failed",
+ report_id=str(report_id),
+ pr_url=pr_url,
+ error=outcome.get("error"),
+ status_code=outcome.get("status_code"),
+ )
+ return False
+ return True
+ except Exception:
+ logger.exception("close_implementation_pr_unexpected_error", report_id=str(report_id))
+ return False
diff --git a/products/signals/backend/receivers.py b/products/signals/backend/receivers.py
new file mode 100644
index 000000000000..eb1dc2dca8ea
--- /dev/null
+++ b/products/signals/backend/receivers.py
@@ -0,0 +1,100 @@
+"""Django signal receivers for the signals product.
+
+Kept in one place so cross-cutting side effects of report state changes have a single home,
+rather than being sprinkled across every dismissal entrypoint (Slack, REST, bulk, …).
+"""
+
+from typing import Any
+
+from django.db import transaction
+from django.db.models.signals import post_save, pre_save
+from django.dispatch import receiver
+
+from products.signals.backend.implementation_pr import PrCloseReason
+from products.signals.backend.models import SignalReport
+from products.signals.backend.tasks import close_dismissed_report_pr
+
+_SNOOZE_SOURCE_STATUSES = frozenset({SignalReport.Status.READY, SignalReport.Status.RESOLVED})
+
+
+@receiver(pre_save, sender=SignalReport)
+def capture_prior_status_for_pr_close(
+ sender: type[SignalReport],
+ instance: SignalReport,
+ **kwargs: Any,
+) -> None:
+ """Stash the row's prior status so post_save can tell a real transition from a no-op edit."""
+ # UUIDModel PKs carry a Python-side default, so pk is set at construction, never None — use
+ # _state.adding to tell an unsaved row (no prior status) from an update.
+ if instance._state.adding:
+ instance._prior_status_for_pr_close = None # type: ignore[attr-defined]
+ return
+
+ update_fields = kwargs.get("update_fields")
+ if update_fields is not None and "status" not in update_fields:
+ instance._prior_status_for_pr_close = None # type: ignore[attr-defined]
+ return
+
+ instance._prior_status_for_pr_close = sender.objects.filter(pk=instance.pk).values_list("status", flat=True).first() # type: ignore[attr-defined]
+
+
+def _pr_close_reason(
+ instance: SignalReport,
+ *,
+ created: bool,
+ update_fields: set[str] | None,
+ prior_status: str | None,
+) -> PrCloseReason | None:
+ if created:
+ # Reports born SUPPRESSED by the scout safety/actionability judge never surfaced a PR.
+ return None
+ # React only to the save that performed the transition, not later edits.
+ if update_fields is not None and "status" not in update_fields:
+ return None
+ if prior_status is None or prior_status == instance.status:
+ return None
+
+ if instance.status == SignalReport.Status.SUPPRESSED:
+ return "suppressed"
+
+ if instance.status == SignalReport.Status.POTENTIAL and prior_status in _SNOOZE_SOURCE_STATUSES:
+ return "snoozed"
+
+ return None
+
+
+@receiver(post_save, sender=SignalReport)
+def close_pr_when_report_dismissed(
+ sender: type[SignalReport],
+ instance: SignalReport,
+ created: bool,
+ update_fields: set[str] | None = None,
+ **kwargs: Any,
+) -> None:
+ """Close the implementation PR when a report is suppressed or snoozed.
+
+ This is the single choke point for the archive→close side effect: every suppression surface
+ (Slack, the REST state/bulk-state API, any future one) ends in a ``save`` that flips status
+ to SUPPRESSED, and snoozing a ready/resolved report ends in READY/RESOLVED → POTENTIAL, so
+ hooking the model here covers them all without each caller opting in.
+ """
+ prior_status = getattr(instance, "_prior_status_for_pr_close", None)
+ reason = _pr_close_reason(
+ instance,
+ created=created,
+ update_fields=update_fields,
+ prior_status=prior_status,
+ )
+ if reason is None:
+ return
+
+ team_id = instance.team_id
+ report_id = str(instance.id)
+ # After commit so a rolled-back transition never closes a PR; best-effort inside the task.
+ transaction.on_commit(
+ lambda: close_dismissed_report_pr.delay(
+ report_id=report_id,
+ team_id=team_id,
+ reason=reason,
+ )
+ )
diff --git a/products/signals/backend/report_actions.py b/products/signals/backend/report_actions.py
index 79a1610030ba..ad61fbf72127 100644
--- a/products/signals/backend/report_actions.py
+++ b/products/signals/backend/report_actions.py
@@ -60,4 +60,6 @@ def suppress_report_from_slack(
content=Dismissal(reason="slack_dismiss", slack_user_id=slack_user_id),
attribution=attribution,
)
+ # The linked implementation PR is closed by the post_save receiver on suppression or snooze
+ # (see receivers.close_pr_when_report_dismissed) — no per-caller call needed here.
return True
diff --git a/products/signals/backend/tasks.py b/products/signals/backend/tasks.py
new file mode 100644
index 000000000000..b115778c4bf9
--- /dev/null
+++ b/products/signals/backend/tasks.py
@@ -0,0 +1,15 @@
+from celery import shared_task
+
+from posthog.models.scoping import with_team_scope
+
+from products.signals.backend.implementation_pr import PrCloseReason, close_implementation_pr_for_report
+
+
+@shared_task(
+ name="products.signals.backend.tasks.close_dismissed_report_pr",
+ ignore_result=True,
+ max_retries=0,
+)
+@with_team_scope()
+def close_dismissed_report_pr(report_id: str, team_id: int, reason: PrCloseReason = "suppressed") -> None:
+ close_implementation_pr_for_report(team_id, report_id, reason=reason)
diff --git a/products/signals/backend/test/test_dismissal_pr_close.py b/products/signals/backend/test/test_dismissal_pr_close.py
new file mode 100644
index 000000000000..c7875b2de496
--- /dev/null
+++ b/products/signals/backend/test/test_dismissal_pr_close.py
@@ -0,0 +1,161 @@
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from products.signals.backend.implementation_pr import PrCloseReason, close_implementation_pr_for_report
+from products.signals.backend.models import SignalReport
+from products.signals.backend.tasks import close_dismissed_report_pr
+
+_PR_URL = "https://github.com/PostHog/posthog/pull/123"
+
+
+class TestClosePrWhenReportDismissed(BaseTest):
+ """The post_save receiver is the single choke point that closes a report's PR on archive."""
+
+ def _create_report(self, report_status=SignalReport.Status.READY) -> SignalReport:
+ return SignalReport.objects.create(
+ team=self.team,
+ status=report_status,
+ title="Test report",
+ summary="Test summary",
+ signal_count=1,
+ total_weight=1.0,
+ )
+
+ def _save_transition(self, report: SignalReport, new_status: SignalReport.Status, **kwargs) -> None:
+ with self.captureOnCommitCallbacks(execute=True):
+ updated = report.transition_to(new_status, **kwargs)
+ report.save(update_fields=updated)
+
+ @parameterized.expand(
+ [
+ ("suppressed", SignalReport.Status.READY, SignalReport.Status.SUPPRESSED, {}, "suppressed"),
+ (
+ "snooze_from_ready",
+ SignalReport.Status.READY,
+ SignalReport.Status.POTENTIAL,
+ {"snooze_for": 5},
+ "snoozed",
+ ),
+ ("snooze_from_resolved", SignalReport.Status.RESOLVED, SignalReport.Status.POTENTIAL, {}, "snoozed"),
+ ]
+ )
+ def test_archive_transition_enqueues_close_task(
+ self, _name, source_status, new_status, transition_kwargs, expected_reason
+ ):
+ report = self._create_report(report_status=source_status)
+ with patch("products.signals.backend.receivers.close_dismissed_report_pr") as mock_task:
+ self._save_transition(report, new_status, **transition_kwargs)
+ mock_task.delay.assert_called_once_with(
+ report_id=str(report.id),
+ team_id=self.team.id,
+ reason=expected_reason,
+ )
+
+ def test_full_save_on_dismiss_enqueues_close_task(self):
+ report = self._create_report()
+ with patch("products.signals.backend.receivers.close_dismissed_report_pr") as mock_task:
+ with self.captureOnCommitCallbacks(execute=True):
+ report.transition_to(SignalReport.Status.SUPPRESSED)
+ report.save()
+ mock_task.delay.assert_called_once_with(
+ report_id=str(report.id),
+ team_id=self.team.id,
+ reason="suppressed",
+ )
+
+ def test_full_save_without_status_change_does_not_enqueue(self):
+ report = self._create_report(report_status=SignalReport.Status.SUPPRESSED)
+ with patch("products.signals.backend.receivers.close_dismissed_report_pr") as mock_task:
+ with self.captureOnCommitCallbacks(execute=True):
+ report.title = "edited"
+ report.save()
+ mock_task.delay.assert_not_called()
+
+ def test_born_suppressed_report_does_not_enqueue(self):
+ with patch("products.signals.backend.receivers.close_dismissed_report_pr") as mock_task:
+ with self.captureOnCommitCallbacks(execute=True):
+ self._create_report(report_status=SignalReport.Status.SUPPRESSED)
+ mock_task.delay.assert_not_called()
+
+ def test_restore_from_suppressed_does_not_enqueue(self):
+ report = self._create_report(report_status=SignalReport.Status.SUPPRESSED)
+ with patch("products.signals.backend.receivers.close_dismissed_report_pr") as mock_task:
+ self._save_transition(report, SignalReport.Status.POTENTIAL)
+ mock_task.delay.assert_not_called()
+
+ def test_pipeline_reset_to_potential_does_not_enqueue(self):
+ report = self._create_report(report_status=SignalReport.Status.IN_PROGRESS)
+ with patch("products.signals.backend.receivers.close_dismissed_report_pr") as mock_task:
+ self._save_transition(report, SignalReport.Status.POTENTIAL, error="not actionable")
+ mock_task.delay.assert_not_called()
+
+ def test_unrelated_save_of_suppressed_report_does_not_enqueue(self):
+ report = self._create_report(report_status=SignalReport.Status.SUPPRESSED)
+ with patch("products.signals.backend.receivers.close_dismissed_report_pr") as mock_task:
+ with self.captureOnCommitCallbacks(execute=True):
+ report.title = "edited"
+ report.save(update_fields=["title"])
+ mock_task.delay.assert_not_called()
+
+
+class TestCloseDismissedReportPrTask(BaseTest):
+ def test_task_invokes_close_helper_with_team_report_and_reason(self):
+ with patch("products.signals.backend.tasks.close_implementation_pr_for_report") as mock_close:
+ close_dismissed_report_pr(report_id="report-1", team_id=self.team.id, reason="snoozed")
+ mock_close.assert_called_once_with(self.team.id, "report-1", reason="snoozed")
+
+
+class TestCloseImplementationPrForReport(BaseTest):
+ @parameterized.expand(
+ [
+ ("suppressed", "suppressed"),
+ ("snoozed", "snoozed"),
+ ]
+ )
+ def test_comments_on_and_closes_linked_pr(self, _name: str, reason: PrCloseReason):
+ github = MagicMock()
+ github.comment_on_pull_request.return_value = {"success": True}
+ github.close_pull_request.return_value = {"success": True, "number": 123, "state": "closed"}
+ with (
+ patch(
+ "products.signals.backend.implementation_pr.fetch_implementation_pr_urls_for_reports",
+ return_value={"report-1": _PR_URL},
+ ),
+ patch(
+ "products.signals.backend.implementation_pr.GitHubIntegration.first_for_team_repository",
+ return_value=github,
+ ) as mock_resolve,
+ ):
+ assert close_implementation_pr_for_report(self.team.id, "report-1", reason=reason) is True
+ mock_resolve.assert_called_once_with(self.team.id, "PostHog/posthog")
+ comment_body = github.comment_on_pull_request.call_args.args[2]
+ assert reason in comment_body
+ github.close_pull_request.assert_called_once_with("PostHog/posthog", 123)
+
+ def test_returns_false_and_skips_github_without_linked_pr(self):
+ with (
+ patch(
+ "products.signals.backend.implementation_pr.fetch_implementation_pr_urls_for_reports",
+ return_value={},
+ ),
+ patch(
+ "products.signals.backend.implementation_pr.GitHubIntegration.first_for_team_repository"
+ ) as mock_resolve,
+ ):
+ assert close_implementation_pr_for_report(self.team.id, "report-1") is False
+ mock_resolve.assert_not_called()
+
+ def test_returns_false_when_no_integration_resolves(self):
+ with (
+ patch(
+ "products.signals.backend.implementation_pr.fetch_implementation_pr_urls_for_reports",
+ return_value={"report-1": _PR_URL},
+ ),
+ patch(
+ "products.signals.backend.implementation_pr.GitHubIntegration.first_for_team_repository",
+ return_value=None,
+ ),
+ ):
+ assert close_implementation_pr_for_report(self.team.id, "report-1") is False
diff --git a/products/signals/backend/views.py b/products/signals/backend/views.py
index fb8eee7e6d1f..2df0b06c41a6 100644
--- a/products/signals/backend/views.py
+++ b/products/signals/backend/views.py
@@ -1442,6 +1442,9 @@ class SignalReportViewSet(
if hasattr(report, "prefetched_dismissal_artefacts"):
del report.prefetched_dismissal_artefacts
+ # A dismissal (transition into SUPPRESSED) closes the linked implementation PR — handled
+ # centrally by the post_save receiver (receivers.close_pr_when_report_dismissed), so this
+ # method doesn't special-case it. Restore/snooze to "potential" leaves the PR alone.
return SignalReportBulkStateOutcome.TRANSITIONED
@extend_schema(