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): cut per-row work from the inbox reports list (#93074)

posthog[bot]957e11adab9f
diff --git a/products/signals/backend/billing.py b/products/signals/backend/billing.py
index 587f748f2419..8b9b5792e103 100644
--- a/products/signals/backend/billing.py
+++ b/products/signals/backend/billing.py
@@ -38,10 +38,11 @@ would otherwise be repeatable free work.
import uuid
from collections import defaultdict
+from collections.abc import Sequence
from datetime import datetime
from typing import TYPE_CHECKING, NamedTuple
-from django.db.models import F, OuterRef, QuerySet, Subquery, Sum
+from django.db.models import F, Min, OuterRef, QuerySet, Subquery, Sum
from django.utils import timezone
from dateutil.relativedelta import relativedelta
@@ -250,6 +251,22 @@ def annotate_first_billable_pr_run_at(queryset: QuerySet[SignalReport]) -> Query
return queryset.annotate(first_billable_pr_run_at=Subquery(earliest))
+def first_billable_pr_run_at_by_report(report_ids: Sequence[str | uuid.UUID]) -> dict[str, datetime]:
+ """`annotate_first_billable_pr_run_at` for a known set of reports, in one grouped query.
+
+ The annotation is a correlated subquery, so it costs one bridge-and-run walk per row the
+ query returns. A list that already knows its page asks for the whole page at once instead.
+ Reports with no billable PR run are absent from the map, matching the annotation's NULL.
+ """
+ rows = (
+ _bridges_with_pr_run()
+ .filter(report_id__in=report_ids)
+ .values("report_id")
+ .annotate(first_run_at=Min("task__runs__created_at"))
+ )
+ return {str(row["report_id"]): row["first_run_at"] for row in rows}
+
+
# Why a report can't be refunded right now (`refund_ineligibility_reason`); None = refundable.
REFUND_INELIGIBLE_ALREADY_REFUNDED = "already_refunded"
REFUND_INELIGIBLE_BILLING_EXEMPT = "billing_exempt"
diff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.py
index ba019b779c08..c5f5e763fac9 100644
--- a/products/signals/backend/serializers.py
+++ b/products/signals/backend/serializers.py
@@ -1,5 +1,6 @@
import json
from collections.abc import Mapping
+from datetime import datetime
from typing import cast
from django.db.models import Q
@@ -727,10 +728,15 @@ class SignalReportSerializer(serializers.ModelSerializer):
# context nor the billable-moment annotation exists — the refund endpoint re-enforces.
if period is None:
return None
+ billable_run_at_map: dict[str, datetime] | None = self.context.get("first_billable_pr_run_at_map")
+ if billable_run_at_map is not None:
+ billable_run_at = billable_run_at_map.get(str(obj.id))
+ else:
+ billable_run_at = getattr(obj, "first_billable_pr_run_at", None)
return refund_ineligibility_reason(
has_refund=getattr(obj, "refund", None) is not None,
billing_exempt=bool(obj.billing_exempt_reason),
- billable_run_at=getattr(obj, "first_billable_pr_run_at", None),
+ billable_run_at=billable_run_at,
period=period,
)
diff --git a/products/signals/backend/test/test_refunds.py b/products/signals/backend/test/test_refunds.py
index d746dfa636e0..061c27eed9e3 100644
--- a/products/signals/backend/test/test_refunds.py
+++ b/products/signals/backend/test/test_refunds.py
@@ -167,8 +167,10 @@ class TestSignalReportRefundAPI(APIBaseTest):
)
@freeze_time(_NOW)
def test_report_response_carries_refund_ineligibility_reason(self, _flag, case, expected):
- # The serializer field shares the refund endpoint's eligibility decision (annotation +
+ # The serializer field shares the refund endpoint's eligibility decision (billable moment +
# period context + helper); a wiring regression would re-enable buttons that only 400.
+ # The list resolves the billable moment from a batched map and the detail from a per-row
+ # annotation, so both paths are asserted — the inbox reads the list one.
if case == "no_billable_pr":
report = _make_report(self.team)
else:
@@ -186,6 +188,12 @@ class TestSignalReportRefundAPI(APIBaseTest):
assert response.status_code == 200
assert response.json()["refund_ineligibility_reason"] == expected
+ list_response = self.client.get(f"/api/projects/{self.team.id}/signals/reports/")
+
+ assert list_response.status_code == 200
+ listed = {row["id"]: row for row in list_response.json()["results"]}
+ assert listed[str(report.id)]["refund_ineligibility_reason"] == expected
+
@freeze_time(_NOW)
def test_refund_on_exempt_report_is_rejected(self, _flag):
report = self._report_with_pr(pr_created_at=datetime(2026, 6, 10, tzinfo=UTC))
diff --git a/products/signals/backend/views.py b/products/signals/backend/views.py
index e0a3e865f3fb..852353ece029 100644
--- a/products/signals/backend/views.py
+++ b/products/signals/backend/views.py
@@ -89,6 +89,7 @@ from products.signals.backend.billing import (
annotate_first_billable_pr_run_at,
current_billing_period_bounds,
first_billable_pr_run,
+ first_billable_pr_run_at_by_report,
period_billable_credits_for_org,
refund_ineligibility_reason,
report_pr_is_merged,
@@ -854,11 +855,9 @@ class SignalReportViewSet(
# report: only visibility matters here, so skip the rendering annotations and
# prefetches every other action's serializer needs.
qs = queryset.filter(team=self.team)
- qs = self._exclude_deleted_signal_reports(qs)
return self._apply_signal_report_status_filter(qs)
if self.action in {"retrieve", "signals"}:
qs = self._scope_signal_report_queryset(queryset)
- qs = self._exclude_deleted_signal_reports(qs)
qs = self._apply_signal_report_status_filter(qs)
qs = self._annotate_latest_actionability(qs)
qs = self._prefetch_signal_report_priority_artefacts(qs)
@@ -866,7 +865,6 @@ class SignalReportViewSet(
return annotate_first_billable_pr_run_at(qs)
qs = queryset
qs = self._scope_signal_report_queryset(qs)
- qs = self._exclude_deleted_signal_reports(qs)
qs = self._apply_signal_report_status_filter(qs)
qs = self._apply_signal_report_search_filter(qs)
qs = self._apply_signal_report_source_product_filter(qs)
@@ -887,9 +885,11 @@ class SignalReportViewSet(
qs = self._apply_signal_report_priority_filter(qs)
qs = self._prefetch_signal_report_priority_artefacts(qs)
qs = self._annotate_is_suggested_reviewer(qs)
- # Batched billable-moment lookup for the serializer's refund_ineligibility_reason field.
- qs = annotate_first_billable_pr_run_at(qs)
- if self.action != "list":
+ if self.action not in self._MULTI_REPORT_ACTIONS:
+ # Both of these are correlated subqueries, so they cost one walk per row the query
+ # matches. The multi-row actions do without them: `list` serves the same two values
+ # from batched lookups over the page it returns, and `bulk_state` renders no report.
+ qs = annotate_first_billable_pr_run_at(qs)
qs = self._annotate_implementation_pr_url(qs)
return qs
@@ -929,13 +929,13 @@ class SignalReportViewSet(
)
)
- def _exclude_deleted_signal_reports(self, queryset):
- # Deleted reports are terminal -- exclude from all endpoints (detail, list, actions)
- return queryset.exclude(status=SignalReport.Status.DELETED)
-
- # `deleted` is in the model but always stripped upstream by `_exclude_deleted_signal_reports`,
- # so it is never a valid filter target.
+ # Deleted reports are terminal, so `deleted` never reaches any endpoint (detail, list,
+ # actions) and is never a valid filter target either.
_FILTERABLE_STATUSES = frozenset(SignalReport.Status.values) - {SignalReport.Status.DELETED}
+ _DEFAULT_STATUSES = _FILTERABLE_STATUSES - {SignalReport.Status.SUPPRESSED}
+
+ # Actions that work on many reports at once, so per-row annotations are wasted work there.
+ _MULTI_REPORT_ACTIONS = frozenset({"list", "bulk_state"})
# Actions allowed to resolve a suppressed report by ID even without an explicit
# `status` filter. These are the read/reopen paths the inbox's Dismissed tab needs:
@@ -962,6 +962,12 @@ class SignalReportViewSet(
}
def _apply_signal_report_status_filter(self, queryset):
+ # Always a positive `status__in`, never a negated equality: Postgres can put an IN into the
+ # `(team, status, promoted_at)` index condition, while `exclude(status=...)` leaves the
+ # status as a filter that runs on rows the index already made it read.
+ return queryset.filter(status__in=sorted(self._visible_statuses()))
+
+ def _visible_statuses(self) -> frozenset[str]:
status_filter = self.request.query_params.get("status")
if status_filter:
statuses = [s.strip() for s in status_filter.split(",") if s.strip()]
@@ -973,7 +979,7 @@ class SignalReportViewSet(
"status": f"Invalid status value(s): {', '.join(sorted(set(invalid)))}. Accepted values: {accepted}."
}
)
- return queryset.filter(status__in=statuses)
+ return frozenset(statuses)
# A few read/reopen actions must be able to reach a suppressed report by ID
# (e.g. `state` reopens a dismissed report, `retrieve`/`signals` back the
# inbox's Dismissed-tab detail view). Everywhere else — including the list and
@@ -982,13 +988,13 @@ class SignalReportViewSet(
# the default exclusions with `include_all_statuses=true` (agents deduping
# against the full inbox state, human dismissals included, without enumerating
# every status — and without breaking if the status set evolves).
- if self.action in self._SUPPRESSED_VISIBLE_ACTIONS:
- return queryset
- if self._include_all_statuses_requested():
- return queryset
- if self.request.query_params.get("view") in {"dismissed", "all"}:
- return queryset
- return queryset.exclude(status=SignalReport.Status.SUPPRESSED)
+ if (
+ self.action in self._SUPPRESSED_VISIBLE_ACTIONS
+ or self._include_all_statuses_requested()
+ or self.request.query_params.get("view") in {"dismissed", "all"}
+ ):
+ return self._FILTERABLE_STATUSES
+ return self._DEFAULT_STATUSES
def _include_all_statuses_requested(self) -> bool:
# List-only: the flag widens the *list* for full-inbox-state scans (agent dedup). By-ID
@@ -1898,12 +1904,18 @@ class SignalReportViewSet(
logger.exception("signals.reports.list.implementation_pr_url_failed", report_count=len(report_ids))
implementation_pr_by_report = {}
+ # One grouped query for the whole page, in place of the per-row annotation the other
+ # actions carry, for the serializer's refund_ineligibility_reason field.
+ with tracer.start_as_current_span("signals.reports.list.fetch_billable_pr_runs"):
+ first_billable_pr_run_at_map = first_billable_pr_run_at_by_report(report_ids)
+
context = {
**self.get_serializer_context(),
"source_products_map": {rid: meta.source_products for rid, meta in signal_meta_map.items()},
"scout_names_map": {rid: meta.scout_name for rid, meta in signal_meta_map.items() if meta.scout_name},
"implementation_pr_url_map": {rid: pr.url for rid, pr in implementation_pr_by_report.items()},
"implementation_pr_merged_ids": {rid for rid, pr in implementation_pr_by_report.items() if pr.merged},
+ "first_billable_pr_run_at_map": first_billable_pr_run_at_map,
}
serializer = self.get_serializer(reports, many=True, context=context)