: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
feat(customer-analytics): add async send_announcement task (#70370)
Christophe Eynius Tranberg53ea91096312
diff --git a/products/customer_analytics/backend/constants.py b/products/customer_analytics/backend/constants.pyindex 803d83240644..0643f420c32a 100644--- a/products/customer_analytics/backend/constants.py+++ b/products/customer_analytics/backend/constants.py@@ -35,3 +35,7 @@ CUSTOM_PROPERTY_OPTION_COLORS = [f"preset-{i}" for i in range(1, 11)]# Bounds the fan-out so one create can't enqueue an unbounded Slack send loop.MAX_ANNOUNCEMENT_CHANNELS = 200++DELIVERY_IN_FLIGHT_ERROR = "in_flight"+DELIVERY_RATE_LIMIT_DEFERRED_ERROR = "rate_limited_deferred"+DELIVERY_INTERRUPTED_ERROR = "interrupted before confirmation; the message may have been delivered"diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.pyindex c855af589381..3281f8719c49 100644--- a/products/customer_analytics/backend/facade/api.py+++ b/products/customer_analytics/backend/facade/api.py@@ -72,6 +72,7 @@ from products.customer_analytics.backend.models import (TargetType,)from products.customer_analytics.backend.models.account import AccountProperties as _ModelAccountProperties+from products.customer_analytics.backend.tasks.tasks import send_announcementfrom products.notebooks.backend.facade import (api as notebooks,contracts as notebook_contracts,@@ -2161,6 +2162,8 @@ def get_announcement(team_id: int, short_id: str) -> contracts.AnnouncementViewdef create_announcement(*, team_id: int, user: "User", message: str, channels: list[str]) -> contracts.AnnouncementView:team = Team.objects.get(id=team_id)announcement = _announcements_logic.create_announcement(team, user, message, channels)+ # Dispatch only after the delivery rows commit; a rollback must not leave a phantom task.+ transaction.on_commit(lambda: send_announcement.delay(str(announcement.id), team_id))return _to_announcement_view(announcement)diff --git a/products/customer_analytics/backend/logic/announcements.py b/products/customer_analytics/backend/logic/announcements.pyindex a6bde3ef6f6e..79f11971acb6 100644--- a/products/customer_analytics/backend/logic/announcements.py+++ b/products/customer_analytics/backend/logic/announcements.py@@ -2,12 +2,22 @@ from __future__ import annotationsfrom typing import TYPE_CHECKING-from django.db import transaction+from django.db import models, transaction+from django.utils import timezone++import structlogfrom products.conversations.backend.facade.api import (+ SupportMessageSendError,SupportSlackChannelsUnavailable,SupportSlackNotConfigured,list_support_bot_channels,+ post_support_message,+)+from products.customer_analytics.backend.constants import (+ DELIVERY_IN_FLIGHT_ERROR,+ DELIVERY_INTERRUPTED_ERROR,+ DELIVERY_RATE_LIMIT_DEFERRED_ERROR,)from products.customer_analytics.backend.facade.contracts import AnnouncementChannelView, AnnouncementValidationErrorfrom products.customer_analytics.backend.models import Account, Announcement, AnnouncementDelivery@@ -16,6 +26,12 @@ if TYPE_CHECKING:from posthog.models.team import Teamfrom posthog.models.user import User+logger = structlog.get_logger(__name__)+++class AnnouncementRateLimited(Exception):+ pass+def create_announcement(team: Team, created_by: User, message: str, channel_ids: list[str]) -> Announcement:try:@@ -77,3 +93,126 @@ def _customer_names_by_channel(team_id: int) -> dict[str, str]:if channel_id:result.setdefault(channel_id, name)return result+++def send_pending_deliveries(announcement_id: str, team_id: int) -> None:+ announcement = Announcement.objects.for_team(team_id).filter(id=announcement_id).first()+ if not announcement:+ logger.warning("announcement_not_found", announcement_id=announcement_id, team_id=team_id)+ return++ pending = list(+ AnnouncementDelivery.objects.filter(announcement_id=announcement.id, status=AnnouncementDelivery.Status.PENDING)+ )+ if not pending:+ _recompute_announcement_status(announcement)+ return++ # A pending row still claimed in-flight means a previous run crashed mid-post; the message+ # may already be in Slack, so never re-post it.+ interrupted_ids = {delivery.id for delivery in pending if delivery.error == DELIVERY_IN_FLIGHT_ERROR}+ if interrupted_ids:+ AnnouncementDelivery.objects.for_team(team_id).filter(id__in=interrupted_ids).update(+ status=AnnouncementDelivery.Status.FAILED,+ error=DELIVERY_INTERRUPTED_ERROR,+ updated_at=timezone.now(),+ )+ pending = [delivery for delivery in pending if delivery.id not in interrupted_ids]++ if announcement.status == Announcement.Status.PENDING:+ announcement.status = Announcement.Status.SENDING+ announcement.save(update_fields=["status", "updated_at"])++ deferred = 0+ for delivery in pending:+ try:+ if not _deliver_to_channel(team_id, delivery, announcement.message):+ deferred += 1+ except SupportSlackNotConfigured:+ logger.warning("announcement_no_slack_credentials", announcement_id=announcement_id, team_id=team_id)+ AnnouncementDelivery.objects.filter(+ announcement_id=announcement.id, status=AnnouncementDelivery.Status.PENDING+ ).update(+ status=AnnouncementDelivery.Status.FAILED,+ error="SupportHog Slack is not connected",+ updated_at=timezone.now(),+ )+ deferred = 0+ break++ _recompute_announcement_status(announcement)+ logger.info(+ "announcement_sent",+ announcement_id=announcement_id,+ team_id=team_id,+ sent=announcement.sent_count,+ failed=announcement.failed_count,+ deferred=deferred,+ )+ if deferred:+ # Ride the task's autoretry backoff instead of sleeping in the worker.+ raise AnnouncementRateLimited(f"{deferred} channel(s) rate limited")+++def _deliver_to_channel(team_id: int, delivery: AnnouncementDelivery, message: str) -> bool:+ was_rate_limit_deferred = delivery.error == DELIVERY_RATE_LIMIT_DEFERRED_ERROR+ # Claim the row before posting so a crash between the Slack post and the outcome save+ # can never lead to a double post on retry.+ delivery.error = DELIVERY_IN_FLIGHT_ERROR+ delivery.save(update_fields=["error", "updated_at"])+ try:+ delivery.slack_message_ts = post_support_message(team_id, delivery.slack_channel_id, message)+ delivery.status = AnnouncementDelivery.Status.SENT+ delivery.sent_at = timezone.now()+ delivery.error = ""+ except SupportMessageSendError as e:+ if e.code == "ratelimited" and not was_rate_limit_deferred:+ # Leave the row pending for the task's autoretry; one deferral per row.+ delivery.error = DELIVERY_RATE_LIMIT_DEFERRED_ERROR+ delivery.save(update_fields=["error", "updated_at"])+ return False+ delivery.status = AnnouncementDelivery.Status.FAILED+ delivery.error = e.code[:2000]+ except SupportSlackNotConfigured:+ raise+ except Exception as e:+ delivery.status = AnnouncementDelivery.Status.FAILED+ delivery.error = str(e)[:2000]+ delivery.save(update_fields=["status", "slack_message_ts", "sent_at", "error", "updated_at"])+ logger.info(+ "announcement_channel_delivery",+ announcement_id=str(delivery.announcement_id),+ team_id=team_id,+ channel=delivery.slack_channel_id,+ status=delivery.status,+ slack_message_ts=delivery.slack_message_ts,+ error=delivery.error or None,+ )+ return True+++def _recompute_announcement_status(announcement: Announcement) -> None:+ counts = AnnouncementDelivery.objects.filter(announcement_id=announcement.id).aggregate(+ sent=models.Count("id", filter=models.Q(status=AnnouncementDelivery.Status.SENT)),+ failed=models.Count("id", filter=models.Q(status=AnnouncementDelivery.Status.FAILED)),+ pending=models.Count("id", filter=models.Q(status=AnnouncementDelivery.Status.PENDING)),+ )+ sent, failed, pending = counts["sent"], counts["failed"], counts["pending"]++ if pending:+ status = Announcement.Status.SENDING+ elif failed and sent:+ status = Announcement.Status.PARTIALLY_FAILED+ elif failed:+ status = Announcement.Status.FAILED+ else:+ status = Announcement.Status.SENT++ announcement.sent_count = sent+ announcement.failed_count = failed+ announcement.status = status+ update_fields = ["sent_count", "failed_count", "status", "updated_at"]+ if not pending and announcement.sent_at is None:+ announcement.sent_at = timezone.now()+ update_fields.append("sent_at")+ announcement.save(update_fields=update_fields)diff --git a/products/customer_analytics/backend/tasks/__init__.py b/products/customer_analytics/backend/tasks/__init__.pyindex d9d3d048f71f..e3eb8d088c53 100644--- a/products/customer_analytics/backend/tasks/__init__.py+++ b/products/customer_analytics/backend/tasks/__init__.py@@ -1,2 +1,5 @@-# Re-exported so Celery autodiscovers the task when the tasks package is imported.-from products.customer_analytics.backend.tasks.tasks import process_custom_property_sync # noqa: F401+# Re-exported so Celery autodiscovers the tasks when the tasks package is imported.+from products.customer_analytics.backend.tasks.tasks import ( # noqa: F401+ process_custom_property_sync,+ send_announcement,+)diff --git a/products/customer_analytics/backend/tasks/tasks.py b/products/customer_analytics/backend/tasks/tasks.pyindex 556540f0fdeb..b2b5196890bd 100644--- a/products/customer_analytics/backend/tasks/tasks.py+++ b/products/customer_analytics/backend/tasks/tasks.py@@ -1,8 +1,25 @@from celery import shared_task+from posthog.models.scoping import with_team_scope++from products.customer_analytics.backend.logic.announcements import send_pending_deliveriesfrom products.customer_analytics.backend.logic.custom_property_sync import run_custom_property_sync@shared_task(name="customer_analytics.process_custom_property_sync", ignore_result=True)def process_custom_property_sync(team_id: int, saved_query_id: str) -> None:run_custom_property_sync(team_id=team_id, saved_query_id=saved_query_id)+++# autoretry_for is load-bearing: bare max_retries kwargs without it are silently inert.+@shared_task(+ name="customer_analytics.send_announcement",+ ignore_result=True,+ autoretry_for=(Exception,),+ max_retries=3,+ retry_backoff=True,+ retry_jitter=True,+)+@with_team_scope()+def send_announcement(announcement_id: str, team_id: int) -> None:+ send_pending_deliveries(announcement_id, team_id)diff --git a/products/customer_analytics/backend/test/test_announcements.py b/products/customer_analytics/backend/test/test_announcements.pyindex dd7c02e4909b..8fb35b282e3d 100644--- a/products/customer_analytics/backend/test/test_announcements.py+++ b/products/customer_analytics/backend/test/test_announcements.py@@ -46,18 +46,36 @@ class TestAnnouncementAPI(APIBaseTest):announcement = Announcement.all_teams.get(id=data["id"])assert AnnouncementDelivery.all_teams.filter(announcement=announcement).count() == 2+ @patch("products.customer_analytics.backend.facade.api.send_announcement")@patch(HELPER)- def test_create_isolates_non_member_channel(self, mock_channels):+ def test_create_enqueues_send_task_after_commit(self, mock_channels, mock_task):mock_channels.return_value = self._member_channels()- response = self.client.post(self.base_url, {"message": "hi", "channels": ["C1", "D_secret_dm"]}, format="json")+ with self.captureOnCommitCallbacks(execute=True):+ response = self.client.post(self.base_url, {"message": "hi", "channels": ["C1"]}, format="json")assert response.status_code == status.HTTP_201_CREATED+ mock_task.delay.assert_called_once_with(response.json()["id"], self.team.pk)++ @patch("products.customer_analytics.backend.logic.announcements.post_support_message")+ @patch(HELPER)+ def test_create_isolates_non_member_channel_and_never_posts_to_it(self, mock_channels, mock_post):+ mock_channels.return_value = self._member_channels()+ mock_post.return_value = "1.0"++ with self.captureOnCommitCallbacks(execute=True):+ response = self.client.post(+ self.base_url, {"message": "hi", "channels": ["C1", "D_secret_dm"]}, format="json"+ )++ assert response.status_code == status.HTTP_201_CREATED+ assert [call.args[1] for call in mock_post.call_args_list] == ["C1"]announcement = Announcement.all_teams.get(id=response.json()["id"])+ assert announcement.status == Announcement.Status.PARTIALLY_FAILEDby_channel = {d.slack_channel_id: d for d in AnnouncementDelivery.all_teams.filter(announcement=announcement)}assert by_channel["D_secret_dm"].status == AnnouncementDelivery.Status.FAILEDassert by_channel["D_secret_dm"].error == "not_in_channel"- assert by_channel["C1"].status == AnnouncementDelivery.Status.PENDING+ assert by_channel["C1"].status == AnnouncementDelivery.Status.SENT@patch(HELPER)def test_create_rejects_when_slack_not_connected(self, mock_channels):diff --git a/products/customer_analytics/backend/test/test_send_announcement.py b/products/customer_analytics/backend/test/test_send_announcement.pynew file mode 100644index 000000000000..36240c2cd5ad--- /dev/null+++ b/products/customer_analytics/backend/test/test_send_announcement.py@@ -0,0 +1,137 @@+from posthog.test.base import BaseTest+from unittest.mock import MagicMock, patch++from products.conversations.backend.facade.api import SupportMessageSendError, SupportSlackNotConfigured+from products.customer_analytics.backend.constants import DELIVERY_IN_FLIGHT_ERROR, DELIVERY_INTERRUPTED_ERROR+from products.customer_analytics.backend.logic.announcements import AnnouncementRateLimited+from products.customer_analytics.backend.models import Announcement, AnnouncementDelivery+from products.customer_analytics.backend.tasks import send_announcement++POST = "products.customer_analytics.backend.logic.announcements.post_support_message"+++class TestSendAnnouncement(BaseTest):+ def _make(self, channel_ids: list[str], message: str = "hi") -> Announcement:+ announcement = Announcement.all_teams.create(+ team=self.team, message=message, total_channels=len(channel_ids), status=Announcement.Status.PENDING+ )+ for channel_id in channel_ids:+ AnnouncementDelivery.all_teams.create(+ team=self.team, announcement=announcement, slack_channel_id=channel_id, slack_channel_name=channel_id+ )+ return announcement++ def _delivery(self, announcement: Announcement, channel_id: str) -> AnnouncementDelivery:+ return AnnouncementDelivery.all_teams.get(announcement=announcement, slack_channel_id=channel_id)++ @patch(POST)+ def test_all_channels_succeed(self, mock_post: MagicMock):+ mock_post.return_value = "111.222"++ announcement = self._make(["C1", "C2"])+ send_announcement(str(announcement.id), self.team.pk)++ announcement.refresh_from_db()+ assert announcement.status == Announcement.Status.SENT+ assert (announcement.sent_count, announcement.failed_count) == (2, 0)+ assert announcement.sent_at is not None+ assert mock_post.call_count == 2+ assert self._delivery(announcement, "C1").slack_message_ts == "111.222"++ @patch(POST)+ def test_one_channel_failure_is_isolated(self, mock_post: MagicMock):+ def fake_post(team_id: int, channel_id: str, text: str) -> str:+ if channel_id == "Cfail":+ raise SupportMessageSendError("not_in_channel")+ return "1.0"++ mock_post.side_effect = fake_post++ announcement = self._make(["Cok", "Cfail"])+ send_announcement(str(announcement.id), self.team.pk)++ announcement.refresh_from_db()+ assert announcement.status == Announcement.Status.PARTIALLY_FAILED+ assert (announcement.sent_count, announcement.failed_count) == (1, 1)+ assert self._delivery(announcement, "Cok").status == AnnouncementDelivery.Status.SENT+ failed = self._delivery(announcement, "Cfail")+ assert failed.status == AnnouncementDelivery.Status.FAILED+ assert failed.error == "not_in_channel"++ @patch(POST)+ def test_no_slack_credentials_fails_all(self, mock_post: MagicMock):+ mock_post.side_effect = SupportSlackNotConfigured()++ announcement = self._make(["C1", "C2"])+ send_announcement(str(announcement.id), self.team.pk)++ announcement.refresh_from_db()+ assert announcement.status == Announcement.Status.FAILED+ assert announcement.failed_count == 2+ assert "not connected" in self._delivery(announcement, "C1").error+ assert mock_post.call_count == 1++ @patch(POST)+ def test_rerun_does_not_repost_to_already_sent_channels(self, mock_post: MagicMock):+ mock_post.return_value = "1"++ announcement = self._make(["C1", "C2"])+ send_announcement(str(announcement.id), self.team.pk)+ assert mock_post.call_count == 2++ send_announcement(str(announcement.id), self.team.pk)+ assert mock_post.call_count == 2++ @patch(POST)+ def test_crashed_in_flight_row_is_never_reposted(self, mock_post: MagicMock):+ mock_post.return_value = "1"++ announcement = self._make(["Ccrashed", "Cok"])+ AnnouncementDelivery.all_teams.filter(announcement=announcement, slack_channel_id="Ccrashed").update(+ error=DELIVERY_IN_FLIGHT_ERROR+ )++ send_announcement(str(announcement.id), self.team.pk)++ assert mock_post.call_count == 1+ assert mock_post.call_args.args[1] == "Cok"+ crashed = self._delivery(announcement, "Ccrashed")+ assert crashed.status == AnnouncementDelivery.Status.FAILED+ assert crashed.error == DELIVERY_INTERRUPTED_ERROR++ @patch(POST)+ def test_rate_limited_channel_defers_once_then_fails(self, mock_post: MagicMock):+ mock_post.side_effect = SupportMessageSendError("ratelimited", retry_after=30.0)++ announcement = self._make(["C1"])+ try:+ send_announcement(str(announcement.id), self.team.pk)+ raise AssertionError("expected AnnouncementRateLimited")+ except AnnouncementRateLimited:+ pass+ assert self._delivery(announcement, "C1").status == AnnouncementDelivery.Status.PENDING++ send_announcement(str(announcement.id), self.team.pk)+ assert mock_post.call_count == 2+ assert self._delivery(announcement, "C1").status == AnnouncementDelivery.Status.FAILED++ @patch(POST)+ def test_rate_limited_channel_sends_on_retry(self, mock_post: MagicMock):+ mock_post.side_effect = [SupportMessageSendError("ratelimited", retry_after=1.0), "9.9"]++ announcement = self._make(["C1"])+ try:+ send_announcement(str(announcement.id), self.team.pk)+ raise AssertionError("expected AnnouncementRateLimited")+ except AnnouncementRateLimited:+ pass++ send_announcement(str(announcement.id), self.team.pk)+ announcement.refresh_from_db()+ assert announcement.status == Announcement.Status.SENT+ assert self._delivery(announcement, "C1").slack_message_ts == "9.9"++ def test_retry_config_is_not_inert(self):+ # Bare max_retries without autoretry_for is silently inert; assert the wiring is real.+ assert Exception in send_announcement.autoretry_for+ assert send_announcement.max_retries == 3