: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): schedule task digest emails (#102962)
Arthur Moreira de Deus6e30292ee700
diff --git a/docs/internal/customer-analytics-account-links.md b/docs/internal/customer-analytics/account-links.mdsimilarity index 100%rename from docs/internal/customer-analytics-account-links.mdrename to docs/internal/customer-analytics/account-links.mddiff --git a/docs/internal/customer-analytics-account-presence.md b/docs/internal/customer-analytics/account-presence.mdsimilarity index 79%rename from docs/internal/customer-analytics-account-presence.mdrename to docs/internal/customer-analytics/account-presence.mdindex f61eef85741f..4f97e53269a3 100644--- a/docs/internal/customer-analytics-account-presence.md+++ b/docs/internal/customer-analytics/account-presence.md@@ -2,7 +2,7 @@Account detail pages show avatars for other active teammates who can read the same account.-The browser sends `POST /api/projects/:team_id/accounts/:account_id/presence/` when the page opens and every 30 seconds while the tab is visible. For an [external-ID account link](customer-analytics-account-links.md), heartbeats start after the account lookup succeeds and use the returned account UUID. The request has no body. The server derives the viewer identity from the authenticated user.+The browser sends `POST /api/projects/:team_id/accounts/:account_id/presence/` when the page opens and every 30 seconds while the tab is visible. For an [external-ID account link](account-links.md), heartbeats start after the account lookup succeeds and use the returned account UUID. The request has no body. The server derives the viewer identity from the authenticated user.Each heartbeat updates an account-scoped Redis roster. A viewer expires after 90 seconds without another heartbeat. Hidden tabs and unmounted pages stop heartbeats, so another viewer can remain visible for up to 90 seconds after leaving.diff --git a/docs/internal/customer-analytics-account-sidebar.md b/docs/internal/customer-analytics/account-sidebar.mdsimilarity index 100%rename from docs/internal/customer-analytics-account-sidebar.mdrename to docs/internal/customer-analytics/account-sidebar.mddiff --git a/docs/internal/customer-analytics-accounts-table.md b/docs/internal/customer-analytics/accounts-table.mdsimilarity index 100%rename from docs/internal/customer-analytics-accounts-table.mdrename to docs/internal/customer-analytics/accounts-table.mddiff --git a/docs/internal/customer-analytics-email-matching.md b/docs/internal/customer-analytics/email-matching.mdsimilarity index 100%rename from docs/internal/customer-analytics-email-matching.mdrename to docs/internal/customer-analytics/email-matching.mddiff --git a/docs/internal/customer-analytics-external-api.md b/docs/internal/customer-analytics/external-api.mdsimilarity index 100%rename from docs/internal/customer-analytics-external-api.mdrename to docs/internal/customer-analytics/external-api.mddiff --git a/docs/internal/customer-analytics-feature-requests.md b/docs/internal/customer-analytics/feature-requests.mdsimilarity index 100%rename from docs/internal/customer-analytics-feature-requests.mdrename to docs/internal/customer-analytics/feature-requests.mddiff --git a/docs/internal/customer-analytics-tasks-workflows.md b/docs/internal/customer-analytics/tasks-workflows.mdsimilarity index 72%rename from docs/internal/customer-analytics-tasks-workflows.mdrename to docs/internal/customer-analytics/tasks-workflows.mdindex 69f6b40f4f03..68f21176e656 100644--- a/docs/internal/customer-analytics-tasks-workflows.md+++ b/docs/internal/customer-analytics/tasks-workflows.md@@ -29,7 +29,7 @@ Those legacy runs create at most one task per action, including across loop visiStart a new workflow run to use per-visit task creation.Task tokens retain their own `posthog:customer-tasks:create` audience. Account tokens cannot call the task endpoint.-The shared key couples service access and rotation for both surfaces. See [Workflow task signing key](../../products/customer_analytics/backend/COMPROMISES.md#workflow-task-signing-key).+The shared key couples service access and rotation for both surfaces. See [Workflow task signing key](../../../products/customer_analytics/backend/COMPROMISES.md#workflow-task-signing-key).Task creation fails when the shared key is missing. Unlike account actions, it has no fallback to the project secret API token.The worker calls `POST /api/projects/{team_id}/workflow_customer_tasks/` through `INTERNAL_API_BASE_URL`, with a short-lived service token scoped to the project, workflow, and invocation/action key. The call goes directly to the backend, avoiding login redirects on the public app URL. Redirects and responses without a valid task UUID fail the workflow step. User API credentials and tokens for other actions cannot call this endpoint. No database migration is required.@@ -79,3 +79,32 @@ The user-config API stores preferences in `UserCustomerAnalyticsConfig.propertieOmitted fields retain their stored values, including fields within `task_digest`.Missing preferences return disabled, 09:00, and weekdays without changing other stored settings.Scheduling and email delivery are implemented separately.++## Task digest delivery++The `customer-analytics-task-digest` feature flag controls scheduled digest emails independently of Tasks and the event stream.+Enable it only for the initial rollout's recipients after verifying delivery in staging.+Disabling it stops both new scheduled sends and worker retries.++Every five minutes, the scheduler reads opted-in users in batches of 100 and enqueues users whose selected time has passed in the project timezone.+Each worker rereads preferences, membership, task permissions, and current assignments before rendering the digest.+Weekday cadence excludes Saturday and Sunday; every-day cadence includes them.+Daylight-saving changes follow the project timezone: a nonexistent time moves forward by the clock change, and a repeated time produces one digest for that local date.+Delayed work can catch up during that date, but does not send an older date's digest.++Digests use the checked-in `email/customer_task_digest.html` template through SMTP.+Configure `EMAIL_ENABLED`, the SMTP host, port, authentication, TLS settings, sender, timeout, and `SITE_URL` before enabling the flag.+Customer.io configuration alone is insufficient; there is no Customer.io template dependency for this email.+Missing SMTP configuration records a failed occurrence instead of reporting success.++The worker sends synchronously and checks `MessagingRecord.sent_at` for provider acceptance.+The campaign key contains the project ID, user ID, and local digest date.+Confirmed sends are skipped by repeated scheduler runs and worker retries.+`MessagingRecord.campaign_count` caps this occurrence at four attempts; permanent rejection marks the remaining attempts unavailable.+Temporary SMTP failures retry with backoff. A provider accepting a message does not prove inbox delivery, and a process failure between acceptance and committing the record can still duplicate a message.++`customer_analytics.task_digest.delivery` records acceptance, temporary failure, retry exhaustion, permanent rejection, and missing configuration.+`customer_analytics.task_digest.send_delay` measures the delay from the configured time to acceptance.+These metrics have no task content, account names, or recipient email labels.+Before a limited rollout, use test users in staging to verify a received email, current permission and opt-out checks, duplicate suppression, and the flag's kill switch.+No production verification is implied by local tests.diff --git a/posthog/email.py b/posthog/email.pyindex 531c93aa87d1..fa0fc10f08d9 100644--- a/posthog/email.py+++ b/posthog/email.py@@ -505,8 +505,7 @@ def sanitize_email_properties(properties: dict[str, Any] | None) -> dict[str, Anreturn {k: sanitize_value(v, key=k) for k, v in properties.items()}-@shared_task(**EMAIL_TASK_KWARGS)-def _send_email(+def _send_email_now(campaign_key: str,to: list[dict[str, str]],subject: str,@@ -518,9 +517,6 @@ def _send_email(use_http: Optional[bool] = False,properties: Optional[dict] = None,) -> None:- """- Sends built email message asynchronously, either through SMTP or HTTP- """if use_http and is_http_email_service_available():_send_via_http(to=to,@@ -542,6 +538,9 @@ def _send_email(raise Exception("Email is not enabled in this instance.")+_send_email = shared_task(**EMAIL_TASK_KWARGS, name="posthog.email._send_email")(_send_email_now)++class EmailMessage:def __init__(self,@@ -593,7 +592,8 @@ class EmailMessage:email = email_override or user.emailself.add_recipient(email=email, name=user.first_name, distinct_id=str(user.distinct_id))- def send(self, send_async: bool = True) -> None:+ def send(self, send_async: bool = True, *, retry: bool = True) -> None:+ """Synchronous callers can disable eager retries to own transport failure handling."""if not self.to:raise ValueError("No recipients provided! Use EmailMessage.add_recipient() first!")@@ -612,5 +612,18 @@ class EmailMessage:if send_async:_send_email.apply_async(kwargs=kwargs)- else:+ elif retry:_send_email.apply(kwargs=kwargs)+ else:+ _send_email_now(+ campaign_key=self.campaign_key,+ to=self.to,+ subject=self.subject,+ headers=self.headers,+ txt_body=self.txt_body,+ html_body=self.html_body,+ template_name=self.template_name,+ reply_to=self.reply_to,+ use_http=self.use_http,+ properties=self.properties,+ )diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.pyindex 6f4e4be732ad..053a8f6d3ed4 100644--- a/posthog/tasks/scheduled.py+++ b/posthog/tasks/scheduled.py@@ -88,6 +88,7 @@ from products.conversations.backend.tasks.email import flush_pending_email_replifrom products.conversations.backend.tasks.maintenance import wake_snoozed_ticketsfrom products.conversations.backend.tasks.slack import sweep_inbound_eventsfrom products.conversations.backend.tasks.teams import poll_teams_shared_channels+from products.customer_analytics.backend.facade.tasks import schedule_task_digestsfrom products.data_modeling.backend.facade.tasks import cleanup_expired_test_saved_queriesfrom products.data_warehouse.backend.facade.tasks import (reconcile_all_managed_warehouse_tables_task,@@ -1176,3 +1177,11 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:run_mcp_registry_sync.s(),name="mcp registry daily sync",)++ add_periodic_task_with_expiry(+ sender,+ crontab(minute="*/5"),+ schedule_task_digests.s(),+ name="schedule customer task digests",+ expires_seconds=300,+ )diff --git a/products/customer_analytics/backend/facade/tasks.py b/products/customer_analytics/backend/facade/tasks.pynew file mode 100644index 000000000000..26477c9ad653--- /dev/null+++ b/products/customer_analytics/backend/facade/tasks.py@@ -0,0 +1,3 @@+from products.customer_analytics.backend.tasks.task_digest import schedule_task_digests, send_task_digest++__all__ = ["schedule_task_digests", "send_task_digest"]diff --git a/products/customer_analytics/backend/logic/task_digest_delivery.py b/products/customer_analytics/backend/logic/task_digest_delivery.pynew file mode 100644index 000000000000..1c68bafb608c--- /dev/null+++ b/products/customer_analytics/backend/logic/task_digest_delivery.py@@ -0,0 +1,119 @@+from datetime import UTC, date, datetime, time+from zoneinfo import ZoneInfo++from django.db import transaction+from django.utils import timezone++import posthoganalytics++from posthog.email import (+ EmailDeliveryError,+ is_email_available,+ is_smtp_email_service_available,+ raise_if_delivery_rejected,+)+from posthog.models.messaging import MessagingRecord++from products.customer_analytics.backend.facade.contracts import TaskDigestPreferences+from products.customer_analytics.backend.logic.customer_task_digest import (+ build_customer_task_digest,+ build_customer_task_digest_email,+)+from products.customer_analytics.backend.logic.user_customer_analytics_config import read_task_digest+from products.customer_analytics.backend.metrics import record_task_digest_delivery+from products.customer_analytics.backend.models import UserCustomerAnalyticsConfig++TASK_DIGEST_FLAG = "customer-analytics-task-digest"+MAX_SEND_ATTEMPTS = 4+++class TemporaryTaskDigestFailure(Exception):+ pass+++def task_digest_scheduled_at(+ preferences: TaskDigestPreferences, project_timezone: str, now: datetime+) -> datetime | None:+ local_now = now.astimezone(ZoneInfo(project_timezone))+ if not preferences.enabled or (preferences.cadence == "weekdays" and local_now.weekday() >= 5):+ return None+ scheduled_at = datetime.combine(+ local_now.date(), time.fromisoformat(preferences.send_time), tzinfo=local_now.tzinfo+ ).astimezone(UTC)+ return scheduled_at if scheduled_at <= now else None+++def task_digest_campaign_key(team_id: int, user_id: int, digest_date: date) -> str:+ return f"customer-task-digest:{team_id}:{user_id}:{digest_date.isoformat()}"+++def task_digest_enabled(config: UserCustomerAnalyticsConfig) -> bool:+ return bool(+ posthoganalytics.feature_enabled(+ TASK_DIGEST_FLAG,+ str(config.user.distinct_id),+ groups={"organization": str(config.team.organization_id)},+ only_evaluate_locally=False,+ send_feature_flag_events=False,+ )+ )+++def deliver_task_digest(team_id: int, user_id: int, digest_date: str) -> None:+ now = timezone.now()+ config = (+ UserCustomerAnalyticsConfig.objects.for_team(team_id)+ .select_related("user", "team")+ .filter(user_id=user_id, user__is_active=True)+ .first()+ )+ if config is None or not task_digest_enabled(config):+ return+ preferences = read_task_digest(config)+ scheduled_at = task_digest_scheduled_at(preferences, config.team.timezone, now)+ local_date = now.astimezone(ZoneInfo(config.team.timezone)).date()+ if scheduled_at is None or local_date.isoformat() != digest_date:+ return+ campaign_key = task_digest_campaign_key(team_id, user_id, local_date)+ if MessagingRecord.objects.filter(campaign_key=campaign_key, sent_at__isnull=False).exists():+ return+ digest = build_customer_task_digest(user=config.user, team=config.team, reference_time=now)+ if digest is None or not task_digest_enabled(config):+ return++ outcome = "permanent_rejection"+ email_available = is_email_available(with_absolute_urls=True) and is_smtp_email_service_available()+ with transaction.atomic():+ record = MessagingRecord.objects.filter(campaign_key=campaign_key).first()+ if record is None:+ record, _ = MessagingRecord.objects.get_or_create(raw_email=config.user.email, campaign_key=campaign_key)+ record = MessagingRecord.objects.select_for_update().get(pk=record.pk)+ if (record.campaign_count or 0) >= MAX_SEND_ATTEMPTS or MessagingRecord.objects.filter(+ campaign_key=campaign_key, sent_at__isnull=False+ ).exists():+ return+ attempt = (record.campaign_count or 0) + 1+ record.campaign_count = MAX_SEND_ATTEMPTS+ record.save(update_fields=["campaign_count"])++ if not email_available:+ outcome = "missing_configuration"+ else:+ message = build_customer_task_digest_email(digest=digest, user=config.user, campaign_key=campaign_key)+ try:+ message.send(send_async=False, retry=False)+ raise_if_delivery_rejected(campaign_key, config.user.email)+ except EmailDeliveryError:+ pass+ except (ConnectionError, TimeoutError, OSError):+ MessagingRecord.objects.filter(pk=record.pk, sent_at__isnull=True).update(campaign_count=attempt)+ outcome = "temporary_failure" if attempt < MAX_SEND_ATTEMPTS else "retries_exhausted"+ else:+ MessagingRecord.objects.filter(pk=record.pk, sent_at__isnull=False).update(campaign_count=attempt)+ outcome = "accepted"+ record_task_digest_delivery(+ outcome=outcome,+ delay_seconds=max(0, (timezone.now() - scheduled_at).total_seconds()) if outcome == "accepted" else None,+ )+ if outcome == "temporary_failure":+ raise TemporaryTaskDigestFailure()diff --git a/products/customer_analytics/backend/metrics.py b/products/customer_analytics/backend/metrics.pyindex acd761ebfa74..1db8d4e19b2b 100644--- a/products/customer_analytics/backend/metrics.py+++ b/products/customer_analytics/backend/metrics.py@@ -143,3 +143,15 @@ def record_account_track_rule_coordinator(# Cutover observability for #82564: the CDP worker's account actions move from# secret_api_token on the external routes to scoped JWTs on the internal routes.# The legacy worker path can be removed once auth_method="secret_api_token" stays at zero.+++def record_task_digest_delivery(*, outcome: str, delay_seconds: float | None) -> None:+ client = posthoganalytics.default_client+ if client is None:+ return+ try:+ client.metrics.count("customer_analytics.task_digest.delivery", 1, attributes={"outcome": outcome})+ if delay_seconds is not None:+ client.metrics.histogram("customer_analytics.task_digest.send_delay", delay_seconds, unit="s")+ except Exception:+ passdiff --git a/products/customer_analytics/backend/tasks/__init__.py b/products/customer_analytics/backend/tasks/__init__.pyindex 75c6b8addf0f..06a81ce9ee6b 100644--- a/products/customer_analytics/backend/tasks/__init__.py+++ b/products/customer_analytics/backend/tasks/__init__.py@@ -1,3 +1,5 @@+from products.customer_analytics.backend.tasks.task_digest import schedule_task_digests, send_task_digest # noqa: F401+# Re-exported so Celery autodiscovers the tasks when the tasks package is imported.from products.customer_analytics.backend.tasks.tasks import ( # noqa: F401process_custom_property_sync,diff --git a/products/customer_analytics/backend/tasks/task_digest.py b/products/customer_analytics/backend/tasks/task_digest.pynew file mode 100644index 000000000000..bfdfca7d864e--- /dev/null+++ b/products/customer_analytics/backend/tasks/task_digest.py@@ -0,0 +1,65 @@+from zoneinfo import ZoneInfo++from django.utils import timezone++from celery import shared_task++from posthog.celery_queues import CeleryQueue+from posthog.models.messaging import MessagingRecord++from products.customer_analytics.backend.logic.task_digest_delivery import (+ MAX_SEND_ATTEMPTS,+ TemporaryTaskDigestFailure,+ deliver_task_digest,+ task_digest_campaign_key,+ task_digest_enabled,+ task_digest_scheduled_at,+)+from products.customer_analytics.backend.logic.user_customer_analytics_config import read_task_digest+from products.customer_analytics.backend.models import UserCustomerAnalyticsConfig++DIGEST_SCHEDULE_BATCH_SIZE = 100+++@shared_task(+ name="customer_analytics.send_task_digest",+ queue=CeleryQueue.EMAIL.value,+ ignore_result=True,+ autoretry_for=(TemporaryTaskDigestFailure,),+ retry_backoff=60,+ retry_backoff_max=900,+ retry_jitter=True,+ max_retries=MAX_SEND_ATTEMPTS - 1,+)+def send_task_digest(team_id: int, user_id: int, digest_date: str) -> None:+ deliver_task_digest(team_id, user_id, digest_date)+++@shared_task(name="customer_analytics.schedule_task_digests", ignore_result=True)+def schedule_task_digests(cursor: str | None = None) -> None:+ now = timezone.now()+ configs = (+ UserCustomerAnalyticsConfig.objects.unscoped()+ .filter(properties__task_digest__enabled=True, user__is_active=True)+ .select_related("user", "team")+ )+ if cursor is not None:+ configs = configs.filter(pk__gt=cursor)+ batch = list(configs.order_by("pk")[:DIGEST_SCHEDULE_BATCH_SIZE])+ for config in batch:+ preferences = read_task_digest(config)+ if task_digest_scheduled_at(preferences, config.team.timezone, now) is None or not task_digest_enabled(config):+ continue+ digest_date = now.astimezone(ZoneInfo(config.team.timezone)).date()+ campaign_key = task_digest_campaign_key(config.team_id, config.user_id, digest_date)+ campaign_records = MessagingRecord.objects.filter( # nosemgrep: celery-task-team-scope-audit - this global model has no team field, and the key embeds team_id+ campaign_key=campaign_key+ )+ if campaign_records.filter(sent_at__isnull=False).exists():+ continue+ record = campaign_records.first()+ if record is not None and (record.sent_at is not None or (record.campaign_count or 0) >= MAX_SEND_ATTEMPTS):+ continue+ send_task_digest.delay(config.team_id, config.user_id, digest_date.isoformat())+ if len(batch) == DIGEST_SCHEDULE_BATCH_SIZE:+ schedule_task_digests.delay(str(batch[-1].pk))diff --git a/products/customer_analytics/backend/test/test_task_digest_delivery.py b/products/customer_analytics/backend/test/test_task_digest_delivery.pynew file mode 100644index 000000000000..1639779fbf66--- /dev/null+++ b/products/customer_analytics/backend/test/test_task_digest_delivery.py@@ -0,0 +1,150 @@+import smtplib+from datetime import UTC, date, datetime+from typing import Literal++import time_machine+from posthog.test.base import BaseTest+from unittest.mock import MagicMock, patch++from django.core import mail+from django.db import DatabaseError+from django.test import SimpleTestCase++from parameterized import parameterized++from posthog.models import OrganizationMembership+from posthog.models.instance_setting import override_instance_config+from posthog.models.messaging import MessagingRecord++from products.customer_analytics.backend.facade.contracts import TaskDigestPreferences+from products.customer_analytics.backend.facade.tasks import schedule_task_digests+from products.customer_analytics.backend.logic.task_digest_delivery import (+ MAX_SEND_ATTEMPTS,+ TemporaryTaskDigestFailure,+ deliver_task_digest,+ task_digest_campaign_key,+ task_digest_scheduled_at,+)+from products.customer_analytics.backend.models import CustomerTask, UserCustomerAnalyticsConfig+++class TestTaskDigestSchedule(SimpleTestCase):+ @parameterized.expand(+ [+ ("before", "2026-03-06T13:59:00+00:00", "09:00", "weekdays", None),+ ("winter", "2026-03-06T14:00:00+00:00", "09:00", "weekdays", "2026-03-06T14:00:00+00:00"),+ ("summer", "2026-03-09T13:00:00+00:00", "09:00", "weekdays", "2026-03-09T13:00:00+00:00"),+ ("weekend", "2026-03-08T13:00:00+00:00", "09:00", "weekdays", None),+ ("daily", "2026-03-08T13:00:00+00:00", "09:00", "every_day", "2026-03-08T13:00:00+00:00"),+ ("gap_before", "2026-03-08T07:15:00+00:00", "02:30", "every_day", None),+ ("gap", "2026-03-08T07:30:00+00:00", "02:30", "every_day", "2026-03-08T07:30:00+00:00"),+ ("fold", "2026-11-01T06:30:00+00:00", "01:30", "every_day", "2026-11-01T05:30:00+00:00"),+ ]+ )+ def test_project_local_schedule(+ self, _name: str, now: str, send_time: str, cadence: Literal["weekdays", "every_day"], expected: str | None+ ) -> None:+ preferences = TaskDigestPreferences(enabled=True, send_time=send_time, cadence=cadence)+ result = task_digest_scheduled_at(preferences, "America/New_York", datetime.fromisoformat(now))+ assert result == (datetime.fromisoformat(expected) if expected else None)+++@time_machine.travel("2026-09-18T09:05:00Z", tick=False)+class TestTaskDigestDelivery(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.enterContext(override_instance_config("EMAIL_HOST", "localhost"))+ self.enterContext(patch("posthoganalytics.feature_enabled", return_value=True))+ self.enterContext(patch("posthog.permissions.posthog_feature_flag_enabled", return_value=True))+ self.team.timezone = "UTC"+ self.team.save(update_fields=["timezone"])+ self.config = UserCustomerAnalyticsConfig.objects.for_team(self.team.pk).create(+ team=self.team,+ user=self.user,+ properties={"task_digest": {"enabled": True, "send_time": "09:00", "cadence": "weekdays"}},+ )+ self.task = CustomerTask.objects.for_team(self.team.pk).create(+ team=self.team,+ assigned_to=self.user,+ name="Prepare example follow-up",+ due_at=datetime(2026, 9, 18, 12, tzinfo=UTC),+ )+ self.campaign_key = task_digest_campaign_key(self.team.pk, self.user.pk, date(2026, 9, 18))++ def test_accepted_send_and_repeated_scheduler_do_not_resend(self) -> None:+ with patch("products.customer_analytics.backend.facade.tasks.send_task_digest.delay") as enqueue:+ schedule_task_digests()+ enqueue.assert_called_once_with(self.team.pk, self.user.pk, "2026-09-18")+ deliver_task_digest(self.team.pk, self.user.pk, "2026-09-18")+ self.user.email = "[email protected]"+ self.user.save(update_fields=["email"])+ deliver_task_digest(self.team.pk, self.user.pk, "2026-09-18")+ with patch("products.customer_analytics.backend.facade.tasks.send_task_digest.delay") as enqueue:+ schedule_task_digests()+ enqueue.assert_not_called()+ assert len(mail.outbox) == 1+ assert MessagingRecord.objects.get(campaign_key=self.campaign_key).sent_at is not None++ def test_ambiguous_send_failure_does_not_retry(self) -> None:+ message = MagicMock()+ message.send.side_effect = DatabaseError("delivery accepted before database failure")+ with patch(+ "products.customer_analytics.backend.logic.task_digest_delivery.build_customer_task_digest_email",+ return_value=message,+ ):+ with self.assertRaises(DatabaseError):+ deliver_task_digest(self.team.pk, self.user.pk, "2026-09-18")+ deliver_task_digest(self.team.pk, self.user.pk, "2026-09-18")++ message.send.assert_called_once_with(send_async=False, retry=False)+ record = MessagingRecord.objects.get(campaign_key=self.campaign_key)+ assert record.sent_at is None+ assert record.campaign_count == MAX_SEND_ATTEMPTS++ @parameterized.expand(+ [+ ("temporary", smtplib.SMTPDataError(451, b"Try later"), True),+ ("permanent", smtplib.SMTPDataError(550, b"Rejected"), False),+ ("no_acceptance", None, False),+ ]+ )+ def test_transport_failures_have_bounded_retry(self, _name: str, error: Exception | None, temporary: bool) -> None:+ with patch(+ "django.core.mail.backends.locmem.EmailBackend.send_messages", side_effect=error, return_value=0+ ) as send:+ for attempt in range(MAX_SEND_ATTEMPTS + 1):+ if temporary and attempt < MAX_SEND_ATTEMPTS - 1:+ with self.assertRaises(TemporaryTaskDigestFailure):+ deliver_task_digest(self.team.pk, self.user.pk, "2026-09-18")+ else:+ deliver_task_digest(self.team.pk, self.user.pk, "2026-09-18")+ assert send.call_count == (MAX_SEND_ATTEMPTS if temporary else 1)+ record = MessagingRecord.objects.get(campaign_key=self.campaign_key)+ assert record.sent_at is None+ assert record.campaign_count == MAX_SEND_ATTEMPTS++ @parameterized.expand([("opt_out",), ("membership",), ("reassigned",), ("disabled",), ("flag",)])+ def test_current_state_is_checked_before_sending(self, change: str) -> None:+ if change == "opt_out":+ self.config.properties["task_digest"]["enabled"] = False+ self.config.save(update_fields=["properties"])+ elif change == "membership":+ OrganizationMembership.objects.filter(user=self.user, organization=self.organization).delete()+ elif change == "reassigned":+ self.task.assigned_to = None+ self.task.save(update_fields=["assigned_to"])+ elif change == "disabled":+ self.user.is_active = False+ self.user.save(update_fields=["is_active"])+ with patch("posthoganalytics.feature_enabled", return_value=change != "flag"):+ deliver_task_digest(self.team.pk, self.user.pk, "2026-09-18")+ assert len(mail.outbox) == 0+ assert not MessagingRecord.objects.filter(campaign_key=self.campaign_key, sent_at__isnull=False).exists()++ def test_missing_smtp_configuration_is_not_acceptance(self) -> None:+ with override_instance_config("EMAIL_HOST", None):+ deliver_task_digest(self.team.pk, self.user.pk, "2026-09-18")+ assert len(mail.outbox) == 0+ record = MessagingRecord.objects.get(campaign_key=self.campaign_key)+ assert record.sent_at is None+ assert record.campaign_count == MAX_SEND_ATTEMPTSdiff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.mdindex ceb8a880de22..02450002c4e4 100644--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md@@ -63,7 +63,7 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_TABLE_DATA_NODE_KEY, acc## Data & query model-`accountsLogic.accountsTableQueryPlan` translates selected columns, filters, custom-property display windows, tile filters, and server-side sort into a typed `AccountsTableQuery`. Unsupported saved columns and filters are omitted instead of switching execution engines. `AccountsTable` reads each keyed `AccountsTableRow` directly through `accountsTableCell`; there is no positional-row compatibility transform. Custom properties and other fields without a saved or column-specific width size to their rendered headers and loaded values, between 80px and 200px. `useAccountColumnAutoSizing` measures a hidden, unconstrained copy of the table after data loads. Automatic widths remain local to the mounted table and update with its data. They use the same table sizing as manually resized columns. Existing defaults, manual resizing, and horizontal scrolling stay unchanged. Every column can be resized from its header down to 80px. See [Accounts table layout](../../../../../docs/internal/customer-analytics-accounts-table.md). Widths save automatically in one team-scoped local storage dictionary keyed by stable column alias. A column keeps its width when a view hides it, then restores it when another view shows it.+`accountsLogic.accountsTableQueryPlan` translates selected columns, filters, custom-property display windows, tile filters, and server-side sort into a typed `AccountsTableQuery`. Unsupported saved columns and filters are omitted instead of switching execution engines. `AccountsTable` reads each keyed `AccountsTableRow` directly through `accountsTableCell`; there is no positional-row compatibility transform. Custom properties and other fields without a saved or column-specific width size to their rendered headers and loaded values, between 80px and 200px. `useAccountColumnAutoSizing` measures a hidden, unconstrained copy of the table after data loads. Automatic widths remain local to the mounted table and update with its data. They use the same table sizing as manually resized columns. Existing defaults, manual resizing, and horizontal scrolling stay unchanged. Every column can be resized from its header down to 80px. See [Accounts table layout](../../../../../docs/internal/customer-analytics/accounts-table.md). Widths save automatically in one team-scoped local storage dictionary keyed by stable column alias. A column keeps its width when a view hides it, then restores it when another view shows it.Search matches the account name and external ID as substrings.A complete email address also matches accounts that list it under `known_emails`.@@ -160,7 +160,7 @@ The empty Properties state uses the hedgehog and primary **Pin properties** actiProperty reference keys at the component boundary are namespaced as `custom:<uuid>` and `relationship:<uuid>`; persistence maps custom keys back to the API's `custom_property` kind.`accountSidebarPropertiesLogic({ projectId, accountId })` loads current custom values and relationship assignments, resolves them in pin order, and owns inline editing. Resource-level Customer analytics editors can change manual/workflow values and relationships; canonical and warehouse-backed rows are read-only.Clearing posts a null custom value and preserves history. Relationship removals end assignments; single-holder replacements let the server end the previous holder. Multi-holder retries reload current assignments to avoid duplicating a partially completed save. Failed saves keep the draft open.-Sidebar saves refresh the mounted Relationships tab and account-list data nodes. Tab relationship reloads also refresh sidebar values. See `docs/internal/customer-analytics-account-sidebar.md` for the behavior and API contract.+Sidebar saves refresh the mounted Relationships tab and account-list data nodes. Tab relationship reloads also refresh sidebar values. See `docs/internal/customer-analytics/account-sidebar.md` for the behavior and API contract.On wide layouts, the sidebar and the active account-detail tab are separate vertical scroll containers. Narrow layouts retain the single stacked page scroll.It reuses `AccountDetailTabs` and `AccountNotesExpansion` with the expanded row, but mounts only the active tab so inactive detail tabs do not load data.Tables use borders in the detail scene and remain embedded in expanded rows.@@ -254,7 +254,7 @@ An explicit shared URL wins over the draft. The draft wins over automatic saved-Restoring only the My accounts preference keeps column initialization active and does not create a fallback draft.While `awaitingSavedView` is true, draft and URL writes wait for the saved-view decision.Selecting a saved view explicitly replaces the draft.-See [Accounts table](../../../../../docs/internal/customer-analytics-accounts-table.md) when changing persistence or navigation.+See [Accounts table](../../../../../docs/internal/customer-analytics/accounts-table.md) when changing persistence or navigation.### Deep-link to one account (path route)