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): batch implementation-PR lookup to kill inbox N+1 (#65417)

Joshua Snyder6dea12cb23fd
diff --git a/products/signals/backend/implementation_pr.py b/products/signals/backend/implementation_pr.py
index fee15760568e..de8459ae3e4e 100644
--- a/products/signals/backend/implementation_pr.py
+++ b/products/signals/backend/implementation_pr.py
@@ -8,20 +8,23 @@ from products.tasks.backend.facade import api as tasks_facade
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.
- The task↔report association comes from `SignalReport.associated_task_runs` (the unified view of
- the `task_run` artefact log + legacy gate rows); the facade then resolves the latest PR-bearing
- run for each task, so multiple runs of a task collapse to the newest PR.
+ The task↔report association comes from `SignalReport.associated_task_runs_for_reports` (the
+ unified view of the `task_run` artefact log + legacy gate rows, batched over the whole page);
+ the facade then resolves the latest PR-bearing run for each task, so multiple runs of a task
+ collapse to the newest PR.
"""
if not report_ids:
return {}
# (report_id, task_id) for each report's implementation task(s); signals owns this mapping.
+ # Batched across the whole page so association costs two queries, not two per report (N+1).
+ runs_by_report = SignalReport.associated_task_runs_for_reports(
+ report_ids=[str(report_id) for report_id in report_ids],
+ product=SIGNALS_PRODUCT,
+ type=TASK_RUN_TYPE_IMPLEMENTATION,
+ )
pairs: list[tuple[str, str]] = [
- (str(report_id), run.task_id)
- for report_id in report_ids
- for run in SignalReport.associated_task_runs(
- report_id=str(report_id), product=SIGNALS_PRODUCT, type=TASK_RUN_TYPE_IMPLEMENTATION
- )
+ (report_id, run.task_id) for report_id, runs in runs_by_report.items() for run in runs
]
if not pairs:
return {}
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.py
index 3d3a0e35b48c..d97335dfdfcf 100644
--- a/products/signals/backend/models.py
+++ b/products/signals/backend/models.py
@@ -1,4 +1,5 @@
import logging
+from collections import defaultdict
from dataclasses import dataclass
from datetime import datetime
from typing import Any, Literal, cast
@@ -461,6 +462,57 @@ class SignalReport(UUIDModel):
type=type,
)
+ @classmethod
+ def associated_task_runs_for_reports(
+ cls,
+ *,
+ report_ids: list[str],
+ team_id: int | None = None,
+ product: str | None = None,
+ type: str | None = None,
+ ) -> dict[str, list[TaskRunArtefact]]:
+ """`associated_task_runs` batched over many reports — two queries total (one for the
+ `task_run` artefacts, one for the legacy `SignalReportTask` gate rows) grouped by report in
+ memory, rather than the 2N a per-report loop issues. Use this when resolving associations for
+ a page of reports (e.g. the inbox list); per-report `associated_task_runs` is the N+1 trap.
+
+ Returns `{report_id: runs}` with each report's runs identical to what `associated_task_runs`
+ would return (oldest-first, de-duplicated by task). Reports with no associated runs are
+ omitted, so callers can treat a missing key as "no runs".
+ """
+ if not report_ids:
+ return {}
+
+ artefacts = SignalReportArtefact.objects.filter(
+ report_id__in=report_ids, type=SignalReportArtefact.ArtefactType.TASK_RUN
+ )
+ report_tasks = SignalReportTask.objects.filter(report_id__in=report_ids)
+ if team_id is not None:
+ artefacts = artefacts.filter(team_id=team_id)
+ report_tasks = report_tasks.filter(team_id=team_id)
+
+ artefact_rows_by_report: dict[str, list[tuple[datetime, str]]] = defaultdict(list)
+ for report_id, created_at, content in artefacts.values_list("report_id", "created_at", "content"):
+ artefact_rows_by_report[str(report_id)].append((created_at, content))
+
+ task_rows_by_report: dict[str, list[tuple[datetime, str | None, Any]]] = defaultdict(list)
+ for report_id, created_at, relationship, task_id in report_tasks.values_list(
+ "report_id", "created_at", "relationship", "task_id"
+ ):
+ task_rows_by_report[str(report_id)].append((created_at, relationship, task_id))
+
+ result: dict[str, list[TaskRunArtefact]] = {}
+ for report_id in {str(rid) for rid in report_ids}:
+ runs = cls._merge_task_runs(
+ artefact_rows_by_report.get(report_id, []),
+ task_rows_by_report.get(report_id, []),
+ product=product,
+ type=type,
+ )
+ if runs:
+ result[report_id] = runs
+ return result
+
@staticmethod
def associated_task_runs_filter(report_ref: Any) -> "models.Q":
"""A `Q` matching `tasks.TaskRun`s whose task is associated with the correlated report,
diff --git a/products/signals/backend/test/test_signal_report_api.py b/products/signals/backend/test/test_signal_report_api.py
index 92496c389306..c65a83d8feb2 100644
--- a/products/signals/backend/test/test_signal_report_api.py
+++ b/products/signals/backend/test/test_signal_report_api.py
@@ -10,6 +10,8 @@ from unittest.mock import patch
from django.apps import apps
from django.core.cache import cache
+from django.db import connection
+from django.test.utils import CaptureQueriesContext
from django.utils import timezone
from parameterized import parameterized
@@ -685,6 +687,33 @@ class TestSignalReportListAPI(APIBaseTest):
str(report_with_pr.id): "https://github.com/org/repo/pull/42",
}
+ def test_fetch_implementation_pr_urls_issues_constant_queries(self):
+ # N+1 guard: association is batched across the page, so resolving PR urls for many reports
+ # costs the same number of queries as for one. A per-report `associated_task_runs` loop
+ # scaled at two queries per report (one artefact read + one gate-row read), the exact
+ # regression this asserts against.
+ def seed(count: int) -> list[str]:
+ ids = []
+ for i in range(count):
+ report = self._create_report(title=f"PR report {i}")
+ self._create_implementation_task_with_run(report, pr_url=f"https://github.com/org/repo/pull/{i}")
+ ids.append(str(report.id))
+ return ids
+
+ single = seed(1)
+ with CaptureQueriesContext(connection) as for_one:
+ fetch_implementation_pr_urls_for_reports(single)
+ baseline = len(for_one.captured_queries)
+
+ page = single + seed(5)
+ with CaptureQueriesContext(connection) as for_many:
+ result = fetch_implementation_pr_urls_for_reports(page)
+
+ assert len(result) == 6
+ # Constant in the page size, and a small fixed cost (artefacts + gate rows + PR lookup).
+ assert len(for_many.captured_queries) == baseline
+ assert baseline <= 3
+
# --- has_implementation_pr filter ---
@parameterized.expand(
@@ -1019,6 +1048,118 @@ class TestSignalReportListAPI(APIBaseTest):
assert row["dismissal_reason"] == "analysis_wrong"
+class TestAssociatedTaskRunsForReports(APIBaseTest):
+ """`SignalReport.associated_task_runs_for_reports` — the batched, page-wide counterpart of
+ `associated_task_runs` that backs the inbox list without an N+1."""
+
+ def _create_report(self, **kwargs) -> SignalReport:
+ defaults = {
+ "team": self.team,
+ "status": SignalReport.Status.READY,
+ "title": "Test report",
+ "summary": "Test summary",
+ "signal_count": 1,
+ "total_weight": 1.0,
+ }
+ defaults.update(kwargs)
+ return SignalReport.objects.create(**defaults)
+
+ def _new_task(self) -> "Task":
+ Task = apps.get_model("tasks", "Task")
+ return Task.objects.create(
+ team=self.team, title="t", description="d", origin_product=Task.OriginProduct.SIGNAL_REPORT
+ )
+
+ def test_empty_report_ids_returns_empty(self):
+ assert SignalReport.associated_task_runs_for_reports(report_ids=[]) == {}
+
+ def test_groups_by_report_and_omits_reports_without_runs(self):
+ report_with_gate = self._create_report()
+ report_with_artefact = self._create_report()
+ report_without_runs = self._create_report()
+ gate_task = self._new_task()
+ artefact_task = self._new_task()
+ record_implementation_task(team_id=self.team.id, report_id=str(report_with_gate.id), task_id=str(gate_task.id))
+ append_task_run_artefact(
+ team_id=self.team.id,
+ report_id=str(report_with_artefact.id),
+ product="signals",
+ type="implementation",
+ task_id=str(artefact_task.id),
+ )
+
+ result = SignalReport.associated_task_runs_for_reports(
+ report_ids=[str(report_with_gate.id), str(report_with_artefact.id), str(report_without_runs.id)]
+ )
+
+ assert set(result.keys()) == {str(report_with_gate.id), str(report_with_artefact.id)}
+ assert [run.task_id for run in result[str(report_with_gate.id)]] == [str(gate_task.id)]
+ assert [run.task_id for run in result[str(report_with_artefact.id)]] == [str(artefact_task.id)]
+
+ def test_matches_per_report_associated_task_runs(self):
+ # Parity with the trusted per-report method across mixed association sources.
+ gate_report = self._create_report()
+ artefact_report = self._create_report()
+ empty_report = self._create_report()
+ gate_task = self._new_task()
+ artefact_task = self._new_task()
+ record_implementation_task(team_id=self.team.id, report_id=str(gate_report.id), task_id=str(gate_task.id))
+ append_task_run_artefact(
+ team_id=self.team.id,
+ report_id=str(artefact_report.id),
+ product="signals",
+ type="implementation",
+ task_id=str(artefact_task.id),
+ )
+
+ report_ids = [str(gate_report.id), str(artefact_report.id), str(empty_report.id)]
+ batched = SignalReport.associated_task_runs_for_reports(
+ report_ids=report_ids, product="signals", type="implementation"
+ )
+
+ for report_id in report_ids:
+ per_report = SignalReport.associated_task_runs(
+ report_id=report_id, product="signals", type="implementation"
+ )
+ assert batched.get(report_id, []) == per_report
+
+ def test_respects_product_and_type_filters(self):
+ report = self._create_report()
+ impl_task = self._new_task()
+ other_task = self._new_task()
+ append_task_run_artefact(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ product="signals",
+ type="implementation",
+ task_id=str(impl_task.id),
+ )
+ append_task_run_artefact(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ product="signals",
+ type="investigation",
+ task_id=str(other_task.id),
+ )
+
+ result = SignalReport.associated_task_runs_for_reports(
+ report_ids=[str(report.id)], product="signals", type="implementation"
+ )
+
+ assert [run.task_id for run in result[str(report.id)]] == [str(impl_task.id)]
+
+ def test_scopes_by_team_id(self):
+ report = self._create_report()
+ task = self._new_task()
+ record_implementation_task(team_id=self.team.id, report_id=str(report.id), task_id=str(task.id))
+
+ other_team = Team.objects.create(organization=self.organization, name="Other team")
+ assert SignalReport.associated_task_runs_for_reports(report_ids=[str(report.id)], team_id=other_team.id) == {}
+ assert str(report.id) in SignalReport.associated_task_runs_for_reports(
+ report_ids=[str(report.id)], team_id=self.team.id
+ )
+
+
class TestSignalReportSuppressionAPI(APIBaseTest):
def _state_url(self, report_id: str) -> str:
return f"/api/projects/{self.team.id}/signals/reports/{report_id}/state/"