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.

perf(signals): decorrelate has_implementation_pr inbox filter (#66112)

Oliver Brownea9d6566b998a
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.py
index ea8ee8c3e1dc..dfea2e574cda 100644
--- a/products/signals/backend/models.py
+++ b/products/signals/backend/models.py
@@ -610,6 +610,23 @@ class SignalReport(UUIDModel):
legacy_report_ids = SignalReportTask.objects.filter(task_id=task_id).values("report_id")
return models.Q(id__in=artefact_report_ids) | models.Q(id__in=legacy_report_ids)
+ @staticmethod
+ def reports_for_task_ids_filter(task_ids: Any) -> "models.Q":
+ """`reports_for_task_filter` widened to a *set* of tasks: a `Q` on `SignalReport.id` matching
+ the reports associated with any task in `task_ids` (a collection or, preferably, a `task_id`
+ subquery), unified across the `task_run` artefact log and the legacy `SignalReportTask` gate
+ rows.
+
+ Lets a per-report correlated `Exists` over `tasks.TaskRun` be *decorrelated*: drive off the
+ small task set (e.g. tasks that produced a PR) and map it to reports here via the indexed
+ `task_id` columns, instead of probing the runs once per candidate report.
+ """
+ artefact_report_ids = SignalReportArtefact.objects.filter(
+ type=SignalReportArtefact.ArtefactType.TASK_RUN, task_id__in=task_ids
+ ).values("report_id")
+ legacy_report_ids = SignalReportTask.objects.filter(task_id__in=task_ids).values("report_id")
+ return models.Q(id__in=artefact_report_ids) | models.Q(id__in=legacy_report_ids)
+
class SignalEmissionRecord(UUIDModel):
"""Tracks which source records have been emitted as signals.
diff --git a/products/signals/backend/views.py b/products/signals/backend/views.py
index c3d8b054e036..ed0ea4be33a1 100644
--- a/products/signals/backend/views.py
+++ b/products/signals/backend/views.py
@@ -666,21 +666,20 @@ class SignalReportViewSet(
type=SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS,
).filter(~has_newer)
- def _implementation_pr_exists_subquery(self):
- # EXISTS over the latest implementation TaskRun that carries a non-empty
- # `pr_url`. Mirrors `_annotate_implementation_pr_url`, but as a boolean
- # EXISTS so it can be used as a filter (and counted) without the
- # per-row PR-url annotation, which the list action skips for performance.
- return tasks_facade.task_run_pr_url_exists_subquery(
- SignalReport.associated_task_runs_filter(OuterRef(OuterRef("id"))),
- )
+ def _implementation_pr_report_filter(self):
+ # Reports with a shipped implementation PR, as a `Q` on `SignalReport.id`. Decorrelated:
+ # starts from the (small, index-backed) set of this team's tasks whose runs carry a non-empty
+ # `pr_url` and maps them to reports via the indexed `task_id` columns — instead of a correlated
+ # `Exists` over `tasks.TaskRun` evaluated once per candidate report (which made the inbox
+ # PR-tab count scan the whole `ready` set per PR'd run).
+ return SignalReport.reports_for_task_ids_filter(tasks_facade.task_ids_with_pr_url_subquery(self.team.id))
def _apply_signal_report_implementation_pr_filter(self, queryset):
# `has_implementation_pr=true|false` filters reports by whether a shipped
# implementation PR exists. Lets the inbox count PR reports (the "Pull
- # requests" tab) with a cheap `limit=1` count query instead of paging the
- # whole list and filtering client-side. Absent or empty param leaves the
- # list unchanged; an unrecognized value is a 400.
+ # requests" tab) with a cheap count query instead of paging the whole list
+ # and filtering client-side. Absent or empty param leaves the list
+ # unchanged; an unrecognized value is a 400.
raw = self.request.query_params.get("has_implementation_pr")
if raw is None or not raw.strip():
return queryset
@@ -693,8 +692,8 @@ class SignalReportViewSet(
raise serializers.ValidationError(
{"has_implementation_pr": f"Invalid value: {raw!r}. Allowed: true, false."}
)
- pr_exists = self._implementation_pr_exists_subquery()
- return queryset.filter(pr_exists if wants_pr else ~pr_exists)
+ pr_filter = self._implementation_pr_report_filter()
+ return queryset.filter(pr_filter) if wants_pr else queryset.exclude(pr_filter)
def _apply_signal_report_suggested_reviewer_filter(self, queryset):
suggested_reviewer_filter = self.request.query_params.get("suggested_reviewers")
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 71e3f11c3c43..b5e7a37b7c0a 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -18,11 +18,11 @@ Functions that bridge to those heavy surfaces import them lazily inside the func
import logging
from collections.abc import Iterable, Sequence
from datetime import datetime, timedelta
-from typing import Literal
+from typing import Any, Literal
from uuid import UUID, uuid4
from django.db import transaction
-from django.db.models import CharField, Count, Exists, F, Min, OuterRef, Q, Subquery
+from django.db.models import CharField, Count, F, Min, OuterRef, Q, QuerySet, Subquery
from django.db.models.fields.json import KeyTextTransform
from django.utils import timezone as django_timezone
@@ -168,9 +168,9 @@ __all__ = [
"start_task_run",
"task_accessible_for_run_view",
"task_exists",
+ "task_ids_with_pr_url_subquery",
"task_run_has_slack_mapping",
"task_run_is_terminal",
- "task_run_pr_url_exists_subquery",
"task_visible",
"update_sandbox_environment",
"update_task",
@@ -458,23 +458,29 @@ def get_latest_pr_url_by_task(task_ids: Iterable[str | UUID]) -> dict[str, str]:
return {str(row["task_id"]): row["output_pr_url_text"] for row in rows if row["output_pr_url_text"]}
-def task_run_pr_url_exists_subquery(*conditions: Q, **task_run_filter) -> Exists:
- """``Exists`` over runs matching the supplied correlation that produced a non-empty output.pr_url.
+def task_ids_with_pr_url_subquery(team_id: int) -> QuerySet[TaskRun, Any]:
+ """A ``values('task_id')`` queryset of ``team_id``'s tasks that produced a non-empty ``output.pr_url``.
- The caller supplies the report→run correlation as keyword lookups (e.g.
- ``task__signal_report_tasks__report_id=OuterRef("id")``) and/or positional ``Q`` objects (e.g.
- an ``OR`` of two ``task_id__in`` subqueries the caller builds). Returns a query expression to
- embed in the caller's queryset — no ORM instances cross the boundary, and the tasks facade
- stays free of the caller's domain.
+ For embedding in a caller's ``task_id__in=...`` lookup so the report→PR correlation can be
+ *decorrelated*: instead of a per-report ``Exists`` over runs, the caller drives off this small,
+ index-backed set (served by the partial ``task_run_output_pr_url_idx``) and joins outward to its
+ own report-association tables. Returns a query expression — no ORM instances cross the boundary.
+
+ Scoped to ``team_id`` so the set stays bounded to the request's tenant rather than scanning every
+ team's PR-bearing runs — associated runs are always same-team, so this drops no valid matches.
"""
- return Exists(
- TaskRun.objects.filter(*conditions, output__pr_url__isnull=False, **task_run_filter).exclude(output__pr_url="")
+ return (
+ TaskRun.objects.filter(team_id=team_id, output__pr_url__isnull=False)
+ .exclude(output__pr_url="")
+ .values("task_id")
)
def latest_task_run_pr_url_subquery(*conditions: Q, **task_run_filter) -> Subquery:
"""``Subquery`` of the latest non-empty output.pr_url for runs matching the supplied correlation
- (keyword lookups and/or positional ``Q`` objects — see ``task_run_pr_url_exists_subquery``)."""
+ (keyword lookups and/or positional ``Q`` objects). Returns a query expression to embed in the
+ caller's queryset — no ORM instances cross the boundary, and the tasks facade stays free of the
+ caller's domain."""
return Subquery(
TaskRun.objects.filter(*conditions, output__pr_url__isnull=False, **task_run_filter)
.exclude(output__pr_url="")