: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
perf(signals): load artefact content only for the newest row per report (#110407)
posthog[bot]6f356411c359
diff --git a/products/signals/backend/briefing_reports.py b/products/signals/backend/briefing_reports.pyindex 5a9f25c66295..086991c259ae 100644--- a/products/signals/backend/briefing_reports.py+++ b/products/signals/backend/briefing_reports.py@@ -106,22 +106,24 @@ class BriefingReportDetails:charts: list[ReportChartSnapshot]-def _latest_artefacts(report_ids: Sequence[str], artefact_type: str) -> dict[str, str]:+def _latest_artefacts(team_id: int, report_ids: Sequence[str], artefact_type: str) -> dict[str, str]:"""The newest artefact content of one type per report, by report id."""- rows = (- SignalReportArtefact.objects.filter(report_id__in=report_ids, type=artefact_type)+ # Pick the newest id per report first, so Postgres reads `content` once per report, not once per row.+ latest_ids = (+ SignalReportArtefact.objects.filter(team_id=team_id, report_id__in=report_ids, type=artefact_type).order_by("report_id", "-created_at").distinct("report_id")- .values_list("report_id", "content")+ .values("id"))+ rows = SignalReportArtefact.objects.filter(team_id=team_id, id__in=latest_ids).values_list("report_id", "content")return {str(report_id): content for report_id, content in rows}-def _priorities(report_ids: Sequence[str]) -> dict[str, str]:+def _priorities(team_id: int, report_ids: Sequence[str]) -> dict[str, str]:"""Latest priority judgment per report, read the same way the inbox serializer reads it."""latest: dict[str, str] = {}for report_id, content in _latest_artefacts(- report_ids, SignalReportArtefact.ArtefactType.PRIORITY_JUDGMENT+ team_id, report_ids, SignalReportArtefact.ArtefactType.PRIORITY_JUDGMENT).items():priority = priority_from_judgment(content)if priority is not None:@@ -541,7 +543,7 @@ def report_details())found_ids = [str(report.id) for report in reports]- priorities = _priorities(found_ids)+ priorities = _priorities(team_id, found_ids)pull_requests = fetch_implementation_pr_state_for_reports(found_ids, team_id=team_id)details = []for report in reports:diff --git a/products/signals/backend/ranking/sweep.py b/products/signals/backend/ranking/sweep.pyindex a2e603da04b7..1ec10f440408 100644--- a/products/signals/backend/ranking/sweep.py+++ b/products/signals/backend/ranking/sweep.py@@ -14,7 +14,7 @@ import uuidimport datetimeimport resourcefrom collections import defaultdict-from collections.abc import Iterator, Sequence+from collections.abc import Iterator, Mapping, Sequencefrom typing import Any, castfrom django.conf import settings@@ -183,23 +183,28 @@ def _scorable_report_teams(return teams-def _latest_scores(report_ids: Sequence[str]) -> dict[str, _ScoreStamp | None]:+def _latest_scores(report_ids_by_team: Mapping[int, Sequence[str]]) -> dict[str, _ScoreStamp | None]:"""The latest `ranking_score` stamp of each report that has one. A row that no longer parses is None."""scores: dict[str, _ScoreStamp | None] = {}- for batch in _batches(report_ids):- rows = (- SignalReportArtefact.objects.filter(- report_id__in=batch, type=SignalReportArtefact.ArtefactType.RANKING_SCORE+ for team_id, report_ids in report_ids_by_team.items():+ for batch in _batches(report_ids):+ # Pick the newest id per report first, so Postgres reads `content` once per report, not once per score.+ latest_ids = (+ SignalReportArtefact.objects.filter(+ team_id=team_id, report_id__in=batch, type=SignalReportArtefact.ArtefactType.RANKING_SCORE+ )+ .order_by("report_id", "-created_at")+ .distinct("report_id")+ .values("id"))- .order_by("report_id", "-created_at")- .distinct("report_id")- .values_list("report_id", "content")- )- for report_id, content in rows:- try:- scores[str(report_id)] = _ScoreStamp.model_validate_json(content)- except pydantic.ValidationError:- scores[str(report_id)] = None+ rows = SignalReportArtefact.objects.filter(team_id=team_id, id__in=latest_ids).values_list(+ "report_id", "content"+ )+ for report_id, content in rows:+ try:+ scores[str(report_id)] = _ScoreStamp.model_validate_json(content)+ except pydantic.ValidationError:+ scores[str(report_id)] = Nonereturn scores@@ -230,7 +235,10 @@ def reports_due_for_scoring(vectors = _live_vectors(since, rendering)report_teams = _scorable_report_teams(list(vectors), now, since)kept = [report_id for report_id, team_id in report_teams.items() if vectors[report_id][0] == team_id]- latest = _latest_scores(kept)+ kept_by_team: dict[int, list[str]] = defaultdict(list)+ for report_id in kept:+ kept_by_team[report_teams[report_id]].append(report_id)+ latest = _latest_scores(kept_by_team)due: list[tuple[datetime.datetime | None, ScoringCandidate]] = []for report_id in kept:diff --git a/products/signals/backend/test/test_briefing_reports.py b/products/signals/backend/test/test_briefing_reports.pyindex 24675d8da004..234f4f3176c4 100644--- a/products/signals/backend/test/test_briefing_reports.py+++ b/products/signals/backend/test/test_briefing_reports.py@@ -15,6 +15,8 @@ from django.utils import timezonefrom parameterized import parameterizedfrom rest_framework.request import Request+from posthog.models import Team+from products.signals.backend.artefact_schemas import ActionabilityChoice, RankingModelResult, RankingScorefrom products.signals.backend.briefing_reports import (BriefingReportRelation,@@ -126,6 +128,15 @@ class TestReportsForBriefing(BaseTest):viewer = ReportMetricAccessPolicy(request=cast(Request, SimpleNamespace(user=self.user, successful_authenticator=None)), team=self.team)+ # A newer judgment stored under another team must not leak into this team's details.+ cross_team = SignalReportArtefact.objects.create(+ team=Team.objects.create(organization=self.organization),+ report=report,+ type=SignalReportArtefact.ArtefactType.PRIORITY_JUDGMENT,+ content=json.dumps({"priority": "P4"}),+ )+ SignalReportArtefact.objects.filter(pk=cross_team.pk).update(created_at=timezone.now() + timedelta(hours=1))+[details] = report_details(team_id=self.team.id, report_ids=[str(report.id)], metric_access=viewer)# Without a viewer the policy reads nothing, so the briefing must hide every metric, as the Inbox does.[unreadable] = report_details(diff --git a/products/signals/backend/test/test_ranking_sweep.py b/products/signals/backend/test/test_ranking_sweep.pyindex 8ac0fd744cdb..dd41eec90f87 100644--- a/products/signals/backend/test/test_ranking_sweep.py+++ b/products/signals/backend/test/test_ranking_sweep.py@@ -116,9 +116,10 @@ class TestReportsDueForScoring(ClickhouseTestMixin, BaseTest):manifest: str = MANIFEST,hours_ago: int = 1,served_version: str = SERVED_VERSION,+ team: Team | None = None,) -> None:SignalReportArtefact.objects.create(- team=self.team,+ team=team or self.team,report_id=report_id,type=SignalReportArtefact.ArtefactType.RANKING_SCORE,content=_score(@@ -176,7 +177,16 @@ class TestReportsDueForScoring(ClickhouseTestMixin, BaseTest):wrong_team = self._report(team=other_team)self._vector(wrong_team, hours_ago=5, team_id=self.team.pk)- assert sorted(self._due()) == sorted([unscored, edited, other_manifest, other_served])+ # A newer current score stored under another team must not count as this report's score.+ cross_team_score = self._report()+ cross_team_vector = self._vector(cross_team_score, hours_ago=5)+ self._scored(cross_team_score, vector_at=cross_team_vector, manifest=OLD_MANIFEST, hours_ago=3)+ self._scored(cross_team_score, vector_at=cross_team_vector, team=other_team)+ SignalReportArtefact.objects.filter(team=other_team, report_id=cross_team_score).update(+ created_at=self.now + datetime.timedelta(hours=1)+ )++ assert sorted(self._due()) == sorted([unscored, edited, other_manifest, other_served, cross_team_score])def test_the_cap_keeps_unscored_reports_first_then_the_oldest_scores(self) -> None:recently_scored, long_ago_scored, unscored = self._report(), self._report(), self._report()