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): cache the newest actionability judgment on the report row (#104927)

posthog[bot]cf447346d232
diff --git a/posthog/test/repo_invariants/setup_receivers_baseline.txt b/posthog/test/repo_invariants/setup_receivers_baseline.txt
index 783cd6f048ae..9ddb384a3336 100644
--- a/posthog/test/repo_invariants/setup_receivers_baseline.txt
+++ b/posthog/test/repo_invariants/setup_receivers_baseline.txt
@@ -102,6 +102,7 @@ post_delete:products.managed_warehouse.backend.models._observe_duckgres_server_d
post_delete:products.replay_vision.backend.media_expiry.expire_media_asset
post_delete:products.signals.backend.receivers.mark_scout_suggestions_stale_on_fleet_change
post_delete:products.signals.backend.receivers.reconcile_report_embedding_on_verdict_deleted
+post_delete:products.signals.backend.receivers.sync_report_latest_actionability_on_delete
post_delete:products.signals.backend.receivers.sync_suggested_reviewer_index_on_delete
post_delete:products.signals.backend.receivers.tombstone_report_embedding_on_hard_delete
post_delete:products.slack_app.backend.signals.invalidate_repo_list_on_user_github_change
@@ -222,6 +223,7 @@ post_save:products.signals.backend.receivers.reconcile_report_embedding_on_verdi
post_save:products.signals.backend.receivers.schedule_handover_for_report_change
post_save:products.signals.backend.receivers.schedule_handover_for_work_change
post_save:products.signals.backend.receivers.schedule_implementation_handover
+post_save:products.signals.backend.receivers.sync_report_latest_actionability_on_save
post_save:products.signals.backend.receivers.sync_suggested_reviewer_index_on_save
post_save:products.signals.backend.receivers.sync_task_run_pr_to_assignments
post_save:products.signals.backend.receivers.tombstone_report_embedding_on_delete
diff --git a/products/signals/backend/facade/api.py b/products/signals/backend/facade/api.py
index 54a4153225ce..b67ecb4947f4 100644
--- a/products/signals/backend/facade/api.py
+++ b/products/signals/backend/facade/api.py
@@ -1,6 +1,6 @@
import uuid
import dataclasses
-from collections.abc import Callable, Sequence
+from collections.abc import Callable, Iterator, Sequence
from datetime import UTC, datetime, timedelta
from typing import TYPE_CHECKING, Any
@@ -28,6 +28,7 @@ from products.signals.backend.artefact_schemas import (
from products.signals.backend.contracts import DIRECT_STEERABLE_SOURCES, SIGNAL_VARIANT_LOOKUP, SignalRemediation
from products.signals.backend.enums import SIGNAL_SOURCE_PRODUCT_LABELS, SignalSourceProduct
from products.signals.backend.models import SignalReport, SignalScoutConfig, SignalScoutRun, SignalSourceConfig
+from products.signals.backend.report_actionability_repair import RepairedBatch, repair_latest_actionability
from products.signals.backend.scout_harness.run_gates import (
# Re-exported so the workflows endpoint can branch on why a fire was refused without reaching
# into the scout harness. Every decision behind them stays Signals-side.
@@ -1120,3 +1121,14 @@ def delete_scout_for_source(*, team: "Team", source_product: str, config_id: str
pass # Already archived; the config is the orphan being cleaned up.
config.delete()
return True
+
+
+def repair_report_actionability_cache(
+ *, team_id: int | None, batch_size: int, after: str | None = None
+) -> Iterator[RepairedBatch]:
+ """Recompute the cached actionability of every report from its artefact log, in batches.
+
+ For the `backfill_report_actionability` command. Receivers keep the cache current on every
+ artefact write, so this only repairs rows that drifted.
+ """
+ return repair_latest_actionability(team_id=team_id, batch_size=batch_size, after=after)
diff --git a/products/signals/backend/management/AGENTS.md b/products/signals/backend/management/AGENTS.md
index 76948bd88aea..11db84720ebf 100644
--- a/products/signals/backend/management/AGENTS.md
+++ b/products/signals/backend/management/AGENTS.md
@@ -183,6 +183,22 @@ records. `--batch-size` bounds each page; the printed `--after` cursor resumes i
The command is idempotent and does not call GitHub, change report state, or enqueue
reviewers. See `docs/internal/signals-pr-lifecycle.md` for rollout and cleanup.
+## Repairing a report's cached actionability
+
+`SignalReport.latest_actionability` and `latest_already_addressed` cache the two values of a report's newest `actionability_judgment` artefact, so the inbox list can sort and filter on a column instead of walking the artefact log once per report.
+A `post_save` / `post_delete` receiver maintains them and a migration filled the historical rows, so this command is a repair rather than a routine job.
+Run it when the columns are suspected to disagree with the artefact log, for example after a bulk write that bypassed Django signals.
+
+```bash
+# Every team
+uv run manage.py backfill_report_actionability
+
+# One team, smaller pages, resuming after the report id an earlier run printed
+uv run manage.py backfill_report_actionability --team-id 1 --batch-size 100 --after <report-id>
+```
+
+Idempotent. It recomputes each report from its artefacts and writes only the rows that disagree.
+
## Tips
- Compare runs by saving output: `list_signal_reports --json > run_baseline.json`
diff --git a/products/signals/backend/management/commands/backfill_report_actionability.py b/products/signals/backend/management/commands/backfill_report_actionability.py
new file mode 100644
index 000000000000..5e087529e806
--- /dev/null
+++ b/products/signals/backend/management/commands/backfill_report_actionability.py
@@ -0,0 +1,26 @@
+from argparse import ArgumentParser
+from typing import cast
+
+from django.core.management.base import BaseCommand
+
+from products.signals.backend.facade.api import repair_report_actionability_cache
+
+
+class Command(BaseCommand):
+ help = "Recompute each report's cached actionability from its artefact log. Safe to rerun."
+
+ def add_arguments(self, parser: ArgumentParser) -> None:
+ parser.add_argument("--team-id", type=int, help="Limit to one team. Omitted means every team.")
+ parser.add_argument("--batch-size", type=int, default=500)
+ parser.add_argument("--after", help="Resume after this report id, as printed by an earlier run.")
+
+ def handle(self, *args: object, **options: object) -> None:
+ scanned = fixed = 0
+ for batch in repair_report_actionability_cache(
+ team_id=cast(int | None, options["team_id"]),
+ batch_size=max(1, min(cast(int, options["batch_size"]), 5000)),
+ after=cast(str | None, options["after"]),
+ ):
+ scanned += batch.scanned
+ fixed += batch.corrected
+ self.stdout.write(f"Scanned {scanned} reports, corrected {fixed}; resume after {batch.cursor}")
diff --git a/products/signals/backend/migrations/0153_signalreport_latest_actionability.py b/products/signals/backend/migrations/0153_signalreport_latest_actionability.py
new file mode 100644
index 000000000000..4b210d889175
--- /dev/null
+++ b/products/signals/backend/migrations/0153_signalreport_latest_actionability.py
@@ -0,0 +1,22 @@
+# Generated by Django 5.2.17 on 2026-09-23 05:46
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("signals", "0152_alter_signalscoutsuggestionset_status"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="signalreport",
+ name="latest_actionability",
+ field=models.CharField(blank=True, max_length=30, null=True),
+ ),
+ migrations.AddField(
+ model_name="signalreport",
+ name="latest_already_addressed",
+ field=models.BooleanField(blank=True, null=True),
+ ),
+ ]
diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txt
index 5b086500b494..9453329abfd3 100644
--- a/products/signals/backend/migrations/max_migration.txt
+++ b/products/signals/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0152_alter_signalscoutsuggestionset_status
+0153_signalreport_latest_actionability
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.py
index 271e60d38160..463a0268a3fe 100644
--- a/products/signals/backend/models.py
+++ b/products/signals/backend/models.py
@@ -1,3 +1,4 @@
+import json
import uuid
import logging
from collections import defaultdict
@@ -16,6 +17,7 @@ from django.utils.functional import Promise
from asgiref.sync import async_to_sync
from pydantic import ValidationError
+from posthog.dataclasses import frozen
from posthog.migration_helpers import deprecate_field
from posthog.models.activity_logging.model_activity import ModelActivityMixin
from posthog.models.scoping.manager import EnvironmentScopedManager
@@ -401,6 +403,12 @@ class SignalReport(UUIDModel):
# Deprecated - unused
relevant_user_count = deprecate_field(models.IntegerField(blank=True, null=True))
+ # Cached from the newest `actionability_judgment` artefact so the inbox list can sort and filter
+ # on a column instead of casting artefact JSON for every report in the team. Receivers in
+ # receivers.py keep them current. NULL means the report has no parseable judgment.
+ latest_actionability = models.CharField(max_length=30, null=True, blank=True)
+ latest_already_addressed = models.BooleanField(null=True, blank=True)
+
class Meta:
indexes = [
models.Index(fields=["team", "status", "promoted_at"]),
@@ -583,6 +591,37 @@ class SignalReport(UUIDModel):
updated_fields.update(["status", "updated_at"])
return list(updated_fields)
+ @classmethod
+ def refresh_latest_actionability(cls, *, team_id: int, report_id: Any) -> bool:
+ """Recompute the cached actionability from the artefact log and store it on the row.
+
+ Returns whether the row changed, and False when the report no longer exists. The row is
+ locked for the read and the write, so two judgment writers cannot interleave: without the
+ lock, a writer that read the log before a concurrent judgment committed would overwrite
+ the cache with the older value once the other writer released the row.
+ """
+ with transaction.atomic():
+ # FOR NO KEY UPDATE, not FOR UPDATE: an artefact insert holds KEY SHARE on its report
+ # through the foreign key, and FOR UPDATE conflicts with that, so two concurrent
+ # judgment writers would deadlock.
+ row = (
+ cls.objects.select_for_update(no_key=True)
+ .filter(team_id=team_id, id=report_id)
+ .values_list("latest_actionability", "latest_already_addressed")
+ .first()
+ )
+ if row is None:
+ return False
+ latest = SignalReportArtefact.latest_actionability(report_id)
+ if row == (latest.actionability, latest.already_addressed):
+ return False
+ # `update()`, not `save()`: refreshing a cache must not bump `updated_at`, which the
+ # inbox sorts on, or fire the report's own save receivers.
+ cls.objects.filter(id=report_id).update(
+ latest_actionability=latest.actionability, latest_already_addressed=latest.already_addressed
+ )
+ return True
+
def restore_target_status(self) -> "SignalReport.Status":
"""
The status a suppressed report should return to on restore (un-archive).
@@ -1148,6 +1187,21 @@ def signal_report_artefact_type_choices() -> list[tuple[str, str | Promise]]:
return list(SignalReportArtefact.ArtefactType.choices)
+@frozen
+class LatestActionability:
+ """The `actionability` and `already_addressed` of a report's newest parseable judgment.
+
+ Both `None` when the report has no `actionability_judgment` whose content is a JSON object.
+ """
+
+ actionability: str | None
+ already_addressed: bool | None
+
+ @classmethod
+ def unjudged(cls) -> "LatestActionability":
+ return cls(actionability=None, already_addressed=None)
+
+
class SignalReportArtefact(UUIDModel):
class ArtefactType(models.TextChoices):
VIDEO_SEGMENT = "video_segment"
@@ -1333,6 +1387,31 @@ class SignalReportArtefact(UUIDModel):
)
return {str(report_id): channel_id for report_id, channel_id, deleted in rows if deleted is False}
+ @classmethod
+ def latest_actionability(cls, report_id: Any) -> LatestActionability:
+ """The newest parseable `actionability_judgment` of a report, as `SignalReport` caches it.
+
+ Entries that are not JSON objects are skipped rather than ending the search, so one
+ malformed row cannot hide the judgment written before it.
+ """
+ rows = cls.objects.filter(report_id=report_id, type=cls.ArtefactType.ACTIONABILITY_JUDGMENT).order_by(
+ "-created_at"
+ )
+ for content in rows.values_list("content", flat=True).iterator(chunk_size=20):
+ 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")
+ return LatestActionability(
+ actionability=actionability if isinstance(actionability, str) else None,
+ already_addressed=already_addressed if isinstance(already_addressed, bool) else None,
+ )
+ return LatestActionability.unjudged()
+
@classmethod
def _create(
cls,
diff --git a/products/signals/backend/receivers.py b/products/signals/backend/receivers.py
index 62a4b4051ea9..9b0dd54d073b 100644
--- a/products/signals/backend/receivers.py
+++ b/products/signals/backend/receivers.py
@@ -649,6 +649,28 @@ def reconcile_report_embedding_on_verdict_saved(
_reconcile_report_embedding_with_verdict(instance)
+def _sync_report_latest_actionability(instance: SignalReportArtefact) -> None:
+ if instance.type != SignalReportArtefact.ArtefactType.ACTIONABILITY_JUDGMENT:
+ return
+ SignalReport.refresh_latest_actionability(team_id=instance.team_id, report_id=instance.report_id)
+
+
+@receiver(post_save, sender=SignalReportArtefact)
+def sync_report_latest_actionability_on_save(
+ sender: type[SignalReportArtefact],
+ instance: SignalReportArtefact,
+ created: bool,
+ **kwargs: Any,
+) -> None:
+ """Keep the report's cached actionability equal to its newest judgment.
+
+ On the artefact write path rather than at each producer, because a judgment reaches a report
+ from the research pipeline, a custom agent, a scout edit, the artefact REST API and the MCP
+ tools. Not gated on `created`, because `update_content` edits a judgment row in place.
+ """
+ _sync_report_latest_actionability(instance)
+
+
def _deleted_directly(origin: Any) -> bool:
"""Whether a delete was issued against artefacts themselves rather than cascading from a report.
@@ -683,6 +705,23 @@ def reconcile_report_embedding_on_verdict_deleted(
_reconcile_report_embedding_with_verdict(instance)
+@receiver(post_delete, sender=SignalReportArtefact)
+def sync_report_latest_actionability_on_delete(
+ sender: type[SignalReportArtefact],
+ instance: SignalReportArtefact,
+ origin: Any = None,
+ **kwargs: Any,
+) -> None:
+ """Deleting the newest judgment reverts the report to the one before it.
+
+ Skipped for a cascade, where the report itself is going away, so a team teardown does not pay
+ a read and a write per artefact for a row nobody will read.
+ """
+ if not _deleted_directly(origin):
+ return
+ _sync_report_latest_actionability(instance)
+
+
@receiver(post_save, sender=SignalReport)
def capture_status_change_analytics(
sender: type[SignalReport],
diff --git a/products/signals/backend/report_actionability_repair.py b/products/signals/backend/report_actionability_repair.py
new file mode 100644
index 000000000000..c0a04bb8f085
--- /dev/null
+++ b/products/signals/backend/report_actionability_repair.py
@@ -0,0 +1,39 @@
+from collections.abc import Iterator
+
+from posthog.dataclasses import frozen
+
+from products.signals.backend.models import SignalReport
+
+
+@frozen
+class RepairedBatch:
+ scanned: int
+ corrected: int
+ cursor: str
+
+
+def repair_latest_actionability(
+ *, team_id: int | None, batch_size: int, after: str | None = None
+) -> Iterator[RepairedBatch]:
+ """Recompute `SignalReport.latest_actionability` and `latest_already_addressed` from the
+ artefact log, one batch of reports at a time, starting after report id `after`.
+
+ The receivers in receivers.py maintain both columns on every artefact write, so this is a
+ repair for rows that drifted, not a routine job. Safe to rerun: each report is recomputed
+ under its row lock and written only when it disagrees with its artefacts.
+ """
+ reports = SignalReport.objects.all()
+ if team_id is not None:
+ reports = reports.filter(team_id=team_id)
+ reports = reports.order_by("id")
+ while True:
+ page = reports.filter(id__gt=after) if after else reports
+ rows = list(page.values_list("id", "team_id")[:batch_size])
+ if not rows:
+ return
+ after = str(rows[-1][0])
+ corrected = sum(
+ SignalReport.refresh_latest_actionability(team_id=row_team_id, report_id=report_id)
+ for report_id, row_team_id in rows
+ )
+ yield RepairedBatch(scanned=len(rows), corrected=corrected, cursor=after)
diff --git a/products/signals/backend/test/test_backfill_report_actionability.py b/products/signals/backend/test/test_backfill_report_actionability.py
new file mode 100644
index 000000000000..62b677e33a4d
--- /dev/null
+++ b/products/signals/backend/test/test_backfill_report_actionability.py
@@ -0,0 +1,46 @@
+import json
+
+from posthog.test.base import BaseTest
+
+from django.core.management import call_command
+
+from products.signals.backend.models import SignalReport, SignalReportArtefact
+
+
+class TestBackfillReportActionability(BaseTest):
+ def _report(self, *, actionability: str | None) -> SignalReport:
+ report = SignalReport.objects.create(
+ team=self.team,
+ status=SignalReport.Status.READY,
+ title="t",
+ summary="s",
+ signal_count=1,
+ total_weight=1.0,
+ )
+ if actionability is not None:
+ SignalReportArtefact.objects.create(
+ team=self.team,
+ report=report,
+ type=SignalReportArtefact.ArtefactType.ACTIONABILITY_JUDGMENT,
+ content=json.dumps(
+ {"explanation": "x", "actionability": actionability, "already_addressed": True},
+ ),
+ )
+ return report
+
+ def _cached(self, report: SignalReport) -> tuple[str | None, bool | None]:
+ row = SignalReport.objects.filter(id=report.id).values("latest_actionability", "latest_already_addressed")[0]
+ return row["latest_actionability"], row["latest_already_addressed"]
+
+ def test_repairs_a_report_whose_cache_disagrees_with_its_artefacts(self):
+ drifted = self._report(actionability="requires_human_input")
+ never_judged = self._report(actionability=None)
+ SignalReport.objects.filter(id=drifted.id).update(
+ latest_actionability="not_actionable", latest_already_addressed=False
+ )
+ SignalReport.objects.filter(id=never_judged.id).update(latest_actionability="immediately_actionable")
+
+ call_command("backfill_report_actionability", "--team-id", str(self.team.id), "--batch-size", "1")
+
+ assert self._cached(drifted) == ("requires_human_input", True)
+ assert self._cached(never_judged) == (None, None)
diff --git a/products/signals/backend/test/test_signal_report_artefact_model.py b/products/signals/backend/test/test_signal_report_artefact_model.py
index 88ea72794e60..dea91f13e0c2 100644
--- a/products/signals/backend/test/test_signal_report_artefact_model.py
+++ b/products/signals/backend/test/test_signal_report_artefact_model.py
@@ -7,6 +7,8 @@ from parameterized import parameterized
from posthog.models import Team
from products.signals.backend.artefact_schemas import (
+ ActionabilityAssessment,
+ ActionabilityChoice,
ArtefactContentValidationError,
Dismissal,
NoteArtefact,
@@ -299,6 +301,57 @@ class TestSignalReportArtefactHelpers(BaseTest):
# Current status is the latest row.
assert json.loads(rows[1].content)["priority"] == "P0"
+ def _append_actionability(
+ self, report: SignalReport, choice: str, *, already_addressed: bool = False
+ ) -> SignalReportArtefact:
+ return SignalReportArtefact.append_status(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ content=ActionabilityAssessment(
+ actionability=ActionabilityChoice(choice),
+ already_addressed=already_addressed,
+ explanation="because",
+ ),
+ attribution=ArtefactAttribution.system(),
+ )
+
+ def _cached_actionability(self, report: SignalReport) -> tuple[str | None, bool | None]:
+ row = SignalReport.objects.filter(id=report.id).values("latest_actionability", "latest_already_addressed")[0]
+ return row["latest_actionability"], row["latest_already_addressed"]
+
+ def test_cached_actionability_follows_the_newest_judgment(self):
+ report = self._report()
+ assert self._cached_actionability(report) == (None, None)
+
+ first = self._append_actionability(report, "not_actionable")
+ assert self._cached_actionability(report) == ("not_actionable", False)
+
+ second = self._append_actionability(report, "immediately_actionable", already_addressed=True)
+ assert self._cached_actionability(report) == ("immediately_actionable", True)
+
+ second.update_content(
+ json.dumps({"explanation": "x", "actionability": "requires_human_input", "already_addressed": False})
+ )
+ assert self._cached_actionability(report) == ("requires_human_input", False)
+
+ second.delete()
+ assert self._cached_actionability(report) == ("not_actionable", False)
+
+ first.delete()
+ assert self._cached_actionability(report) == (None, None)
+
+ def test_cached_actionability_skips_a_judgment_that_is_not_an_object(self):
+ report = self._report()
+ self._append_actionability(report, "immediately_actionable")
+ SignalReportArtefact.objects.create(
+ team=self.team,
+ report=report,
+ type=SignalReportArtefact.ArtefactType.ACTIONABILITY_JUDGMENT,
+ content='"not an object"',
+ )
+
+ assert self._cached_actionability(report) == ("immediately_actionable", False)
+
def test_append_status_rejects_log_content(self):
report = self._report()
with self.assertRaises(ValueError):