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.

fix(signals): filter inbox pr reports by team before joining (#108583)

posthog[bot]2416d4d1174e
diff --git a/products/signals/backend/implementation_pr.py b/products/signals/backend/implementation_pr.py
index 243fd23f56aa..bc95e3f8091e 100644
--- a/products/signals/backend/implementation_pr.py
+++ b/products/signals/backend/implementation_pr.py
@@ -4,11 +4,12 @@ import re
from collections.abc import Callable
from dataclasses import replace
from datetime import datetime
-from typing import TYPE_CHECKING, Literal
+from typing import TYPE_CHECKING, Any, Literal
from uuid import NAMESPACE_URL, uuid5
from django.conf import settings
-from django.db.models import Q
+from django.contrib.postgres.expressions import ArraySubquery
+from django.db.models import F, Lookup, Q
import structlog
@@ -36,6 +37,9 @@ from products.tasks.backend.facade import api as tasks_facade
logger = structlog.get_logger(__name__)
if TYPE_CHECKING:
+ from django.db.backends.base.base import BaseDatabaseWrapper
+ from django.db.models.sql.compiler import SQLCompiler
+
from posthog.models.user import User
# A report in one of these statuses is finished with its pull request. Anything else still holds
@@ -52,14 +56,20 @@ _PULL_REQUEST_URL_ARRAY_PATTERN = rf'"{_PULL_REQUEST_URL_BODY}([/?#][^"]*)?"'
_PR_BEARING_LEGACY_TASK_RELATIONSHIPS = (TASK_RUN_TYPE_IMPLEMENTATION, TASK_RUN_TYPE_DISCUSSION)
+class _EqualsAny(Lookup):
+ """`lhs = ANY(rhs)`, the SQL form an `ArraySubquery` needs on the right side."""
+
+ def as_sql(self, compiler: SQLCompiler, connection: BaseDatabaseWrapper) -> tuple[str, tuple[Any, ...]]:
+ lhs, lhs_params = self.process_lhs(compiler, connection)
+ rhs, rhs_params = self.process_rhs(compiler, connection)
+ return f"{lhs} = ANY({rhs})", (*lhs_params, *rhs_params)
+
+
def implementation_pr_report_filter(*, team_id: int, active_only: bool = False) -> Q:
- assignment_pr = Q(assignment__team_id=team_id, assignment__pr_url__regex=_PULL_REQUEST_URL_PATTERN)
- pull_request_links = SignalReportArtefact.objects.filter(
- team_id=team_id,
- type=SignalReportArtefact.ArtefactType.PULL_REQUEST,
- pull_request__team_id=team_id,
- pull_request__url__regex=_PULL_REQUEST_URL_PATTERN,
- )
+ # Every branch is a team-scoped subquery on the report id. A join through `assignment` or
+ # `pull_request` lets the planner scan every team's rows before it applies the team scope.
+ assignments = SignalReportAssignment.all_teams.filter(team_id=team_id, pr_url__regex=_PULL_REQUEST_URL_PATTERN)
+ pull_requests = SignalReportPullRequest.objects.for_team(team_id).filter(url__regex=_PULL_REQUEST_URL_PATTERN)
task_ids = tasks_facade.task_ids_with_pr_url_subquery(
team_id,
pr_bearing_task_run_filter(),
@@ -91,16 +101,22 @@ def implementation_pr_report_filter(*, team_id: int, active_only: bool = False)
SignalReportAssignment.PrState.DRAFT,
SignalReportAssignment.PrState.OPEN,
]
- assignment_pr &= Q(assignment__pr_merged=False) & (
- Q(assignment__pr_state__isnull=True)
- | Q(assignment__pr_state="")
- | Q(assignment__pr_state__in=active_states)
+ assignments = assignments.filter(
+ Q(pr_merged=False) & (Q(pr_state__isnull=True) | Q(pr_state="") | Q(pr_state__in=active_states))
)
- pull_request_links = pull_request_links.filter(pull_request__state__in=active_states)
+ pull_requests = pull_requests.filter(state__in=active_states)
+
+ # `pull_request_id IN (subquery)` keeps the cross-team merge join. Only the array form makes
+ # Postgres probe `signals_artefact_pr_report_idx` with this team's PR ids.
+ pull_request_links = SignalReportArtefact.objects.filter(
+ _EqualsAny(F("pull_request_id"), ArraySubquery(pull_requests.values("id"))),
+ team_id=team_id,
+ type=SignalReportArtefact.ArtefactType.PULL_REQUEST,
+ ).values("report_id")
return (
- assignment_pr
- | Q(id__in=pull_request_links.values("report_id"))
+ Q(id__in=assignments.values("report_id"))
+ | Q(id__in=pull_request_links)
| Q(id__in=task_run_artefacts)
| Q(id__in=legacy_tasks)
| Q(id__in=assignment_tasks)
diff --git a/products/signals/backend/test/test_signal_report_api.py b/products/signals/backend/test/test_signal_report_api.py
index d05f4f6e0975..4b20606ef7be 100644
--- a/products/signals/backend/test/test_signal_report_api.py
+++ b/products/signals/backend/test/test_signal_report_api.py
@@ -1571,8 +1571,11 @@ class TestSignalReportListAPI(APIBaseTest):
]
assert filter_sql
for sql in filter_sql:
- # Django aliases the task, legacy artefact, and assignment association tables as V0.
- assert sql.count(f'V0."team_id" = {self.team.id}') == 3
+ # Django aliases the PR artefact, task-run artefact, legacy task, and assignment task tables as V0.
+ assert sql.count(f'V0."team_id" = {self.team.id}') == 4
+ # A join to the assignment or pull request table lets the planner scan every team's rows first.
+ assert "JOIN" not in sql
+ assert '"pull_request_id" = ANY((ARRAY(SELECT' in sql
def test_filter_has_implementation_pr_absent_returns_all(self):
report_with_pr = self._create_report(title="Report with PR")
diff --git a/products/signals/backend/test/test_signal_report_assignment_api.py b/products/signals/backend/test/test_signal_report_assignment_api.py
index a6fa1fc76a18..87c973cf20fb 100644
--- a/products/signals/backend/test/test_signal_report_assignment_api.py
+++ b/products/signals/backend/test/test_signal_report_assignment_api.py
@@ -678,6 +678,30 @@ class TestSignalReportAssignmentAPI(APIBaseTest):
pr_number=123,
pr_state=SignalReportAssignment.PrState.OPEN,
)
+ merged_assignment = self._create_report(title="Merged assignment")
+ SignalReportAssignment.all_teams.create(
+ team=self.team,
+ report=merged_assignment,
+ pr_url="https://github.com/PostHog/posthog/pull/124",
+ repository="posthog/posthog",
+ pr_number=124,
+ pr_state=SignalReportAssignment.PrState.MERGED,
+ pr_merged=True,
+ )
+ linked = {}
+ for number, state in [(125, SignalReportPullRequest.State.OPEN), (126, SignalReportPullRequest.State.MERGED)]:
+ report = self._create_report(title=f"Linked {state}")
+ pr = SignalReportPullRequest.objects.create(
+ team=self.team,
+ repository="posthog/posthog",
+ number=number,
+ url=f"https://github.com/PostHog/posthog/pull/{number}",
+ state=state,
+ )
+ SignalReportArtefact.objects.create(
+ team=self.team, report=report, type=SignalReportArtefact.ArtefactType.PULL_REQUEST, pull_request=pr
+ )
+ linked[state] = report
response = self.client.get(self._list_url(unclaimed="true"))
@@ -686,6 +710,9 @@ class TestSignalReportAssignmentAPI(APIBaseTest):
assert str(unclaimed.id) in ids
assert str(claimed.id) not in ids
assert str(in_review.id) not in ids
+ assert str(merged_assignment.id) in ids
+ assert str(linked[SignalReportPullRequest.State.OPEN].id) not in ids
+ assert str(linked[SignalReportPullRequest.State.MERGED].id) in ids
def test_assignee_me_matches_exact_external_agent(self):
mine = self._create_report(title="Mine")