: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
feat(signals): attribute inbox status changes and pr closes to an actor (#114701)
posthog[bot]c70345c7781f
diff --git a/posthog/github/attribution.py b/posthog/github/attribution.pyindex 92f030a64c4c..7d2299c49d3f 100644--- a/posthog/github/attribution.py+++ b/posthog/github/attribution.py@@ -74,3 +74,20 @@ def _merged_by_attribution(payload: dict, team_id: int) -> tuple[dict, str | Nonif distinct_id is not None:properties["pr_merged_by_distinct_id"] = distinct_idreturn properties, distinct_id+++def _closed_by_attribution(payload: dict, team_id: int) -> dict:+ """Identity of the GitHub user who closed the PR without a merge, from the delivery's `sender`.++ The event keeps the caller's default actor, because the closer is often the GitHub App itself+ (a dismissed report closes its PR), which never resolves to an org member.+ """+ sender = payload.get("sender") or {}+ login = sender.get("login")+ if not login:+ return {}+ properties: dict = {"pr_closed_by_login": login, "pr_closed_by_id": sender.get("id")}+ distinct_id = _resolve_github_login_distinct_id(login, team_id)+ if distinct_id is not None:+ properties["pr_closed_by_distinct_id"] = distinct_id+ return propertiesdiff --git a/posthog/github/pull_request_events.py b/posthog/github/pull_request_events.pyindex 6fff400f7765..d13f59e35779 100644--- a/posthog/github/pull_request_events.py+++ b/posthog/github/pull_request_events.py@@ -9,7 +9,7 @@ import posthoganalyticsfrom posthog.dataclasses import frozenfrom posthog.event_usage import groups-from posthog.github.attribution import _merged_by_attribution, _resolve_github_login_distinct_id+from posthog.github.attribution import _closed_by_attribution, _merged_by_attribution, _resolve_github_login_distinct_idfrom posthog.github.installations import _resolve_external_teamfrom posthog.github.metrics import GitHubWebhookAnalyticsEvent, observe_github_webhook_pr_event_dropped@@ -142,6 +142,8 @@ def capture_pr_event(merger_properties, merger_distinct_id = _merged_by_attribution(payload, attribution.team_id)properties.update(merger_properties)distinct_id = merger_distinct_id or distinct_id+ elif event == "pr_closed":+ properties.update(_closed_by_attribution(payload, attribution.team_id))elif event == "pr_reviewed":review = payload.get("review") or {}reviewer = review.get("user") or {}diff --git a/posthog/github/test/test_pull_request_events.py b/posthog/github/test/test_pull_request_events.pyindex f63134b805f5..954dc6f4d8dd 100644--- a/posthog/github/test/test_pull_request_events.py+++ b/posthog/github/test/test_pull_request_events.py@@ -36,6 +36,7 @@ class TestProductPullRequestAttribution(SimpleTestCase):"body": "private PR content",},"review": {"id": 90, "state": "approved", "user": {"login": "reviewer", "type": "User"}},+ "sender": {"login": "reviewer", "id": 5},}attribution = PullRequestAttribution(source="wizard",@@ -74,6 +75,11 @@ class TestProductPullRequestAttribution(SimpleTestCase):self.assertEqual(properties["pr_url"], pr_url)self.assertNotIn("task_id", properties)self.assertIsNone(properties["pr_body"])+ closer = {"pr_closed_by_login": "reviewer", "pr_closed_by_id": 5, "pr_closed_by_distinct_id": "reviewer-id"}+ self.assertEqual(+ {key: properties.get(key) for key in closer},+ closer if event == "pr_closed" else dict.fromkeys(closer),+ )suffix = ":90" if event == "pr_reviewed" else ""self.assertEqual(kwargs["uuid"],diff --git a/products/signals/backend/receivers.py b/products/signals/backend/receivers.pyindex 002db5bcca33..150d449f6fdd 100644--- a/products/signals/backend/receivers.py+++ b/products/signals/backend/receivers.py@@ -21,7 +21,9 @@ import structlogimport posthoganalyticsfrom posthog.event_usage import groups+from posthog.models.user import User+from products.signals.backend.artefact_attribution import ArtefactAttributionfrom products.signals.backend.models import SignalReport, SignalReportArtefactfrom products.signals.backend.report_embeddings import (emit_report_embeddings,@@ -265,6 +267,41 @@ def capture_prior_state()+def _transition_actor(instance: SignalReport) -> ArtefactAttribution | None:+ """Who asked for this transition, when the caller set `_transition_actor` before the save."""+ return getattr(instance, "_transition_actor", None)+++def _transition_actor_user(instance: SignalReport) -> User | None:+ """The actor's already-loaded user, when the caller set `_transition_actor_user` before the save."""+ return getattr(instance, "_transition_actor_user", None)+++def _actor_properties(actor: ArtefactAttribution | None, actor_user: User | None = None) -> dict[str, Any]:+ """Actor properties for the status-change label. A transition with no caller-set actor is `system`."""+ actor = actor or ArtefactAttribution.system()+ properties: dict[str, Any] = {+ "actor_kind": actor.kind,+ "actor_user_uuid": None,+ "actor_distinct_id": None,+ "actor_agent": actor.agent_name,+ "actor_task_id": actor.task_id,+ }+ if actor.user_id is None:+ return properties+ # The bulk-state endpoint transitions up to 100 reports for one actor, so it passes the request+ # user to skip a repeat lookup per report.+ if actor_user is not None and actor_user.id == actor.user_id:+ properties["actor_user_uuid"] = str(actor_user.uuid)+ properties["actor_distinct_id"] = actor_user.distinct_id+ return properties+ user = User.objects.filter(id=actor.user_id).values("uuid", "distinct_id").first()+ if user is not None:+ properties["actor_user_uuid"] = str(user["uuid"])+ properties["actor_distinct_id"] = user["distinct_id"]+ return properties++def _status_changed_on_this_save(instance: SignalReport,*,@@ -335,7 +372,8 @@ def close_pr_when_report_dismissed(# The person who asked for this transition, when a caller set it before the save. GitHub# credits the App for the close, so the comment left beside it is the only place they appear.# Absent on every automated transition (PR webhook, judges, temporal), which stays unattributed.- actor_user_id = getattr(instance, "_transition_actor_user_id", None)+ actor = _transition_actor(instance)+ actor_user_id = actor.user_id if actor is not None else Nonereason = _pr_close_reason(instance,created=created,@@ -850,6 +888,8 @@ def capture_status_change_analytics(# caller supplied it — a PR-merge resolve from the tasks webhook writes none, and must not pick# up an unrelated earlier reason that happens to fall inside the freshness window.wrote_dismissal_feedback = bool(getattr(instance, "_wrote_dismissal_feedback", False))+ actor = _transition_actor(instance)+ actor_user = _transition_actor_user(instance)def _capture() -> None:try:@@ -874,6 +914,7 @@ def capture_status_change_analytics(properties={**properties,"previous_status": previous_status,+ **_actor_properties(actor, actor_user),**_classification_snapshot(report_id,include_dismissal=wrote_dismissal_feedbackdiff --git a/products/signals/backend/report_actions.py b/products/signals/backend/report_actions.pyindex 8b4b13662a26..0053fa6e1cd3 100644--- a/products/signals/backend/report_actions.py+++ b/products/signals/backend/report_actions.py@@ -49,14 +49,13 @@ def suppress_report_from_slack()return False- # Name the clicker in the comments the receiver leaves on GitHub, when the Slack identity- # resolved to a PostHog user. An unresolved click stays unattributed.- report._transition_actor_user_id = user_id # type: ignore[attr-defined]- report.save(update_fields=updated_fields)# Attribute to the resolved PostHog user when the caller mapped the Slack click to one;- # fall back to system if not. Either way the slack_user_id stays in the content as the+ # fall back to system if not. The receivers name this actor in the GitHub comments and in+ # the status-change label. Either way the slack_user_id stays in the content as the# Slack-side trace.attribution = ArtefactAttribution.from_user(user_id) if user_id is not None else ArtefactAttribution.system()+ report._transition_actor = attribution # type: ignore[attr-defined]+ report.save(update_fields=updated_fields)SignalReportArtefact.append_dismissal(team_id=team_id,report_id=str(report.id),diff --git a/products/signals/backend/report_merge.py b/products/signals/backend/report_merge.pyindex 38bb9f502fd7..2f6fb06aabff 100644--- a/products/signals/backend/report_merge.py+++ b/products/signals/backend/report_merge.py@@ -314,7 +314,7 @@ def _dismiss_as_merged("""updated_fields = source.transition_to(SignalReport.Status.SUPPRESSED)source._wrote_dismissal_feedback = True # type: ignore[attr-defined]- source._transition_actor_user_id = attribution.user_id # type: ignore[attr-defined]+ source._transition_actor = attribution # type: ignore[attr-defined]source.save(update_fields=updated_fields)note = f"Merged into report {survivor.id}."diff --git a/products/signals/backend/test/test_dismissal_pr_close.py b/products/signals/backend/test/test_dismissal_pr_close.pyindex 5b2257994292..0fb548a2ab86 100644--- a/products/signals/backend/test/test_dismissal_pr_close.py+++ b/products/signals/backend/test/test_dismissal_pr_close.py@@ -77,7 +77,7 @@ class TestClosePrWhenReportDismissed(BaseTest):):report = self._create_report(report_status=source_status)if with_actor:- report._transition_actor_user_id = self.user.id # type: ignore[attr-defined]+ report._transition_actor = ArtefactAttribution.from_user(self.user.id) # type: ignore[attr-defined]with patch("products.signals.backend.tasks.close_dismissed_report_pr") as mock_task:self._save_transition(report, new_status, **transition_kwargs)mock_task.delay.assert_called_once_with(diff --git a/products/signals/backend/test/test_signal_report_api.py b/products/signals/backend/test/test_signal_report_api.pyindex 7c1b7b6e0c1e..b97491b09b6c 100644--- a/products/signals/backend/test/test_signal_report_api.py+++ b/products/signals/backend/test/test_signal_report_api.py@@ -3623,6 +3623,31 @@ class TestSignalReportBulkStateAPI(APIBaseTest):other_teams_report.refresh_from_db()assert other_teams_report.status == SignalReport.Status.READY+ def test_bulk_status_labels_reuse_request_user_without_actor_lookups(self):+ ids = [str(self._create_report().id) for _ in range(3)]++ with patch("products.signals.backend.receivers.posthoganalytics.capture") as mock_capture:+ with CaptureQueriesContext(connection) as ctx, self.captureOnCommitCallbacks(execute=True):+ response = self._post({"ids": ids, "state": "suppressed"})++ assert response.status_code == status.HTTP_200_OK, response.json()+ labels = [+ call.kwargs["properties"]+ for call in mock_capture.call_args_list+ if call.kwargs["event"] == "signal_report_status_changed"+ ]+ assert len(labels) == 3+ for label in labels:+ assert label["actor_kind"] == "user"+ assert label["actor_user_uuid"] == str(self.user.uuid)+ assert label["actor_distinct_id"] == self.user.distinct_id+ actor_lookups = [+ query+ for query in ctx.captured_queries+ if query["sql"].startswith('SELECT "posthog_user"."uuid" AS "uuid", "posthog_user"."distinct_id"')+ ]+ assert actor_lookups == []+def test_bulk_deduplicates_ids_preserving_order(self):first = self._create_report()second = self._create_report()diff --git a/products/signals/backend/test/test_status_change_telemetry.py b/products/signals/backend/test/test_status_change_telemetry.pyindex b058885f87c8..e22d5ccc0680 100644--- a/products/signals/backend/test/test_status_change_telemetry.py+++ b/products/signals/backend/test/test_status_change_telemetry.py@@ -9,6 +9,7 @@ from django.utils import timezonefrom parameterized import parameterized+from products.signals.backend.artefact_attribution import ArtefactAttributionfrom products.signals.backend.models import SignalReport, SignalReportArtefact@@ -52,6 +53,40 @@ class TestCaptureStatusChangeAnalytics(BaseTest):assert kwargs["properties"]["signal_count"] == 3assert kwargs["properties"]["total_weight"] == 2.5+ @parameterized.expand(+ [+ ("pipeline_without_actor", None, "system", False, None, None),+ ("user", "user", "user", True, None, None),+ ("external_agent", "agent", "agent", True, "codex", None),+ ("internal_task", "task", "task", False, None, "11111111-1111-1111-1111-111111111111"),+ ]+ )+ def test_label_carries_transition_actor(+ self, _name, actor_kind, expected_kind, expects_user, expected_agent, expected_task_id+ ):+ actors = {+ None: None,+ "user": ArtefactAttribution.from_user(self.user.id),+ "agent": ArtefactAttribution.from_agent(self.user.id, "codex"),+ "task": ArtefactAttribution.from_task("11111111-1111-1111-1111-111111111111"),+ }+ report = self._create_report()+ if actors[actor_kind] is not None:+ report._transition_actor = actors[actor_kind] # type: ignore[attr-defined]+ with patch("products.signals.backend.receivers.posthoganalytics.capture") as mock_capture:+ with self.captureOnCommitCallbacks(execute=True):+ report.save(update_fields=report.transition_to(SignalReport.Status.SUPPRESSED))+ kwargs = mock_capture.call_args.kwargs+ assert kwargs["distinct_id"] == str(self.team.uuid)+ actor_properties = {key: value for key, value in kwargs["properties"].items() if key.startswith("actor_")}+ assert actor_properties == {+ "actor_kind": expected_kind,+ "actor_user_uuid": str(self.user.uuid) if expects_user else None,+ "actor_distinct_id": self.user.distinct_id if expects_user else None,+ "actor_agent": expected_agent,+ "actor_task_id": expected_task_id,+ }+@parameterized.expand([("dismissal_includes_fresh_reason", SignalReport.Status.SUPPRESSED, False, "wontfix_irrelevant"),diff --git a/products/signals/backend/views.py b/products/signals/backend/views.pyindex 47952c090e0b..d29f65a90dfc 100644--- a/products/signals/backend/views.py+++ b/products/signals/backend/views.py@@ -2683,7 +2683,7 @@ class SignalReportViewSet(# Hide the report from the list immediately while signal deletion continues asynchronously.updated_fields = report.transition_to(SignalReport.Status.DELETED)- report._transition_actor_user_id = self._request_attribution().user_id # type: ignore[attr-defined]+ report._transition_actor = self._request_attribution() # type: ignore[attr-defined]report.save(update_fields=updated_fields)return Response({"status": "deletion_started", "report_id": report_id}, status=status.HTTP_202_ACCEPTED)@@ -3310,10 +3310,11 @@ class SignalReportViewSet(# superseded and the receiver closes it. The PR-merge webhook resolves through# transition_to directly and never sets this, so a merged PR is left alone.report._close_pr_on_resolve = target_status == SignalReport.Status.RESOLVED # type: ignore[attr-defined]- # Name the caller in the comments the receiver leaves on the linked pull request- # and tracker issue. An external agent keeps its user principal, so it names the- # person who ran it rather than nobody.- report._transition_actor_user_id = self._request_attribution().user_id # type: ignore[attr-defined]+ # Name the caller in the status-change label and in the comments the receiver leaves+ # on the linked pull request and tracker issue. An external agent keeps its user+ # principal, so it names the person who ran it rather than nobody.+ report._transition_actor = self._request_attribution() # type: ignore[attr-defined]+ report._transition_actor_user = self.request.user # type: ignore[attr-defined]# Read under the row lock, so two concurrent dismissals count as one new suppression.report._newly_suppressed = target_status == SignalReport.Status.SUPPRESSED # type: ignore[attr-defined]@@ -3613,7 +3614,7 @@ class SignalReportViewSet(resolved_via_merged_pr = report.status == SignalReport.Status.RESOLVED and pr_mergedif report.status != SignalReport.Status.SUPPRESSED and not resolved_via_merged_pr:updated_fields = report.transition_to(SignalReport.Status.SUPPRESSED)- report._transition_actor_user_id = attribution.user_id # type: ignore[attr-defined]+ report._transition_actor = attribution # type: ignore[attr-defined]report.save(update_fields=updated_fields)SignalReportArtefact.append_dismissal(team_id=self.team.id,diff --git a/products/signals/dags/inbox_ranking/README.md b/products/signals/dags/inbox_ranking/README.mdindex 98ac6e730038..f294ab8aca19 100644--- a/products/signals/dags/inbox_ranking/README.md+++ b/products/signals/dags/inbox_ranking/README.md@@ -49,6 +49,7 @@ The first four are report grain and land in one table. `inbox_signal_embeddings`- **The `inserted_at` bound does not cover a re-embedded rendering.** The source replaces on a key that includes the rendering and the document id, so a partition rebuilt _later_ for an earlier day finds only the newer row, whose `inserted_at` is past the cutoff, and the report reads as having no vector that day. That loses coverage and never leaks a future vector. A forward run carries the same loss over a shorter window: the schedule fires at 02:30 UTC for the previous day, so the query starts at least 2.5 hours after the cutoff, and the title snapshot runs after the join, which makes its window the wider of the two. A partition before `title_v1` emission shipped holds zero rows, which is written as an empty Parquet with the full schema rather than skipped.- Report-state mutability reaches **inclusion**, not just feature values: `promoted_at` is cleared on suppression and snooze, so a report promoted before the cutoff and suppressed after it leaves the spine unless a label event referenced it before the cutoff. Forward runs see this only for the 2.5 hours between the cutoff and the schedule; backfills see the full accumulated effect. Deriving the spine from immutable promotion history (`signal_report_status_changed` carries `promoted_at`) is the v2 fix.- **The server-side action counts read current artefact rows**, bounded by `created_at < snapshot_end`. A report merge moves the source's notes and linked PRs to the survivor and keeps their `created_at`, and a note can be deleted. A partition rebuilt after either change gives that action to the survivor, or loses it. Claims and Slack discussions stay on the source report. Forward runs see this only for the 2.5 hours between the cutoff and the schedule.+- **`signal_report_status_changed` names the actor of each transition.** `actor_kind` is `user`, `agent`, `task` or `system`, and `actor_user_uuid`, `actor_distinct_id`, `actor_agent` and `actor_task_id` identify it. A transition no caller attributed (the pipeline, the PR-merge webhook, an unresolved Slack click) is `system`. The event `distinct_id` stays the team uuid. Events before this change carry no actor keys, so a per-user feature must treat a missing `actor_kind` as unknown, not as `system`.### Signal-grain partitions