: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(tasks): stop PostHog Code Slack bot from mis-firing PR follow-ups (#68966)
posthog[bot]dd9e107940e9
diff --git a/products/tasks/backend/temporal/process_task/activities/get_pr_context.py b/products/tasks/backend/temporal/process_task/activities/get_pr_context.pyindex f37886371206..e9ef6844d4b3 100644--- a/products/tasks/backend/temporal/process_task/activities/get_pr_context.py+++ b/products/tasks/backend/temporal/process_task/activities/get_pr_context.py@@ -1,3 +1,4 @@+import hashlibfrom dataclasses import dataclassfrom typing import Any@@ -29,12 +30,24 @@ class GetPrContextOutput:def compute_pr_fingerprint(pr: dict[str, Any]) -> str:- """Compute a fingerprint for a PR based on its URL and updated_at timestamp."""- import hashlib-- pr_url = pr.get("url", "")- updated_at = pr.get("updated_at", "")- fingerprint_source = f"{pr_url}|{updated_at}"+ """Fingerprint the actionable state of a PR for the CI follow-up loop.++ Keyed on the signals that mean the agent has real work to do — PR state, the+ CI check rollup, and whether changes are requested — never on ``updated_at``.+ GitHub bumps ``updated_at`` on any PR activity (comments, labels, reviews, the+ bot's own pushes), so hashing it re-poked the agent for every one of those long+ after the PR was opened.++ For the review signal we key on the boolean ``review_decision == "changes_requested"``+ rather than the raw decision: ``changes_requested`` is the only value that means+ the agent has code to fix, so an ``approved`` or ``review_required`` transition no+ longer re-pokes it for nothing. Net effect: the follow-up re-fires only when CI+ changes or a reviewer requests changes.+ """+ changes_requested = pr.get("review_decision") == "changes_requested"+ fingerprint_source = "|".join(+ [str(pr.get(key, "")) for key in ("url", "state", "ci_status")] + [str(changes_requested)]+ )return hashlib.sha256(fingerprint_source.encode()).hexdigest()@@ -89,7 +102,11 @@ def get_pr_context(input: GetPrContextInput) -> GetPrContextOutput | None:return Nonetry:- pull_request = github_integration.get_pull_request_from_url(pr_url) # Validate PR URL and permissions+ # Snapshot (GraphQL) over the plain REST fetch: it carries the CI rollup+ # and review decision the fingerprint keys on, so the follow-up loop can+ # tell a real CI change or a changes-requested review from noise like+ # comments, approvals, or thread churn.+ pull_request = github_integration.get_pull_request_snapshot(pr_url) # Validate PR URL and permissionsif not pull_request.get("success"):return Nonefingerprint = compute_pr_fingerprint(pull_request)diff --git a/products/tasks/backend/temporal/process_task/activities/post_slack_update.py b/products/tasks/backend/temporal/process_task/activities/post_slack_update.pyindex d24fb6a311d0..9e250149d29b 100644--- a/products/tasks/backend/temporal/process_task/activities/post_slack_update.py+++ b/products/tasks/backend/temporal/process_task/activities/post_slack_update.py@@ -132,12 +132,13 @@ def _post_pr_opened_notification_once(handler.delete_progress()return- # Resolve the reply target from the live mapping so the PR notification- # tags the current actor instead of the thread starter.+ # Tag the person who started the task. This fires asynchronously (often long+ # after the PR opened, once the CI follow-up loop settles), so tagging the+ # latest actor would ping whoever last happened to touch the thread — a casual+ # joiner — rather than the person who owns the work. Interactive replies still+ # tag the current speaker; only these milestone pings key on the starter.mapping = SlackThreadTaskMapping.objects.filter(task_run=task_run).first()- reply_target_slack_user_id = (- (mapping.latest_actor_slack_user_id or mapping.mentioning_slack_user_id) if mapping else None- )+ reply_target_slack_user_id = mapping.mentioning_slack_user_id if mapping else Nonehandler.post_pr_opened(pr_url, task_url, reply_target_slack_user_id=reply_target_slack_user_id)diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_get_pr_context.py b/products/tasks/backend/temporal/process_task/activities/tests/test_get_pr_context.pyindex 902a708e0e4e..31ee92682eb0 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_get_pr_context.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_get_pr_context.py@@ -5,6 +5,8 @@ from unittest.mock import MagicMock, patchfrom django.core.exceptions import ObjectDoesNotExist+from parameterized import parameterized+from products.tasks.backend.exceptions import TaskInvalidStateErrorfrom products.tasks.backend.temporal.process_task.activities.get_pr_context import (GetPrContextInput,@@ -20,19 +22,58 @@ GET_PR_CONTEXT_MODULE = "products.tasks.backend.temporal.process_task.activitiesclass TestComputePrFingerprint:def test_is_deterministic_for_same_input(self):- pr = {"url": "https://api.github.com/repos/org/repo/pulls/1", "updated_at": "2026-04-23T10:00:00Z"}+ pr = {"url": "https://github.com/org/repo/pull/1", "state": "open", "ci_status": "failing"}assert compute_pr_fingerprint(pr) == compute_pr_fingerprint(pr)- def test_changes_when_updated_at_changes(self):- base = {"url": "https://api.github.com/repos/org/repo/pulls/1"}- earlier = compute_pr_fingerprint({**base, "updated_at": "2026-04-23T10:00:00Z"})- later = compute_pr_fingerprint({**base, "updated_at": "2026-04-23T10:05:00Z"})- assert earlier != later+ def test_stable_when_only_updated_at_or_comments_change(self):+ # The bug: GitHub bumps updated_at on any activity (comments, labels, the bot's+ # own pushes), so hashing it re-poked the agent as noise. unresolved_threads is+ # in the same bucket — a review comment resolving or reopening a thread is noise,+ # not a reason to re-fire the follow-up. Actionable state is unchanged here, so+ # the fingerprint must not move.+ base = {"url": "https://github.com/org/repo/pull/1", "state": "open", "ci_status": "pending"}+ earlier = compute_pr_fingerprint(+ {**base, "updated_at": "2026-04-23T10:00:00Z", "comments": 0, "unresolved_threads": 0}+ )+ later = compute_pr_fingerprint(+ {**base, "updated_at": "2026-04-23T10:05:00Z", "comments": 3, "unresolved_threads": 2}+ )+ assert earlier == later++ @parameterized.expand(+ [+ ("ci_status", "pending", "failing"),+ ("review_decision", None, "changes_requested"),+ ("state", "open", "closed"),+ ]+ )+ def test_changes_when_actionable_field_changes(self, field, before, after):+ base = {"url": "https://github.com/org/repo/pull/1", "state": "open", "ci_status": "pending"}+ assert compute_pr_fingerprint({**base, field: before}) != compute_pr_fingerprint({**base, field: after})++ @parameterized.expand(+ [+ (None, "approved"),+ (None, "review_required"),+ ("approved", "review_required"),+ ("review_required", "approved"),+ ]+ )+ def test_stable_across_non_actionable_review_decisions(self, before, after):+ # Only changes_requested means the agent has code to fix. Keying on the raw+ # decision re-poked the agent on approval and the review_required shuffle —+ # common, non-actionable events. The fingerprint collapses review_decision to+ # the changes_requested boolean, so transitions among the other values (none of+ # which touch changes_requested) must not move it.+ base = {"url": "https://github.com/org/repo/pull/1", "state": "open", "ci_status": "pending"}+ assert compute_pr_fingerprint({**base, "review_decision": before}) == compute_pr_fingerprint(+ {**base, "review_decision": after}+ )def test_changes_when_url_changes(self):- base = {"updated_at": "2026-04-23T10:00:00Z"}- a = compute_pr_fingerprint({**base, "url": "https://api.github.com/repos/org/repo/pulls/1"})- b = compute_pr_fingerprint({**base, "url": "https://api.github.com/repos/org/repo/pulls/2"})+ base = {"state": "open", "ci_status": "failing"}+ a = compute_pr_fingerprint({**base, "url": "https://github.com/org/repo/pull/1"})+ b = compute_pr_fingerprint({**base, "url": "https://github.com/org/repo/pull/2"})assert a != bdef test_handles_missing_keys_without_raising(self):@@ -97,7 +138,7 @@ class TestGetPrContextActivity:test_task_run.save(update_fields=["output"])integration = MagicMock()- integration.get_pull_request_from_url.return_value = {"success": False, "error": "not found"}+ integration.get_pull_request_snapshot.return_value = {"success": False, "error": "not found"}ctx = self._ctx(run_id=str(test_task_run.id))with patch(f"{GET_PR_CONTEXT_MODULE}.get_github_integration", return_value=integration):@@ -109,13 +150,16 @@ class TestGetPrContextActivity:test_task_run.output = {"pr_url": pr_url}test_task_run.save(update_fields=["output"])- integration = MagicMock()- integration.get_pull_request_from_url.return_value = {+ snapshot = {"success": True,"url": pr_url,"state": "open",- "updated_at": "2026-04-23T10:00:00Z",+ "ci_status": "failing",+ "review_decision": None,+ "unresolved_threads": 1,}+ integration = MagicMock()+ integration.get_pull_request_snapshot.return_value = snapshotctx = self._ctx(run_id=str(test_task_run.id))with patch(f"{GET_PR_CONTEXT_MODULE}.get_github_integration", return_value=integration):@@ -124,8 +168,8 @@ class TestGetPrContextActivity:assert isinstance(result, GetPrContextOutput)assert result.pr_url == pr_urlassert result.pr_state == "open"- assert result.fingerprint == compute_pr_fingerprint({"url": pr_url, "updated_at": "2026-04-23T10:00:00Z"})- integration.get_pull_request_from_url.assert_called_once_with(pr_url)+ assert result.fingerprint == compute_pr_fingerprint(snapshot)+ integration.get_pull_request_snapshot.assert_called_once_with(pr_url)@pytest.mark.django_dbdef test_uses_user_github_integration_for_user_credentials(self, test_task_run):@@ -134,7 +178,7 @@ class TestGetPrContextActivity:test_task_run.save(update_fields=["output"])integration = MagicMock()- integration.get_pull_request_from_url.return_value = {+ integration.get_pull_request_snapshot.return_value = {"success": True,"url": pr_url,"state": "open",@@ -149,7 +193,7 @@ class TestGetPrContextActivity:assert isinstance(result, GetPrContextOutput)assert result.pr_url == pr_url- integration.get_pull_request_from_url.assert_called_once_with(pr_url)+ integration.get_pull_request_snapshot.assert_called_once_with(pr_url)@pytest.mark.django_dbdef test_defaults_pr_state_to_unknown_when_missing(self, test_task_run):@@ -158,7 +202,7 @@ class TestGetPrContextActivity:test_task_run.save(update_fields=["output"])integration = MagicMock()- integration.get_pull_request_from_url.return_value = {+ integration.get_pull_request_snapshot.return_value = {"success": True,"url": pr_url,"updated_at": "2026-04-23T10:00:00Z",@@ -178,7 +222,7 @@ class TestGetPrContextActivity:test_task_run.save(update_fields=["output"])integration = MagicMock()- integration.get_pull_request_from_url.side_effect = RuntimeError("GitHub exploded")+ integration.get_pull_request_snapshot.side_effect = RuntimeError("GitHub exploded")ctx = self._ctx(run_id=str(test_task_run.id))with patch(f"{GET_PR_CONTEXT_MODULE}.get_github_integration", return_value=integration):@@ -186,10 +230,10 @@ class TestGetPrContextActivity:self._run(ctx)@pytest.mark.django_db- def test_different_updated_at_yields_different_fingerprint(self, test_task_run):- # Drives the same invariant as test_ci_follow_up_fires_on_changed_fingerprint_and_persists- # at the activity level — if upstream GitHub reports a newer updated_at,- # the workflow must see a new fingerprint and re-fire CI follow-up.+ def test_ci_status_change_yields_different_fingerprint(self, test_task_run):+ # When CI actually transitions (pending -> failing) the workflow must see a new+ # fingerprint and re-fire the CI follow-up. The mirror of this — that a bare+ # updated_at bump does NOT change the fingerprint — is covered at the unit level.pr_url = "https://github.com/org/repo/pull/7"test_task_run.output = {"pr_url": pr_url}test_task_run.save(update_fields=["output"])@@ -197,20 +241,22 @@ class TestGetPrContextActivity:integration = MagicMock()ctx = self._ctx(run_id=str(test_task_run.id))- integration.get_pull_request_from_url.return_value = {+ integration.get_pull_request_snapshot.return_value = {"success": True,"url": pr_url,"state": "open",+ "ci_status": "pending","updated_at": "2026-04-23T10:00:00Z",}with patch(f"{GET_PR_CONTEXT_MODULE}.get_github_integration", return_value=integration):first = self._run(ctx)- integration.get_pull_request_from_url.return_value = {+ integration.get_pull_request_snapshot.return_value = {"success": True,"url": pr_url,"state": "open",- "updated_at": "2026-04-23T11:00:00Z",+ "ci_status": "failing",+ "updated_at": "2026-04-23T10:00:00Z",}with patch(f"{GET_PR_CONTEXT_MODULE}.get_github_integration", return_value=integration):second = self._run(ctx)diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.pyindex 0024fc38e42f..772048878285 100644--- a/products/tasks/backend/temporal/process_task/workflow.py+++ b/products/tasks/backend/temporal/process_task/workflow.py@@ -398,7 +398,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):self._pr_progress_emitted = Trueawait self._emit_progress("pr", "completed", "Opened pull request", "setup", detail=pr_context.pr_url)await self._emit_progress("ci", "in_progress", "Keeping CI green", "setup")- if pr_context.pr_state == "closed":+ if pr_context.pr_state in ("closed", "merged"):workflow.logger.info("PR is closed, skipping CI follow-up",extra={diff --git a/products/tasks/backend/temporal/task_management/workflow.py b/products/tasks/backend/temporal/task_management/workflow.pyindex b8c265731b0b..d604be997ab4 100644--- a/products/tasks/backend/temporal/task_management/workflow.py+++ b/products/tasks/backend/temporal/task_management/workflow.py@@ -907,7 +907,7 @@ class TaskManagementWorkflow(PostHogWorkflow):)if not pr_context:return CIFollowUpDecision.NO_PR- if pr_context.pr_state == "closed":+ if pr_context.pr_state in ("closed", "merged"):workflow.logger.info("task_management_ci_skipped_pr_closed",run_id=self._run_id,diff --git a/products/tasks/backend/tests/test_post_slack_update.py b/products/tasks/backend/tests/test_post_slack_update.pyindex 565b10774ff9..254283f1813d 100644--- a/products/tasks/backend/tests/test_post_slack_update.py+++ b/products/tasks/backend/tests/test_post_slack_update.py@@ -191,7 +191,10 @@ class TestPostSlackUpdate(TestCase):state={},)mock_task_run_class.objects.select_related.return_value.get.return_value = mock_run- # Reply target now resolves from the live mapping, not the workflow context.+ # This milestone ping tags the task starter, not whoever last touched the+ # thread: latest_actor is a casual joiner here, and this update can fire long+ # after the PR opened (once the CI follow-up loop settles), so tagging them+ # would spam the wrong person.mock_mapping = MagicMock()mock_mapping.latest_actor_slack_user_id = "U123"mock_mapping.mentioning_slack_user_id = "U_ORIG"@@ -210,7 +213,7 @@ class TestPostSlackUpdate(TestCase):mock_post_pr_opened.assert_called_once_with("https://github.com/org/repo/pull/1","http://localhost:8000/project/1/tasks/10?runId=run-1",- reply_target_slack_user_id="U123",+ reply_target_slack_user_id="U_ORIG",)mock_update_reaction.assert_called_once_with("eyes")mock_post_progress.assert_not_called()