: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
fix(signals): send one inbox card per report, ever (#86471)
Georgiy Tarasovf6c25c80c5f1
diff --git a/products/signals/backend/migrations/0113_signalreport_inbox_notified_at.py b/products/signals/backend/migrations/0113_signalreport_inbox_notified_at.pynew file mode 100644index 000000000000..805aa6b5493d--- /dev/null+++ b/products/signals/backend/migrations/0113_signalreport_inbox_notified_at.py@@ -0,0 +1,17 @@+# Generated by Django 5.2.17 on 2026-08-20 13:04++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("signals", "0111_signalreport_signals_researched"),+ ]++ operations = [+ migrations.AddField(+ model_name="signalreport",+ name="inbox_notified_at",+ field=models.DateTimeField(blank=True, null=True),+ ),+ ]diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txtindex 35273f6f3b02..c5c69aa5e060 100644--- a/products/signals/backend/migrations/max_migration.txt+++ b/products/signals/backend/migrations/max_migration.txt@@ -1 +1 @@-0111_signalreport_signals_researched+0113_signalreport_inbox_notified_atdiff --git a/products/signals/backend/models.py b/products/signals/backend/models.pyindex e44058b07859..516f70d188fd 100644--- a/products/signals/backend/models.py+++ b/products/signals/backend/models.py@@ -288,6 +288,12 @@ class SignalReport(UUIDModel):# recount it against SignalTeamConfig.max_reports_per_day. Null for reports that predate the# field or never surfaced.first_visible_at = models.DateTimeField(null=True, blank=True)+ # When the report's inbox notification was dispatched. A report notifies once, ever: research+ # settles every time a new signal carries the report to its next bucket, and each settle starts+ # the notification workflow again, so without this a report re-notified per research pass. Set+ # once and never cleared, so it survives past Temporal's history retention window — a workflow+ # ID de-duplication would not. Null for reports that never notified or predate the field.+ inbox_notified_at = models.DateTimeField(null=True, blank=True)# Video segment clustering fieldscluster_centroid = deprecate_field(diff --git a/products/signals/backend/temporal/inbox_notification.py b/products/signals/backend/temporal/inbox_notification.pyindex be016f3f2b46..6d7ed7604fc0 100644--- a/products/signals/backend/temporal/inbox_notification.py+++ b/products/signals/backend/temporal/inbox_notification.py@@ -1,8 +1,10 @@"""Decides when to send a report's inbox Slack notification.-Every actionable report notifies; the PR is enrichment, not a gate. With an auto-start task we-wait (bounded by a timeout) for the PR so the card can link it, then notify either way; with no-task we notify immediately. Actionability is enforced downstream (READY status + persisted+Every actionable report notifies once, ever; the PR is enrichment, not a gate. With an auto-start+task we wait (bounded by a timeout) for the PR so the card can link it, then notify either way; with+no task we notify immediately. Research settles again every time a new signal carries the report to+its next bucket, and every settle starts this workflow, so `SignalReport.inbox_notified_at` is what+keeps one report to one card. Actionability is enforced downstream (READY status + persistedpriority). Posting lives in `dispatch_inbox_item_notifications`; this workflow governs timing."""@@ -12,12 +14,14 @@ from dataclasses import dataclassfrom datetime import timedeltafrom django.conf import settings+from django.utils import timezoneimport structlogimport temporaliofrom temporalio import workflowfrom temporalio.common import RetryPolicy+from posthog.dataclasses import frozenfrom posthog.models import Teamfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.common.scoped import scoped_temporal@@ -37,14 +41,27 @@ class InboxNotificationInput:report_id: str-@dataclass+@frozenclass InboxNotificationState:has_implementation_task: boolpr_available: booltask_terminal: bool+ # Whether the report already notified. Defaults to False so a history written before this field+ # decodes to the old behavior and replays through the same commands (see+ # .claude/rules/temporal-workflow-versioning.md, the activity-output gating pattern).+ already_notified: bool = Falsedef _compute_inbox_notification_state(team_id: int, report_id: str) -> InboxNotificationState:+ already_notified = SignalReport.objects.filter(+ id=report_id, team_id=team_id, inbox_notified_at__isnull=False+ ).exists()+ if already_notified:+ # Nothing downstream matters once the card is out, and skipping the task lookups keeps a+ # re-researched report from paying for the PR wait it will not use.+ return InboxNotificationState(+ has_implementation_task=False, pr_available=False, task_terminal=False, already_notified=True+ )impl_task_ids = [run.task_idfor run in SignalReport.associated_task_runs(@@ -76,6 +93,19 @@ async def get_inbox_notification_state_activity(input: InboxNotificationInput) -)+def _claim_inbox_notification(team_id: int, report_id: str) -> bool:+ """Stamp `inbox_notified_at`, returning False when another sender already claimed the report."""+ return bool(+ SignalReport.objects.filter(id=report_id, team_id=team_id, inbox_notified_at__isnull=True).update(+ inbox_notified_at=timezone.now()+ )+ )+++def _release_inbox_notification_claim(team_id: int, report_id: str) -> None:+ SignalReport.objects.filter(id=report_id, team_id=team_id).update(inbox_notified_at=None)++def _send_report_inbox_notifications(team_id: int, report_id: str) -> int:# Guard on status: a deferred wait can outlast the READY state (suppressed/deleted/re-promoted).report = SignalReport.objects.filter(id=report_id, team_id=team_id).only("status").first()@@ -99,20 +129,44 @@ def _send_report_inbox_notifications(team_id: int, report_id: str) -> int:# Re-derive source products at send time so a deferred notification reflects the current signals.signals = fetch_signals_for_report_sync(team, report_id)source_products = sorted({s["source_product"] for s in signals if s.get("source_product")})+# Point any support ticket that raised this report at it. Shares this function's READY guard.- # Guarded here as well as inside: the write-back is supplementary, and letting it raise would fail- # the activity before the Slack notification below, so a retry loop would drop the notification- # entirely over a side errand.+ # This runs above the claim, so it also runs on a settle that sends no card. A note is per ticket+ # and not per report, so a ticket that joins the report after its card still needs one, and the+ # note's dedupe key stops a repeat from posting twice to the same ticket. Guarded here as well as+ # inside: the write-back is supplementary, and letting it raise would fail the activity before the+ # Slack notification below, so a retry loop would drop the notification entirely over a side errand.try:post_report_findings_to_tickets(team, report_id, signals)except Exception:logger.exception("inbox notification: support write-back failed", report_id=report_id, team_id=team_id)- return dispatch_inbox_item_notifications(- report_id=report_id,- team_id=team_id,- source_products=source_products,- signals=signals,- )++ # Claim the report immediately before the send. One conditional UPDATE, so a concurrent settle that+ # got past the workflow's already-notified check loses here instead of sending a second card.+ # Nothing else runs under the claim, because a worker that dies while holding it never reaches the+ # release below and leaves the report stamped for a card it never sent. Keeping the covered span as+ # short as the send itself is what bounds that window.+ if not _claim_inbox_notification(team_id, report_id):+ logger.info("inbox notification skipped: already notified", report_id=report_id, team_id=team_id)+ return 0++ try:+ sent = dispatch_inbox_item_notifications(+ report_id=report_id,+ team_id=team_id,+ source_products=source_products,+ signals=signals,+ )+ except Exception:+ # Release so a retry or a later settle can still send the card.+ _release_inbox_notification_claim(team_id, report_id)+ raise+ if not sent:+ # Nothing went out — no channel configured yet, or the report failed the dispatcher's own+ # actionability check. Releasing lets a later settle try again, so a team that connects Slack+ # after its first report still gets a card for it.+ _release_inbox_notification_claim(team_id, report_id)+ return sent@temporalio.activity.defn@@ -137,7 +191,13 @@ class SignalReportInboxNotificationWorkflow:log_ctx = {"report_id": inputs.report_id, "team_id": inputs.team_id}state = await self._fetch_state(inputs)- if state.has_implementation_task and not state.pr_available and not state.task_terminal:+ if state.already_notified:+ # The card is out, so nothing is left to wait for and the PR wait is skipped. The send+ # activity still runs, because it also carries the support write-back, which is per ticket+ # and not per report: a ticket that joined this report after its card still needs its note.+ # The claim inside that activity is what holds the report to one card.+ workflow.logger.info("inbox notification: already notified, skipping the PR wait", extra=log_ctx)+ elif state.has_implementation_task and not state.pr_available and not state.task_terminal:workflow.logger.info("inbox notification: implementation task present, waiting for its PR",extra={**log_ctx, "timeout_seconds": timeout_seconds},@@ -147,9 +207,14 @@ class SignalReportInboxNotificationWorkflow:await workflow.sleep(timedelta(seconds=poll_seconds))elapsed += poll_secondsstate = await self._fetch_state(inputs)- if state.pr_available or state.task_terminal:+ # `already_notified` ends the wait as well. A concurrent settle that sent the card makes+ # the state activity report no PR and no terminal task, so without this test the break+ # condition can never be met again and the wait runs the full timeout for nothing.+ if state.already_notified or state.pr_available or state.task_terminal:break- if state.pr_available:+ if state.already_notified:+ wait_outcome = "notified_by_another_run"+ elif state.pr_available:wait_outcome = "pr_opened"elif state.task_terminal:wait_outcome = "task_ended_without_pr"diff --git a/products/signals/backend/test/test_inbox_notification_workflow.py b/products/signals/backend/test/test_inbox_notification_workflow.pyindex c93316f47202..e421e27eb98e 100644--- a/products/signals/backend/test/test_inbox_notification_workflow.py+++ b/products/signals/backend/test/test_inbox_notification_workflow.py@@ -5,6 +5,7 @@ from unittest.mock import patchfrom django.apps import appsfrom django.test import override_settings+from django.utils import timezonefrom temporalio import activityfrom temporalio.testing import WorkflowEnvironment@@ -160,15 +161,22 @@ WAIT = InboxNotificationState(has_implementation_task=True, pr_available=False,NO_TASK = InboxNotificationState(has_implementation_task=False, pr_available=False, task_terminal=False)PR_READY = InboxNotificationState(has_implementation_task=True, pr_available=True, task_terminal=False)TERMINAL = InboxNotificationState(has_implementation_task=True, pr_available=False, task_terminal=True)+ALREADY_NOTIFIED = InboxNotificationState(+ has_implementation_task=False, pr_available=False, task_terminal=False, already_notified=True+)@pytest.mark.asyncio[email protected]("ends_the_wait", [PR_READY, ALREADY_NOTIFIED], ids=["pr_opened", "notified_elsewhere"])@override_settings(SIGNALS_INBOX_PR_NOTIFICATION_TIMEOUT_SECONDS=10, SIGNALS_INBOX_PR_NOTIFICATION_POLL_SECONDS=1)-async def test_workflow_waits_then_notifies_when_pr_opens():- recorder = _Recorder([WAIT, WAIT, PR_READY])+async def test_workflow_ends_the_pr_wait_as_soon_as_the_state_resolves(ends_the_wait):+ # ALREADY_NOTIFIED has to end the wait as well. A concurrent settle that sent the card leaves the+ # state activity reporting no PR and no terminal task, so a run that watches only those two can+ # never meet its break condition again and polls the full timeout for a card it cannot send.+ recorder = _Recorder([WAIT, WAIT, ends_the_wait])sent = await _run_workflow(recorder)assert sent == 1- assert recorder.state_calls == 3+ assert recorder.state_calls == 3 # the wait ends on the resolving fetch, not at the timeoutassert recorder.dispatch_calls == 1@@ -197,3 +205,80 @@ async def test_workflow_notifies_even_without_pr(states, timeout_seconds, polls)assert recorder.state_calls >= 2 # initial fetch + at least one poll while waiting for the PRelse:assert recorder.state_calls == 1 # decided on the first fetch — no task means no polling+++def test_send_stamps_the_report_and_refuses_a_second_send(team):+ """One report, one card. A report re-researches whenever a new signal carries it to its next+ bucket, and every settle starts this workflow again, so the second send must be refused. The+ support write-back still runs on both, because its note is per ticket rather than per report: a+ ticket that joins the report after its card has had no note yet and still needs one."""+ report = _make_report(team)+ with (+ patch("products.signals.backend.slack_inbox_notifications.dispatch_inbox_item_notifications") as dispatch,+ patch("products.signals.backend.temporal.inbox_notification.post_report_findings_to_tickets") as writeback,+ ):+ dispatch.return_value = 1+ first = _send_report_inbox_notifications(team.id, str(report.id))+ second = _send_report_inbox_notifications(team.id, str(report.id))++ assert (first, second) == (1, 0)+ assert dispatch.call_count == 1+ assert writeback.call_count == 2+ report.refresh_from_db()+ assert report.inbox_notified_at is not None++[email protected]("outcome", ["sent_nothing", "raised", "raised_before_dispatch"])+def test_send_releases_the_claim_when_no_card_went_out(team, outcome):+ """A report whose team has no Slack channel yet must stay eligible. Without the release it would+ burn its one notification on a dispatch that sent nothing, and never get a card. A raise before the+ dispatch, such as the unretried ClickHouse read that re-derives the signals, must leave the report+ eligible too; the claim is taken below that read, so there is nothing left to release."""+ report = _make_report(team)+ with patch("products.signals.backend.slack_inbox_notifications.dispatch_inbox_item_notifications") as dispatch:+ if outcome == "raised_before_dispatch":+ with patch(+ "products.signals.backend.temporal.inbox_notification.fetch_signals_for_report_sync",+ side_effect=RuntimeError("clickhouse timed out"),+ ):+ with pytest.raises(RuntimeError):+ _send_report_inbox_notifications(team.id, str(report.id))+ dispatch.assert_not_called()+ elif outcome == "raised":+ dispatch.side_effect = RuntimeError("slack is down")+ with pytest.raises(RuntimeError):+ _send_report_inbox_notifications(team.id, str(report.id))+ else:+ dispatch.return_value = 0+ assert _send_report_inbox_notifications(team.id, str(report.id)) == 0++ report.refresh_from_db()+ assert report.inbox_notified_at is None+++def test_state_reports_already_notified(team):+ report = _make_report(team)+ _link_implementation_task(team, report, pr_url=None, run_status="started")+ report.inbox_notified_at = timezone.now()+ report.save(update_fields=["inbox_notified_at"])++ state = _compute_inbox_notification_state(team.id, str(report.id))++ # The implementation task is deliberately not reported: a notified report has nothing left to+ # wait for, so the workflow must not sit through the PR timeout before finding that out.+ assert state == ALREADY_NOTIFIED+++@override_settings(SIGNALS_INBOX_PR_NOTIFICATION_TIMEOUT_SECONDS=10, SIGNALS_INBOX_PR_NOTIFICATION_POLL_SECONDS=1)+async def test_workflow_skips_the_pr_wait_when_the_report_already_notified():+ # One fetch, then straight to the send activity. A notified report has nothing left to wait for,+ # but the activity still runs because the support write-back it carries is per ticket. Refusing+ # the second card is the claim's job, covered by test_send_stamps_the_report_and_refuses_a_second_send.+ recorder = _Recorder([ALREADY_NOTIFIED])+ await _run_workflow(recorder)+ assert recorder.state_calls == 1+ assert recorder.dispatch_calls == 1