: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): read the inbox actionability cache instead of artefact json (#105683)
posthog[bot]50a449ddd5c8
diff --git a/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txt b/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txtindex 440143f2ab8b..c05b654ad1bf 100644--- a/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txt+++ b/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txt@@ -38,3 +38,8 @@ tasks.0120_backfill_canvas_search_documents# Fills the generic tag pointer in batches of 10,000 rows, so the run never holds one transaction open.# Re-running is a no-op: each UPDATE only touches rows whose content_type_id is still NULL.posthog.1370_backfill_taggeditem_generic_pointer+# Fills the actionability cache for reports judged before the columns existed, in id-ordered+# batches so no single transaction locks the whole backlog. Re-running is a no-op: a pass only+# selects reports that still hold no cached judgment, and each value is recomputed from the+# artefact log.+signals.0154_backfill_report_actionabilitydiff --git a/products/signals/backend/migrations/0154_backfill_report_actionability.py b/products/signals/backend/migrations/0154_backfill_report_actionability.pynew file mode 100644index 000000000000..ab1a06e568ce--- /dev/null+++ b/products/signals/backend/migrations/0154_backfill_report_actionability.py@@ -0,0 +1,95 @@+import json++from django.db import migrations++BATCH_SIZE = 500+++def _latest_judgment(contents: list[str], max_actionability_length: int) -> tuple[str | None, bool | None] | None:+ """The newest parseable judgment of one report, newest content first.++ A row that is not a JSON object is skipped rather than ending the search, so one malformed+ artefact cannot hide the judgment written before it. Returns None when nothing parses. A+ judgment holds whatever string its author wrote, so a value too long for the column is+ dropped here rather than failing the whole deploy.+ """+ for content in contents:+ try:+ parsed = json.loads(content)+ except (json.JSONDecodeError, TypeError, ValueError):+ continue+ if not isinstance(parsed, dict):+ continue+ actionability = parsed.get("actionability")+ already_addressed = parsed.get("already_addressed")+ if not isinstance(actionability, str) or len(actionability) > max_actionability_length:+ actionability = None+ return actionability, already_addressed if isinstance(already_addressed, bool) else None+ return None+++def backfill_report_actionability(apps, schema_editor):+ """Fill the cached actionability of every report judged before the columns existed.++ The receivers write both columns on each judgment artefact write, so only reports whose+ newest judgment predates those receivers hold NULL. The inbox list now filters and sorts on+ the columns, so an unfilled report would drop out of the Reports tab it belongs in.++ The parsing is repeated here rather than taken from `report_actionability_repair`, which+ reads a report under its row lock through the live model. This runs against the historical+ models, and what an applied migration did must not change when the live parser changes.+ """+ SignalReport = apps.get_model("signals", "SignalReport")+ SignalReportArtefact = apps.get_model("signals", "SignalReportArtefact")+ max_actionability_length = SignalReport._meta.get_field("latest_actionability").max_length+ unfilled = SignalReport.objects.filter(+ latest_actionability__isnull=True, latest_already_addressed__isnull=True+ ).order_by("id")+ cursor = None+ while True:+ page = unfilled.filter(id__gt=cursor) if cursor else unfilled+ report_ids = list(page.values_list("id", flat=True)[:BATCH_SIZE])+ if not report_ids:+ return+ cursor = report_ids[-1]+ contents_by_report: dict[str, list[str]] = {}+ rows = (+ SignalReportArtefact.objects.filter(report_id__in=report_ids, type="actionability_judgment")+ .order_by("report_id", "-created_at")+ .values_list("report_id", "content")+ )+ for report_id, content in rows.iterator(chunk_size=1000):+ contents_by_report.setdefault(str(report_id), []).append(content)+ # Group the page by judgment value so a batch costs one UPDATE per distinct pair rather+ # than one per report.+ ids_by_value: dict[tuple[str | None, bool | None], list[str]] = {}+ for report_id, contents in contents_by_report.items():+ judgment = _latest_judgment(contents, max_actionability_length)+ if judgment is None or judgment == (None, None):+ continue+ ids_by_value.setdefault(judgment, []).append(report_id)+ for (actionability, already_addressed), ids in ids_by_value.items():+ # `update()`, not `save()`: filling a cache must not bump `updated_at`, which the+ # inbox sorts on. The UPDATE repeats the NULL conditions of the page query because a+ # receiver can store a newer judgment after the artefact read above. Postgres+ # re-checks the WHERE clause on the current row version, so that report is skipped.+ unfilled.filter(id__in=ids).update(+ latest_actionability=actionability, latest_already_addressed=already_addressed+ )+++class Migration(migrations.Migration):+ # Non-atomic so each batch commits and releases its row locks as it goes, instead of holding+ # every report the backfill touches locked until the last batch commits. Safe to resume after+ # a partial run: a pass only selects reports that still hold no cached judgment, and the+ # values are recomputed from the artefact log rather than accumulated.+ atomic = False++ dependencies = [+ ("signals", "0153_signalreport_latest_actionability"),+ ]++ # Reverse is a noop: clearing the cache would hide judged reports from the inbox again.+ operations = [+ migrations.RunPython(backfill_report_actionability, migrations.RunPython.noop, elidable=True),+ ]diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txtindex 9453329abfd3..ec62cb3182a9 100644--- a/products/signals/backend/migrations/max_migration.txt+++ b/products/signals/backend/migrations/max_migration.txt@@ -1 +1 @@-0153_signalreport_latest_actionability+0154_backfill_report_actionabilitydiff --git a/products/signals/backend/test/test_backfill_report_actionability.py b/products/signals/backend/test/test_backfill_report_actionability.pyindex 62b677e33a4d..e8c9e909571c 100644--- a/products/signals/backend/test/test_backfill_report_actionability.py+++ b/products/signals/backend/test/test_backfill_report_actionability.py@@ -1,7 +1,11 @@import json+import importlib+from datetime import UTC, datetimefrom posthog.test.base import BaseTest+from unittest.mock import patch+from django.apps import appsfrom django.core.management import call_commandfrom products.signals.backend.models import SignalReport, SignalReportArtefact@@ -44,3 +48,68 @@ class TestBackfillReportActionability(BaseTest):assert self._cached(drifted) == ("requires_human_input", True)assert self._cached(never_judged) == (None, None)++ def _judgment(self, report: SignalReport, *, content: str, created_at: datetime) -> None:+ artefact = SignalReportArtefact.objects.create(+ team=self.team,+ report=report,+ type=SignalReportArtefact.ArtefactType.ACTIONABILITY_JUDGMENT,+ content=content,+ )+ SignalReportArtefact.objects.filter(id=artefact.id).update(created_at=created_at)++ def test_migration_fills_reports_judged_before_the_columns_existed(self):+ judged = self._report(actionability=None)+ self._judgment(+ judged,+ content=json.dumps({"actionability": "not_actionable", "already_addressed": False}),+ created_at=datetime(2026, 1, 1, tzinfo=UTC),+ )+ self._judgment(+ judged,+ content=json.dumps({"actionability": "immediately_actionable", "already_addressed": True}),+ created_at=datetime(2026, 1, 2, tzinfo=UTC),+ )+ self._judgment(judged, content="not json", created_at=datetime(2026, 1, 3, tzinfo=UTC))+ other = self._report(actionability=None)+ self._judgment(+ other,+ content=json.dumps({"actionability": "requires_human_input", "already_addressed": False}),+ created_at=datetime(2026, 1, 2, tzinfo=UTC),+ )+ unjudged = self._report(actionability=None)+ # The receivers keep the columns current today, so clearing them is what a report judged+ # before those columns existed looks like.+ SignalReport.objects.all().update(latest_actionability=None, latest_already_addressed=None)++ migration = importlib.import_module("products.signals.backend.migrations.0154_backfill_report_actionability")+ migration.backfill_report_actionability(apps, None)++ assert self._cached(judged) == ("immediately_actionable", True)+ assert self._cached(other) == ("requires_human_input", False)+ assert self._cached(unjudged) == (None, None)++ def test_migration_keeps_a_judgment_stored_after_its_artefact_read(self):+ report = self._report(actionability=None)+ self._judgment(+ report,+ content=json.dumps({"actionability": "not_actionable", "already_addressed": False}),+ created_at=datetime(2026, 1, 1, tzinfo=UTC),+ )+ SignalReport.objects.all().update(latest_actionability=None, latest_already_addressed=None)+ migration = importlib.import_module("products.signals.backend.migrations.0154_backfill_report_actionability")+ latest_judgment = migration._latest_judgment++ def judged_again_before_the_update(*args, **kwargs):+ SignalReportArtefact.objects.create(+ team=self.team,+ report=report,+ type=SignalReportArtefact.ArtefactType.ACTIONABILITY_JUDGMENT,+ content=json.dumps({"actionability": "immediately_actionable", "already_addressed": True}),+ )+ return latest_judgment(*args, **kwargs)++ with patch.object(migration, "_latest_judgment", side_effect=judged_again_before_the_update):+ migration.backfill_report_actionability(apps, None)++ assert self._cached(report) == ("immediately_actionable", True)diff --git a/products/signals/backend/test/test_signal_report_api.py b/products/signals/backend/test/test_signal_report_api.pyindex dd352e8bbfc7..32387f82f1d1 100644--- a/products/signals/backend/test/test_signal_report_api.py+++ b/products/signals/backend/test/test_signal_report_api.py@@ -1592,6 +1592,21 @@ class TestSignalReportListAPI(APIBaseTest):ids = {r["id"] for r in response.json()["results"]}assert {str(a.id), str(b.id)} <= ids+ def test_filter_already_addressed_false_excludes_reports_nobody_judged(self):+ addressed = self._create_report(title="Addressed")+ self._actionability_artefact(addressed, actionability="immediately_actionable", already_addressed=True)+ open_report = self._create_report(title="Still open")+ self._actionability_artefact(open_report, actionability="immediately_actionable", already_addressed=False)+ self._create_report(title="No judgment")++ response = self.client.get(self._list_url(already_addressed="false", scope="entire_project"))+ assert response.status_code == status.HTTP_200_OK+ assert [row["id"] for row in response.json()["results"]] == [str(open_report.id)]++ response = self.client.get(self._list_url(already_addressed="true", scope="entire_project"))+ assert response.status_code == status.HTTP_200_OK+ assert [row["id"] for row in response.json()["results"]] == [str(addressed.id)]+def test_filter_actionability_invalid_value_returns_400(self):response = self.client.get(self._list_url(actionability="maybe_later"))assert response.status_code == status.HTTP_400_BAD_REQUESTdiff --git a/products/signals/backend/views.py b/products/signals/backend/views.pyindex 9d56aef3db27..d6b67ad7acf6 100644--- a/products/signals/backend/views.py+++ b/products/signals/backend/views.py@@ -1025,8 +1025,7 @@ class SignalReportViewSet(scope_object = "task"queryset = SignalReport.objects.all()# Shared Q for "ready but not actionable" — used in status ranking and suggested-reviewer suppression.- # Requires `latest_actionability_value` annotation to be applied first.- _Q_READY_NOT_ACTIONABLE = Q(status=SignalReport.Status.READY) & Q(latest_actionability_value="not_actionable")+ _Q_READY_NOT_ACTIONABLE = Q(status=SignalReport.Status.READY) & Q(latest_actionability="not_actionable")_DEFAULT_SIGNAL_REPORT_ORDERING = "-is_suggested_reviewer,status,-updated_at"_INBOX_SORT_ORDERINGS = {"priority": "priority,status,-updated_at",@@ -1067,7 +1066,6 @@ class SignalReportViewSet(qs = self._annotate_artefact_count(qs)qs = self._annotate_channel_id(qs)qs = self._apply_signal_report_status_filter(qs)- qs = self._annotate_latest_actionability(qs)qs = self._prefetch_signal_report_priority_artefacts(qs)qs = self._annotate_is_suggested_reviewer(qs)return annotate_first_billable_pr_run_at(qs)@@ -1094,9 +1092,6 @@ class SignalReportViewSet(qs = self._apply_signal_report_suggested_reviewer_filter(qs)qs = self._apply_signal_report_inbox_scope_filter(qs)qs = self._apply_signal_report_task_filter(qs)- qs = self._annotate_latest_actionability(qs)- if self._needs_already_addressed_annotation():- qs = self._annotate_latest_already_addressed(qs)qs = self._apply_signal_report_actionability_filter(qs)qs = self._apply_signal_report_already_addressed_filter(qs)qs = self._apply_signal_report_inbox_view_filter(qs)@@ -1497,13 +1492,12 @@ class SignalReportViewSet(return queryset.filter(priority_rank__in=values)def _apply_signal_report_actionability_filter(self, queryset):- # Filters on the `latest_actionability_value` annotation (the actionability- # choice from the latest actionability_judgment artefact), which must be- # annotated first. Powers the inbox's actionability-keyed tabs: the Reports- # tab passes the two actionable values, the staff-only Not-actionable tab- # passes `not_actionable`. Reports without an actionability judgment- # (annotation is NULL) are excluded when this filter is set. Absent or empty- # param leaves the list unchanged; an unrecognized value is a 400.+ # Filters on `latest_actionability`, the column cached from the report's latest+ # actionability_judgment artefact. Powers the inbox's actionability-keyed tabs: the+ # Reports tab passes the two actionable values, the staff-only Not-actionable tab+ # passes `not_actionable`. Reports without an actionability judgment (column is NULL)+ # are excluded when this filter is set. Absent or empty param leaves the list+ # unchanged; an unrecognized value is a 400.actionability_filter = self.request.query_params.get("actionability")if not actionability_filter:return queryset@@ -1522,7 +1516,7 @@ class SignalReportViewSet(})- return queryset.filter(latest_actionability_value__in=values)+ return queryset.filter(latest_actionability__in=values)def _apply_signal_report_already_addressed_filter(self, queryset):raw = self.request.query_params.get("already_addressed")@@ -1530,9 +1524,11 @@ class SignalReportViewSet(return querysetvalue = raw.strip().lower()if value in ("1", "true", "yes"):- return queryset.filter(latest_already_addressed_value="true")+ return queryset.filter(latest_already_addressed=True)if value in ("0", "false", "no"):- return queryset.exclude(latest_already_addressed_value="true")+ # `=False`, not `exclude(=True)`: a report with no parseable judgment holds NULL, and+ # "not already addressed" has never covered reports nobody judged.+ return queryset.filter(latest_already_addressed=False)raise serializers.ValidationError({"already_addressed": f"Invalid value: {raw!r}. Allowed: true, false."})def _apply_signal_report_inbox_view_filter(self, queryset):@@ -1545,12 +1541,13 @@ class SignalReportViewSet(if inbox_view == "actionable":return queryset.filter(status=SignalReport.Status.READY,- latest_actionability_value=ActionabilityChoice.IMMEDIATELY_ACTIONABLE.value,- ).exclude(self._implementation_pr_report_filter() | Q(latest_already_addressed_value="true"))+ latest_actionability=ActionabilityChoice.IMMEDIATELY_ACTIONABLE.value,+ latest_already_addressed=False,+ ).exclude(self._implementation_pr_report_filter())if inbox_view == "needs_input":return queryset.filter(status=SignalReport.Status.PENDING_INPUT,- latest_actionability_value=ActionabilityChoice.REQUIRES_HUMAN_INPUT.value,+ latest_actionability=ActionabilityChoice.REQUIRES_HUMAN_INPUT.value,)if inbox_view == "needs_decision":return queryset.filter(@@ -1558,7 +1555,7 @@ class SignalReportViewSet(| (Q(status__in=[SignalReport.Status.READY, SignalReport.Status.PENDING_INPUT],- latest_actionability_value__in=[+ latest_actionability__in=[ActionabilityChoice.IMMEDIATELY_ACTIONABLE.value,ActionabilityChoice.REQUIRES_HUMAN_INPUT.value,],@@ -1573,12 +1570,12 @@ class SignalReportViewSet(if inbox_view == "dismissed":return queryset.filter(status=SignalReport.Status.SUPPRESSED)if inbox_view == "not_actionable":- return queryset.filter(latest_actionability_value=ActionabilityChoice.NOT_ACTIONABLE.value)+ return queryset.filter(latest_actionability=ActionabilityChoice.NOT_ACTIONABLE.value)return querysetdef _annotate_signal_report_status_rank(self, queryset):# `ordering=status` uses semantic stage rank (annotation), not lexicographic `status` column order.- # `status=ready` splits into two virtual stages (requires `latest_actionability_value`):+ # `status=ready` splits into two virtual stages:# 0 = ready + actionable (or no judgment yet), 1 = ready + not_actionable; then other stages.return queryset.annotate(pipeline_status_rank=Case(@@ -1630,41 +1627,6 @@ class SignalReportViewSet())- def _latest_actionability_field(self, field: str):- return Subquery(- SignalReportArtefact.objects.filter(- report_id=OuterRef("id"),- type=SignalReportArtefact.ArtefactType.ACTIONABILITY_JUDGMENT,- content__startswith="{",- )- .order_by("-created_at")- .annotate(- _actionability_val=Func(- Cast(F("content"), output_field=JSONField()),- Value(field),- function="jsonb_extract_path_text",- output_field=CharField(),- ),- )- .values("_actionability_val")[:1],- output_field=CharField(),- )-- def _annotate_latest_actionability(self, queryset):- return queryset.annotate(latest_actionability_value=self._latest_actionability_field("actionability"))-- def _annotate_latest_already_addressed(self, queryset):- return queryset.annotate(latest_already_addressed_value=self._latest_actionability_field("already_addressed"))-- def _needs_already_addressed_annotation(self) -> bool:- # A second correlated subquery over the same artefact row, so it is worth carrying only for- # the two request shapes that read it: the `already_addressed` filter, and the Actionable- # view, which hides reports whose issue is already being handled.- raw = self.request.query_params.get("already_addressed")- if raw is not None and raw.strip():- return True- return self.request.query_params.get("view") == "actionable"-def _needs_priority_annotation(self) -> bool:# The priority value is a correlated subquery too, and the serializer renders priority from# the prefetched artefacts instead, so only a priority filter or a priority sort needs it.