: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(web-analytics): Add Web analytics weekly digest to notifications (#63035)
Jordan Mryyan0b389fd79b49
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/activity/buildNotificationSourcePath.test.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/activity/buildNotificationSourcePath.test.tsindex f76632d8b179..87a6180ddba2 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/activity/buildNotificationSourcePath.test.ts+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/activity/buildNotificationSourcePath.test.ts@@ -19,6 +19,7 @@ function makeNotification(overrides: Partial<InAppNotification> = {}): InAppNotisource_url: '',source_type: null,source_id: null,+ metadata: null,created_at: '2026-04-01T00:00:00Z',...overrides,}diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/activity/notificationsSSE.test.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/activity/notificationsSSE.test.tsindex 800bd3aebe31..2d4f5e2c2d5b 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/activity/notificationsSSE.test.ts+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/activity/notificationsSSE.test.ts@@ -25,6 +25,7 @@ function makeNotification(overrides: Partial<InAppNotification> = {}): InAppNotisource_url: '',source_type: null,source_id: null,+ metadata: null,created_at: '2026-04-01T00:00:00Z',...overrides,}diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic.test.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic.test.tsindex 77620d95ddc4..29a3c3c21d63 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic.test.ts+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic.test.ts@@ -19,6 +19,7 @@ function makeNotification(overrides: Partial<InAppNotification> = {}): InAppNotisource_url: '',source_type: null,source_id: null,+ metadata: null,target_type: 'user',target_id: '42',created_at: '2026-05-07T12:00:00Z',diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic.tsx b/frontend/src/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic.tsxindex 330bd43836a7..923934471ac0 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic.tsx+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic.tsx@@ -21,7 +21,7 @@ import { urls } from 'scenes/urls'import { connectToNotificationsSSE } from '~/layout/navigation-3000/sidepanel/panels/activity/notificationsSSE'import { ChangesResponse } from '~/layout/navigation-3000/sidepanel/panels/activity/sidePanelActivityLogic'-import { InAppNotification, InsightShortId } from '~/types'+import { InAppNotification, InsightShortId, SidePanelTab, WebAnalyticsDigestMetadata } from '~/types'import {notificationsList,@@ -84,6 +84,21 @@ export function buildNotificationSourcePath(notification: InAppNotification): streturn notification.source_url || null}+export function buildWebAnalyticsDigestMaxPrompt(metadata: WebAnalyticsDigestMetadata | null): string {+ if (!metadata) {+ return '!Summarize my web analytics for the last 7 days and tell me what changed and why.'+ }+ const metricsLine = metadata.metrics+ .map((metric) => {+ const change = metric.change+ ? ` (${metric.change.direction === 'Up' ? 'up' : 'down'} ${metric.change.percent}%)`+ : ''+ return `${metric.label} ${metric.value}${change}`+ })+ .join(', ')+ return `!Here's my web analytics digest for ${metadata.period_label.toLowerCase()} on ${metadata.project_name}: ${metricsLine}. What are the most important changes, and what should I dig into?`+}+export interface ChangelogFlagPayload {notificationDate: dayjs.Dayjsmarkdown: string@@ -127,6 +142,8 @@ export const sidePanelNotificationsLogic = kea<sidePanelNotificationsLogicType>(markAsRead: (id: string) => ({ id }),toggleRead: (id: string) => ({ id }),navigateToNotification: (notification: InAppNotification) => ({ notification }),+ viewWebAnalyticsFromDigest: (notification: InAppNotification) => ({ notification }),+ askMaxAboutDigest: (notification: InAppNotification) => ({ notification }),loadMoreNotifications: true,loadMoreNotificationsSuccess: (count: number) => ({ count }),loadGroupChildren: (group: NotificationGroup) => ({ group }),@@ -555,6 +572,25 @@ export const sidePanelNotificationsLogic = kea<sidePanelNotificationsLogicType>(},})},+ viewWebAnalyticsFromDigest: ({ notification }) => {+ posthog.capture('web_analytics_digest_notification_clicked', {+ cta: 'view_web_analytics',+ notification_id: notification.id,+ team_id: notification.team_id,+ })+ actions.navigateToNotification(notification)+ },+ askMaxAboutDigest: ({ notification }) => {+ posthog.capture('web_analytics_digest_notification_clicked', {+ cta: 'ask_max',+ notification_id: notification.id,+ team_id: notification.team_id,+ })+ if (!notification.read) {+ actions.markAsRead(notification.id)+ }+ actions.openSidePanel(SidePanelTab.Max, buildWebAnalyticsDigestMaxPrompt(notification.metadata))+ },markAsRead: async ({ id }) => {try {await notificationsMarkReadCreate((values.currentProjectId ?? '').toString(), id)diff --git a/frontend/src/lib/components/NotificationsMenu/NotificationRow.tsx b/frontend/src/lib/components/NotificationsMenu/NotificationRow.tsxindex cd974d86733e..129a33d3fece 100644--- a/frontend/src/lib/components/NotificationsMenu/NotificationRow.tsx+++ b/frontend/src/lib/components/NotificationsMenu/NotificationRow.tsx@@ -4,6 +4,7 @@ import { useState } from 'react'import { IconCheckCircle } from '@posthog/icons'import { Tooltip } from '@posthog/lemon-ui'+import { getNotificationDescriber } from 'lib/components/NotificationsMenu/notificationDescribers'import { getNotificationIcon } from 'lib/components/NotificationsMenu/notificationToasts'import { dayjs } from 'lib/dayjs'import { IconRadioButtonUnchecked } from 'lib/lemon-ui/icons'@@ -49,6 +50,10 @@ export const REALTIME_NOTIFICATION_TYPE_META: Record<string, { label: string; delabel: 'Usage spikes',description: 'When billing detects a usage spike for one of your accounts',},+ web_analytics_digest: {+ label: 'Web analytics digest',+ description: 'Your weekly Web analytics summary is ready!',+ },}export function NotificationRow({@@ -63,6 +68,9 @@ export function NotificationRow({const [expanded, setExpanded] = useState(false)const otherProjectName = projectNameForNotification(notification)+ const describer = getNotificationDescriber(notification)+ const customBody = describer ? <describer.Component notification={notification} onNavigate={onNavigate} /> : null+ const rich = !!describer?.takesOverRow && !!notification.metadataconst hasNavigationTarget = !!sourcePathForNotification(notification)const handleNavigate = (e: React.MouseEvent): void => {@@ -80,19 +88,27 @@ export function NotificationRow({return (<div- className={`flex items-start gap-2.5 p-2 rounded cursor-pointer transition-colors ${+ className={`flex items-start gap-2.5 p-2 rounded transition-colors ${rich ? '' : 'cursor-pointer'} ${notification.read ? 'hover:bg-fill-highlight-100' : 'bg-fill-highlight-50 hover:bg-fill-highlight-100'}`}- onClick={() => notification.body && setExpanded(!expanded)}+ onClick={rich ? undefined : () => notification.body && setExpanded(!expanded)}><div className="shrink-0 mt-0.5">{getNotificationIcon(notification.notification_type)}</div><div className="flex-1 min-w-0"><div className="flex items-start justify-between gap-1">- <span className={`text-xs leading-snug ${notification.read ? 'text-secondary' : 'font-semibold'}`}>- {notification.title}- </span>+ {rich ? (+ <span className="text-[10px] font-semibold uppercase tracking-wide text-muted mt-1">+ Web analytics digest+ </span>+ ) : (+ <span+ className={`text-xs leading-snug ${notification.read ? 'text-secondary' : 'font-semibold'}`}+ >+ {notification.title}+ </span>+ )}<div className="flex items-center gap-1 shrink-0">- {hasNavigationTarget && (+ {!rich && hasNavigationTarget && (<Tooltip title="Go to source"><buttonclassName="min-w-[26px] min-h-[26px] flex items-center justify-center rounded hover:bg-fill-highlight-200 text-secondary hover:text-primary cursor-pointer"@@ -119,11 +135,13 @@ export function NotificationRow({</Tooltip></div></div>- {notification.body && (- <div className={`text-xs text-secondary mt-0.5 ${expanded ? '' : 'line-clamp-1'}`}>- {notification.body}- </div>- )}+ {rich+ ? customBody+ : notification.body && (+ <div className={`text-xs text-secondary mt-0.5 ${expanded ? '' : 'line-clamp-1'}`}>+ {notification.body}+ </div>+ )}<div className="flex items-center gap-1.5 mt-2"><span className="text-[10px] text-muted">{dayjs(notification.created_at).fromNow()}</span>{otherProjectName && (diff --git a/frontend/src/lib/components/NotificationsMenu/WebAnalyticsDigestNotification.tsx b/frontend/src/lib/components/NotificationsMenu/WebAnalyticsDigestNotification.tsxnew file mode 100644index 000000000000..55f330a91271--- /dev/null+++ b/frontend/src/lib/components/NotificationsMenu/WebAnalyticsDigestNotification.tsx@@ -0,0 +1,64 @@+import { IconArrowRight, IconSparkles } from '@posthog/icons'+import { LemonButton } from '@posthog/lemon-ui'++import { WebAnalyticsDigestMetadata, WebAnalyticsDigestMetric, WebAnalyticsDigestMetricChange } from '~/types'++function TrendPill({ change }: { change: WebAnalyticsDigestMetricChange | null }): JSX.Element | null {+ if (!change) {+ return null+ }+ const colorClass = change.is_good ? 'text-success' : 'text-danger'+ return (+ <span className={`inline-flex items-center gap-0.5 text-xs font-semibold ${colorClass}`}>+ <span className="leading-none">{change.direction === 'Up' ? '↑' : '↓'}</span>+ {change.percent}%+ </span>+ )+}++export function WebAnalyticsDigestNotification({+ metadata,+ onOpen,+ onAskMax,+}: {+ metadata: WebAnalyticsDigestMetadata+ onOpen: (e: React.MouseEvent) => void+ onAskMax: (e: React.MouseEvent) => void+}): JSX.Element {+ const byKey = (key: string): WebAnalyticsDigestMetric | undefined => metadata.metrics.find((m) => m.key === key)+ const hero = byKey('visitors')+ const pageviews = byKey('pageviews')+ const sessions = byKey('sessions')+ const subline = [pageviews, sessions]+ .filter((metric): metric is WebAnalyticsDigestMetric => Boolean(metric))+ .map((metric) => `${metric.value} ${metric.label.toLowerCase()}`)+ .join(' · ')++ return (+ <div className="mt-1 flex flex-col gap-2.5">+ {hero && (+ <div className="flex items-baseline gap-2">+ <span className="text-3xl font-bold leading-none tabular-nums">{hero.value}</span>+ <span className="text-sm text-secondary">{hero.label.toLowerCase()}</span>+ <TrendPill change={hero.change} />+ </div>+ )}+ {subline && <div className="text-xs text-muted">{subline}</div>}+ <div className="flex flex-col gap-1.5">+ <LemonButton+ type="primary"+ size="small"+ fullWidth+ center+ sideIcon={<IconArrowRight />}+ onClick={onOpen}+ >+ View web analytics+ </LemonButton>+ <LemonButton type="secondary" size="small" fullWidth center icon={<IconSparkles />} onClick={onAskMax}>+ Ask PostHog AI+ </LemonButton>+ </div>+ </div>+ )+}diff --git a/frontend/src/lib/components/NotificationsMenu/notificationDescribers.tsx b/frontend/src/lib/components/NotificationsMenu/notificationDescribers.tsxnew file mode 100644index 000000000000..5d98aab4a2a6--- /dev/null+++ b/frontend/src/lib/components/NotificationsMenu/notificationDescribers.tsx@@ -0,0 +1,48 @@+import { useActions } from 'kea'++import { WebAnalyticsDigestNotification } from 'lib/components/NotificationsMenu/WebAnalyticsDigestNotification'++import { sidePanelNotificationsLogic } from '~/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic'+import { InAppNotification } from '~/types'++export interface NotificationDescriberProps {+ notification: InAppNotification+ onNavigate?: () => void+}++export interface NotificationDescriber {+ takesOverRow?: boolean+ Component: (props: NotificationDescriberProps) => JSX.Element | null+}++function WebAnalyticsDigestDescriber({ notification, onNavigate }: NotificationDescriberProps): JSX.Element | null {+ const { viewWebAnalyticsFromDigest, askMaxAboutDigest } = useActions(sidePanelNotificationsLogic)++ if (!notification.metadata) {+ return null+ }++ return (+ <WebAnalyticsDigestNotification+ metadata={notification.metadata}+ onOpen={(e) => {+ e.stopPropagation()+ viewWebAnalyticsFromDigest(notification)+ onNavigate?.()+ }}+ onAskMax={(e) => {+ e.stopPropagation()+ askMaxAboutDigest(notification)+ onNavigate?.()+ }}+ />+ )+}++export const NOTIFICATION_DESCRIBERS: Record<string, NotificationDescriber> = {+ web_analytics_digest: { takesOverRow: true, Component: WebAnalyticsDigestDescriber },+}++export function getNotificationDescriber(notification: InAppNotification): NotificationDescriber | undefined {+ return NOTIFICATION_DESCRIBERS[notification.notification_type]+}diff --git a/frontend/src/lib/components/NotificationsMenu/notificationToasts.tsx b/frontend/src/lib/components/NotificationsMenu/notificationToasts.tsxindex 000a5395d69f..109f98d37dc6 100644--- a/frontend/src/lib/components/NotificationsMenu/notificationToasts.tsx+++ b/frontend/src/lib/components/NotificationsMenu/notificationToasts.tsx@@ -5,6 +5,7 @@ import {IconFlask,IconFolder,IconNotification,+ IconPieChart,IconPlug,IconTrending,IconWarning,@@ -25,6 +26,7 @@ const NOTIFICATION_TYPE_ICONS: Record<string, JSX.Element> = {experiment_concluded: <IconFlask className="size-5 text-primary shrink-0" />,project_created: <IconFolder className="size-5 text-primary shrink-0" />,usage_spike: <IconTrending className="size-5 text-warning shrink-0" />,+ web_analytics_digest: <IconPieChart className="size-5 text-primary shrink-0" />,}export function getNotificationIcon(notificationType: string): JSX.Element {diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex b5f571c63cdf..f3154bf1342e 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -428,6 +428,33 @@ export interface NotificationSettings {pipeline_notifications_disabled?: Record<string, boolean>}+export interface WebAnalyticsDigestMetricChange {+ percent: number+ direction: 'Up' | 'Down'+ is_good: boolean+}++export interface WebAnalyticsDigestMetric {+ key: string+ label: string+ value: string+ change: WebAnalyticsDigestMetricChange | null+}++export interface WebAnalyticsDigestListItem {+ label: string+ value: string+}++export interface WebAnalyticsDigestMetadata {+ period_label: string+ project_name: string+ dashboard_url: string+ metrics: WebAnalyticsDigestMetric[]+ top_pages: WebAnalyticsDigestListItem[]+ top_sources: WebAnalyticsDigestListItem[]+}+export interface InAppNotification {id: stringteam_id: number | null@@ -444,6 +471,7 @@ export interface InAppNotification {source_url: stringsource_type: string | nullsource_id: string | null+ metadata: WebAnalyticsDigestMetadata | nullcreated_at: string}diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.pyindex 2753fd62a2f3..474546380fd6 100644--- a/posthog/temporal/schedule.py+++ b/posthog/temporal/schedule.py@@ -94,6 +94,7 @@ from products.replay_vision.backend.temporal.gemini_cleanup_sweep import (from products.replay_vision.backend.temporal.reconciler import create_replay_vision_reconciler_schedulefrom products.signals.backend.temporal.agentic.schedule import create_signals_scout_coordinator_schedulefrom products.tasks.backend.temporal.code_workstreams.schedule import create_evaluate_code_workstreams_schedule+from products.web_analytics.backend.temporal.digest_notification.types import WADigestNotificationInputfrom products.web_analytics.backend.temporal.weekly_digest.types import WAWeeklyDigestInputfrom ee.billing.salesforce_enrichment.constants import DEFAULT_CHUNK_SIZE@@ -403,6 +404,41 @@ async def create_wa_weekly_digest_schedule(client: Client):)+async def create_wa_digest_notification_schedule(client: Client):+ """Create or update the schedule for the WA digest notification workflow."""+ wa_digest_notification_schedule = Schedule(+ action=ScheduleActionStartWorkflow(+ "wa-digest-notification",+ WADigestNotificationInput(),+ id="wa-digest-notification-schedule",+ task_queue=settings.MESSAGING_TASK_QUEUE,+ retry_policy=common.RetryPolicy(+ maximum_attempts=1,+ ),+ ),+ spec=ScheduleSpec(+ calendars=[+ ScheduleCalendarSpec(+ comment="Weekly at Monday 9 AM PT",+ hour=[ScheduleRange(start=9, end=9)],+ day_of_week=[ScheduleRange(start=1, end=1)],+ )+ ],+ time_zone_name="America/Los_Angeles",+ ),+ )++ if await a_schedule_exists(client, "wa-digest-notification-schedule"):+ await a_update_schedule(client, "wa-digest-notification-schedule", wa_digest_notification_schedule)+ else:+ await a_create_schedule(+ client,+ "wa-digest-notification-schedule",+ wa_digest_notification_schedule,+ trigger_immediately=False,+ )++async def create_ducklake_compaction_schedule(client: Client):"""Create or update the schedule for the DuckLake compaction workflow.@@ -662,6 +698,7 @@ schedules = [create_error_tracking_symbol_set_cleanup_schedule,create_error_tracking_spike_event_cleanup_schedule,create_wa_weekly_digest_schedule,+ create_wa_digest_notification_schedule,create_logs_alert_check_schedule,create_schedule_due_alert_checks_schedule,create_run_investigation_safety_net_schedule,diff --git a/products/notifications/backend/facade/contracts.py b/products/notifications/backend/facade/contracts.pyindex c7cc2018c13b..227bca04ee9a 100644--- a/products/notifications/backend/facade/contracts.py+++ b/products/notifications/backend/facade/contracts.py@@ -1,7 +1,7 @@from __future__ import annotationsfrom dataclasses import dataclass, field-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Anyfrom products.notifications.backend.facade.enums import (NotificationResourceType,@@ -29,4 +29,5 @@ class NotificationData:source_type: SourceType | None = Nonesource_id: str | None = Nonepriority: Priority = Priority.NORMAL+ metadata: dict[str, Any] | None = Noneresolver: RecipientsResolver | None = field(default=None, compare=False)diff --git a/products/notifications/backend/facade/enums.py b/products/notifications/backend/facade/enums.pyindex a15818085e78..8ecea4c61bae 100644--- a/products/notifications/backend/facade/enums.py+++ b/products/notifications/backend/facade/enums.py@@ -15,6 +15,7 @@ class NotificationType(str, Enum):PIPELINE_FAILURE = "pipeline_failure"PROJECT_CREATED = "project_created"USAGE_SPIKE = "usage_spike"+ WEB_ANALYTICS_DIGEST = "web_analytics_digest"class Priority(str, Enum):diff --git a/products/notifications/backend/logic.py b/products/notifications/backend/logic.pyindex 37e406053760..74e39cd74fd8 100644--- a/products/notifications/backend/logic.py+++ b/products/notifications/backend/logic.py@@ -143,6 +143,7 @@ def create_notification(data: NotificationData) -> NotificationEvent | None:target_type=data.target_type,target_id=data.target_id,resolved_user_ids=resolved_user_ids,+ metadata=data.metadata,)def _on_commit() -> None:diff --git a/products/notifications/backend/migrations/0013_notificationevent_metadata.py b/products/notifications/backend/migrations/0013_notificationevent_metadata.pynew file mode 100644index 000000000000..719d5f2e98b4--- /dev/null+++ b/products/notifications/backend/migrations/0013_notificationevent_metadata.py@@ -0,0 +1,17 @@+# Generated by Django 5.2.14 on 2026-06-11 05:23++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("notifications", "0012_alter_notificationevent_notification_type"),+ ]++ operations = [+ migrations.AddField(+ model_name="notificationevent",+ name="metadata",+ field=models.JSONField(blank=True, default=None, null=True),+ ),+ ]diff --git a/products/notifications/backend/migrations/0014_alter_notificationevent_notification_type.py b/products/notifications/backend/migrations/0014_alter_notificationevent_notification_type.pynew file mode 100644index 000000000000..aad626f54802--- /dev/null+++ b/products/notifications/backend/migrations/0014_alter_notificationevent_notification_type.py@@ -0,0 +1,31 @@+# Generated by Django 5.2.14 on 2026-06-08 22:22++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("notifications", "0013_notificationevent_metadata"),+ ]++ operations = [+ migrations.AlterField(+ model_name="notificationevent",+ name="notification_type",+ field=models.CharField(+ choices=[+ ("comment_mention", "COMMENT_MENTION"),+ ("alert_firing", "ALERT_FIRING"),+ ("issue_assigned", "ISSUE_ASSIGNED"),+ ("approval_requested", "APPROVAL_REQUESTED"),+ ("approval_resolved", "APPROVAL_RESOLVED"),+ ("experiment_concluded", "EXPERIMENT_CONCLUDED"),+ ("pipeline_failure", "PIPELINE_FAILURE"),+ ("project_created", "PROJECT_CREATED"),+ ("usage_spike", "USAGE_SPIKE"),+ ("web_analytics_digest", "WEB_ANALYTICS_DIGEST"),+ ],+ max_length=32,+ ),+ ),+ ]diff --git a/products/notifications/backend/migrations/max_migration.txt b/products/notifications/backend/migrations/max_migration.txtindex dafb13aee25e..03b894d2199e 100644--- a/products/notifications/backend/migrations/max_migration.txt+++ b/products/notifications/backend/migrations/max_migration.txt@@ -1 +1 @@-0012_alter_notificationevent_notification_type+0014_alter_notificationevent_notification_typediff --git a/products/notifications/backend/models.py b/products/notifications/backend/models.pyindex bc957a3d7ec2..b85412d392bf 100644--- a/products/notifications/backend/models.py+++ b/products/notifications/backend/models.py@@ -20,6 +20,7 @@ class NotificationEvent(UUIDModel):target_type = models.CharField(max_length=16, choices=[(t.value, t.name) for t in TargetType])target_id = models.CharField(max_length=64)resolved_user_ids = models.JSONField(default=list)+ metadata = models.JSONField(null=True, blank=True, default=None)created_at = models.DateTimeField(auto_now_add=True)class Meta:diff --git a/products/notifications/backend/presentation/serializers.py b/products/notifications/backend/presentation/serializers.pyindex f5c16107108d..9e5355f43988 100644--- a/products/notifications/backend/presentation/serializers.py+++ b/products/notifications/backend/presentation/serializers.py@@ -1,8 +1,15 @@+from drf_spectacular.types import OpenApiTypes+from drf_spectacular.utils import extend_schema_fieldfrom rest_framework import serializersfrom products.notifications.backend.facade.enums import SourceType+@extend_schema_field(OpenApiTypes.OBJECT)+class _NotificationMetadataField(serializers.JSONField):+ pass++class NotificationEventSerializer(serializers.Serializer):id = serializers.UUIDField()team_id = serializers.IntegerField(allow_null=True)@@ -19,4 +26,14 @@ class NotificationEventSerializer(serializers.Serializer):source_url = serializers.CharField()source_type = serializers.ChoiceField(choices=[(s.value, s.name) for s in SourceType], allow_null=True)source_id = serializers.CharField(allow_null=True)+ metadata = _NotificationMetadataField(+ required=False,+ allow_null=True,+ help_text=(+ "Optional structured payload for rich client-side rendering, specific to the notification "+ "type. For `web_analytics_digest`, holds the weekly metrics (visitors, pageviews, sessions, "+ "bounce rate, session duration with week-over-week change), top pages, and top sources used "+ "to render the digest card."+ ),+ )created_at = serializers.DateTimeField()diff --git a/products/notifications/frontend/generated/api.schemas.ts b/products/notifications/frontend/generated/api.schemas.tsindex 8101853a5f4a..c73edc69677f 100644--- a/products/notifications/frontend/generated/api.schemas.ts+++ b/products/notifications/frontend/generated/api.schemas.ts@@ -33,6 +33,12 @@ export const NotificationEventSourceTypeEnumApi = {CustomerAnalytics: 'customer_analytics',} as const+/**+ * Optional structured payload for rich client-side rendering, specific to the notification type. For `web_analytics_digest`, holds the weekly metrics (visitors, pageviews, sessions, bounce rate, session duration with week-over-week change), top pages, and top sources used to render the digest card.+ * @nullable+ */+export type NotificationEventApiMetadata = { [key: string]: unknown } | null+export interface NotificationEventApi {id: string/** @nullable */@@ -53,6 +59,11 @@ export interface NotificationEventApi {source_type: NotificationEventSourceTypeEnumApi | null/** @nullable */source_id: string | null+ /**+ * Optional structured payload for rich client-side rendering, specific to the notification type. For `web_analytics_digest`, holds the weekly metrics (visitors, pageviews, sessions, bounce rate, session duration with week-over-week change), top pages, and top sources used to render the digest card.+ * @nullable+ */+ metadata?: NotificationEventApiMetadatacreated_at: string}diff --git a/products/web_analytics/backend/temporal/__init__.py b/products/web_analytics/backend/temporal/__init__.pyindex 7514660ae673..b3e549d2df89 100644--- a/products/web_analytics/backend/temporal/__init__.py+++ b/products/web_analytics/backend/temporal/__init__.py@@ -1,7 +1,11 @@+from products.web_analytics.backend.temporal.digest_notification import (+ ACTIVITIES as DIGEST_NOTIFICATION_ACTIVITIES,+ WORKFLOWS as DIGEST_NOTIFICATION_WORKFLOWS,+)from products.web_analytics.backend.temporal.weekly_digest import (ACTIVITIES as WEEKLY_DIGEST_ACTIVITIES,WORKFLOWS as WEEKLY_DIGEST_WORKFLOWS,)-WORKFLOWS = WEEKLY_DIGEST_WORKFLOWS-ACTIVITIES = WEEKLY_DIGEST_ACTIVITIES+WORKFLOWS = WEEKLY_DIGEST_WORKFLOWS + DIGEST_NOTIFICATION_WORKFLOWS+ACTIVITIES = WEEKLY_DIGEST_ACTIVITIES + DIGEST_NOTIFICATION_ACTIVITIESdiff --git a/products/web_analytics/backend/temporal/digest_common.py b/products/web_analytics/backend/temporal/digest_common.pynew file mode 100644index 000000000000..b7c532bfd067--- /dev/null+++ b/products/web_analytics/backend/temporal/digest_common.py@@ -0,0 +1,32 @@+from datetime import timedelta++from django.db.models import QuerySet++from temporalio import common++from posthog.models.organization import Organization++ACTIVITY_RETRY_POLICY = common.RetryPolicy(+ maximum_attempts=3,+ initial_interval=timedelta(seconds=30),+ backoff_coefficient=2.0,+ maximum_interval=timedelta(minutes=5),+)+++def paginate_index(items: list[str], cursor: str | None, page_size: int) -> tuple[list[str], str | None]:+ start = int(cursor) if cursor is not None else 0+ page = items[start : start + page_size]+ next_index = start + len(page)+ next_cursor = str(next_index) if next_index < len(items) else None+ return page, next_cursor+++def paginate_keyset(qs: QuerySet[Organization], cursor: str | None, page_size: int) -> tuple[list[str], str | None]:+ if cursor is not None:+ qs = qs.filter(id__gt=cursor)+ fetched = [str(oid) for oid in qs.order_by("id").values_list("id", flat=True)[: page_size + 1]]+ page = fetched[:page_size]+ has_more = len(fetched) > page_size+ next_cursor = page[-1] if has_more and page else None+ return page, next_cursordiff --git a/products/web_analytics/backend/temporal/digest_notification/__init__.py b/products/web_analytics/backend/temporal/digest_notification/__init__.pynew file mode 100644index 000000000000..965bc2e9c350--- /dev/null+++ b/products/web_analytics/backend/temporal/digest_notification/__init__.py@@ -0,0 +1,16 @@+from products.web_analytics.backend.temporal.digest_notification.activities import (+ get_org_batch_page,+ run_wa_digest_notification_batch,+ send_test_wa_digest_notification,+)+from products.web_analytics.backend.temporal.digest_notification.workflows import (+ WADigestNotificationTestWorkflow,+ WADigestNotificationWorkflow,+)++WORKFLOWS = [WADigestNotificationWorkflow, WADigestNotificationTestWorkflow]+ACTIVITIES = [+ get_org_batch_page,+ run_wa_digest_notification_batch,+ send_test_wa_digest_notification,+]diff --git a/products/web_analytics/backend/temporal/digest_notification/activities.py b/products/web_analytics/backend/temporal/digest_notification/activities.pynew file mode 100644index 000000000000..a01b123eab2a--- /dev/null+++ b/products/web_analytics/backend/temporal/digest_notification/activities.py@@ -0,0 +1,517 @@+import time+from itertools import batched+from typing import cast+from uuid import UUID++from django.db import close_old_connections++import structlog+import posthoganalytics+from temporalio import activity++from posthog.clickhouse.client.execute import KillSwitchLevel, get_kill_switch_level+from posthog.clickhouse.query_tagging import Feature, Product, tag_queries+from posthog.exceptions_capture import capture_exception+from posthog.models import Team+from posthog.models.organization import Organization, OrganizationMembership+from posthog.models.user import User+from posthog.ph_client import ph_scoped_capture+from posthog.sync import database_sync_to_async+from posthog.temporal.common.heartbeat import Heartbeater+from posthog.user_permissions import UserPermissions++from products.notifications.backend.facade.api import (+ NotificationData,+ NotificationType,+ Priority,+ TargetType,+ create_notification,+)+from products.web_analytics.backend.temporal.digest_common import paginate_index, paginate_keyset+from products.web_analytics.backend.temporal.digest_notification.types import (+ DigestBatchInput,+ DigestBatchResult,+ NotificationDigestOutcome,+ OrgBatchPageInput,+ OrgBatchPageResult,+ OrgDigestNotificationCounts,+ SendTestDigestNotificationInput,+)+from products.web_analytics.backend.weekly_digest import build_team_digest++logger = structlog.get_logger(__name__)+++def _org_has_realtime_notifications(org: Organization) -> bool:+ try:+ return bool(+ posthoganalytics.feature_enabled(+ "real-time-notifications",+ str(org.id),+ groups={"organization": str(org.id)},+ only_evaluate_locally=False,+ send_feature_flag_events=False,+ )+ )+ except Exception as e:+ logger.warning(+ "wa digest notification: real-time-notifications flag eval failed, treating org as disabled",+ org_id=str(org.id),+ error=str(e),+ )+ capture_exception(e, {"org_id": str(org.id)})+ return False+++def _get_digest_variant(user: User, org_id: str, flag_key: str) -> str | None:+ try:+ variant = cast(+ "bool | str | None",+ posthoganalytics.get_feature_flag(+ flag_key,+ distinct_id=str(user.distinct_id),+ groups={"organization": org_id},+ only_evaluate_locally=False,+ send_feature_flag_events=True,+ ),+ )+ except Exception as e:+ logger.warning(+ "wa digest notification: holdout flag eval failed, treating user as not exposed",+ user_id=str(user.uuid),+ org_id=org_id,+ error=str(e),+ )+ capture_exception(e, {"user_id": str(user.uuid), "org_id": org_id})+ return None++ if variant is None:+ return None+ if isinstance(variant, bool):+ return "test" if variant else "control"+ return variant+++def _build_title(digest: dict) -> str:+ visitors = int(digest["visitors"]["current"] or 0)+ title = f"{visitors:,} visitor{'' if visitors == 1 else 's'} this week"+ change = digest.get("visitors", {}).get("change")+ if isinstance(change, dict):+ direction = change.get("direction")+ percent = change.get("percent")+ if direction in ("Up", "Down") and percent:+ arrow = "↑" if direction == "Up" else "↓"+ title = f"{title} {arrow}{percent}%"+ return title+++def _build_body(digest: dict) -> str:+ pageviews = int(digest["pageviews"]["current"] or 0)+ body = f"{pageviews:,} page view{'' if pageviews == 1 else 's'}"++ top_pages = digest.get("top_pages") or []+ if top_pages and top_pages[0].get("path"):+ body = f"{body} · Top page {top_pages[0]['path']}"++ top_sources = digest.get("top_sources") or []+ if top_sources and top_sources[0].get("name"):+ body = f"{body} · Top source {top_sources[0]['name']}"++ return body+++_DIGEST_GOOD_COLOR = "#2f7d4f"+++def _digest_change(change: dict | None) -> dict | None:+ if not isinstance(change, dict):+ return None+ direction = change.get("direction")+ percent = change.get("percent")+ if direction not in ("Up", "Down") or not percent:+ return None+ return {"percent": percent, "direction": direction, "is_good": change.get("color") == _DIGEST_GOOD_COLOR}+++def _digest_metric(key: str, label: str, value: str, change: dict | None) -> dict:+ return {"key": key, "label": label, "value": value, "change": _digest_change(change)}+++def _build_digest_metadata(digest: dict) -> dict:+ team = digest["team"]+ visitors = int(digest["visitors"]["current"] or 0)+ pageviews = int(digest["pageviews"]["current"] or 0)+ sessions = int(digest["sessions"]["current"] or 0)+ bounce = digest["bounce_rate"]["current"] or 0+ return {+ "period_label": "Last 7 days",+ "project_name": team.name,+ "dashboard_url": digest["dashboard_url"],+ "metrics": [+ _digest_metric("visitors", "Visitors", f"{visitors:,}", digest["visitors"]["change"]),+ _digest_metric("pageviews", "Page views", f"{pageviews:,}", digest["pageviews"]["change"]),+ _digest_metric("sessions", "Sessions", f"{sessions:,}", digest["sessions"]["change"]),+ _digest_metric("bounce_rate", "Bounce rate", f"{round(bounce)}%", digest["bounce_rate"]["change"]),+ _digest_metric(+ "avg_session_duration",+ "Avg. session",+ digest["avg_session_duration"]["current"] or "0s",+ digest["avg_session_duration"]["change"],+ ),+ ],+ "top_pages": [+ {"label": p.get("path") or "/", "value": f"{int(p.get('visitors') or 0):,}"}+ for p in (digest.get("top_pages") or [])[:3]+ ],+ "top_sources": [+ {"label": s.get("name") or "", "value": f"{int(s.get('visitors') or 0):,}"}+ for s in (digest.get("top_sources") or [])[:3]+ ],+ }+++def _capture_digest_sent(+ user: User,+ org: Organization,+ team_id: int,+ digest: dict,+ variant: str | None,+ notification_id: UUID,+) -> None:+ try:+ with ph_scoped_capture() as capture:+ capture(+ distinct_id=str(user.distinct_id),+ event="web_analytics_digest_notification_sent",+ properties={+ "org_id": str(org.id),+ "team_id": team_id,+ "variant": variant,+ "visitors": digest["visitors"]["current"],+ "pageviews": digest["pageviews"]["current"],+ "notification_id": str(notification_id),+ },+ groups={"organization": str(org.id)},+ )+ except Exception as e:+ logger.warning(+ "wa digest notification: failed to capture sent event",+ org_id=str(org.id),+ user_id=str(user.uuid),+ error=str(e),+ )+ capture_exception(e, {"org_id": str(org.id), "user_id": str(user.uuid)})+++def _accessible_team_data(+ user: User,+ org: Organization,+ membership: OrganizationMembership,+ team_digest_data: dict[int, dict],+) -> dict[int, dict]:+ user_perms = UserPermissions(user)+ accessible: dict[int, dict] = {}+ for team_id, data in team_digest_data.items():+ team = data["team"]+ if user_perms.team(team).effective_membership_level_for_parent_membership(org, membership) is not None:+ accessible[team_id] = data+ return accessible+++def _send_digest_notification(+ *,+ user: User,+ org: Organization,+ team_digest_data: dict[int, dict],+ variant: str | None,+) -> NotificationDigestOutcome:+ busiest_team_id = max(team_digest_data, key=lambda tid: team_digest_data[tid]["visitors"]["current"] or 0)+ busiest = team_digest_data[busiest_team_id]++ event = create_notification(+ NotificationData(+ team_id=busiest_team_id,+ notification_type=NotificationType.WEB_ANALYTICS_DIGEST,+ title=_build_title(busiest),+ body=_build_body(busiest),+ target_type=TargetType.USER,+ target_id=str(user.id),+ resource_type="web_analytics",+ priority=Priority.NORMAL,+ source_url=f"/project/{busiest_team_id}/web?utm_source=web_analytics_digest&utm_medium=in_app",+ metadata=_build_digest_metadata(busiest),+ )+ )++ if event is None:+ return NotificationDigestOutcome.SKIPPED_NO_DATA++ _capture_digest_sent(user, org, busiest_team_id, busiest, variant, event.id)+ return NotificationDigestOutcome.SENT+++def _expose_and_notify_user(+ *,+ user: User,+ org: Organization,+ membership: OrganizationMembership,+ team_digest_data: dict[int, dict],+ flag_key: str,+ dry_run: bool,+) -> NotificationDigestOutcome:+ accessible = _accessible_team_data(user, org, membership, team_digest_data)+ if not accessible:+ return NotificationDigestOutcome.SKIPPED_NO_DATA++ variant = _get_digest_variant(user, str(org.id), flag_key)+ if variant != "test":+ return NotificationDigestOutcome.CONTROL++ if dry_run:+ return NotificationDigestOutcome.DRY_RUN++ return _send_digest_notification(user=user, org=org, team_digest_data=accessible, variant=variant)+++def _build_team_digest_data(org: Organization) -> tuple[dict[int, dict], int, float]:+ build_start = time.monotonic()+ team_digest_data: dict[int, dict] = {}+ for team in Team.objects.filter(organization_id=org.id):+ digest = build_team_digest(team)+ if (digest["visitors"]["current"] or 0) > 0:+ team_digest_data[team.id] = digest+ build_duration = time.monotonic() - build_start+ return team_digest_data, len(team_digest_data), build_duration+++def _build_and_send_for_org(org_id: str, flag_key: str, dry_run: bool = False) -> OrgDigestNotificationCounts:+ close_old_connections()++ counts = OrgDigestNotificationCounts()++ try:+ org = Organization.objects.get(id=org_id)+ except Organization.DoesNotExist:+ logger.warning("Organization not found for WA digest notification", org_id=org_id)+ counts.skipped_reason = "org_not_found"+ return counts++ if not _org_has_realtime_notifications(org):+ counts.skipped_reason = "notifications_not_enabled"+ return counts++ if not Team.objects.filter(organization_id=org.id).exists():+ counts.skipped_reason = "no_teams"+ return counts++ team_digest_data, counts.team_count, counts.build_duration = _build_team_digest_data(org)+ if not team_digest_data:+ counts.skipped_reason = "no_wa_data"+ return counts++ send_start = time.monotonic()+ for membership in OrganizationMembership.objects.prefetch_related("user").filter(+ organization_id=org.id, user__is_active=True+ ):+ try:+ outcome = _expose_and_notify_user(+ user=membership.user,+ org=org,+ membership=membership,+ team_digest_data=team_digest_data,+ flag_key=flag_key,+ dry_run=dry_run,+ )+ except Exception as e:+ logger.warning(+ "wa digest notification: failed to process user",+ org_id=org_id,+ user_id=str(membership.user.uuid),+ error=str(e),+ )+ capture_exception(e, {"org_id": org_id, "user_id": str(membership.user.uuid)})+ counts.failed += 1+ continue+ if outcome in (NotificationDigestOutcome.SENT, NotificationDigestOutcome.DRY_RUN):+ counts.sent += 1+ elif outcome == NotificationDigestOutcome.CONTROL:+ counts.control += 1+ elif outcome == NotificationDigestOutcome.SKIPPED_NO_DATA:+ counts.skipped_no_data += 1+ elif outcome == NotificationDigestOutcome.FAILED:+ counts.failed += 1+ counts.send_duration = time.monotonic() - send_start++ logger.info(+ "Sent WA digest notifications for org",+ org_id=org_id,+ sent_count=counts.sent,+ control=counts.control,+ skipped_no_data=counts.skipped_no_data,+ failed=counts.failed,+ team_count=counts.team_count,+ )+ return counts+++def _run_wa_digest_notification_batch(input: DigestBatchInput) -> DigestBatchResult:+ close_old_connections()++ tag_queries(+ product=Product.WEB_ANALYTICS,+ feature=Feature.DIGEST,+ name="wa_digest_notification",+ )++ totals = DigestBatchResult(batch_size=len(input.org_ids))++ for org_id in input.org_ids:+ try:+ org_counts = _build_and_send_for_org(org_id, flag_key=input.flag_key, dry_run=input.dry_run)+ except Exception as e:+ logger.exception("WA digest notification failed for org", org_id=org_id, error=str(e))+ capture_exception(e, {"org_id": org_id})+ totals.orgs_failed += 1+ continue++ if org_counts.skipped_reason is not None:+ totals.orgs_skipped += 1+ continue++ totals.orgs_processed += 1+ totals.notifications_sent += org_counts.sent+ totals.control_exposed += org_counts.control+ totals.skipped_no_data += org_counts.skipped_no_data+ totals.failed += org_counts.failed+ totals.build_duration += org_counts.build_duration+ totals.send_duration += org_counts.send_duration++ return totals+++def _get_org_batch_page(input: OrgBatchPageInput) -> OrgBatchPageResult:+ close_old_connections()++ kill_switch_level = get_kill_switch_level()+ if kill_switch_level != KillSwitchLevel.OFF:+ logger.info(+ "skipping wa digest notification due to clickhouse kill switch",+ kill_switch_level=kill_switch_level.value,+ )+ return OrgBatchPageResult(batches=[], cursor=None)++ workflow_input = input.workflow_input++ if workflow_input.org_ids:+ page_org_ids, next_cursor = paginate_index(list(workflow_input.org_ids), input.cursor, input.page_size)+ source = "configured"+ else:+ page_org_ids, next_cursor = paginate_keyset(Organization.objects.all(), input.cursor, input.page_size)+ source = "keyset"++ batches = [list(b) for b in batched(page_org_ids, workflow_input.batch_size, strict=False)]+ logger.info(+ "wa digest notification org batch page",+ source=source,+ count=len(page_org_ids),+ batch_count=len(batches),+ batch_size=workflow_input.batch_size,+ cursor=input.cursor,+ next_cursor=next_cursor,+ )+ return OrgBatchPageResult(batches=batches, cursor=next_cursor)+++def _send_test_digest_notification(email: str, team_id: int | None = None) -> None:+ close_old_connections()++ user = User.objects.filter(email__iexact=email, is_active=True).first()+ if not user:+ raise ValueError(f"No active user found with email {email}")++ if team_id is not None:+ team = Team.objects.select_related("organization").filter(id=team_id).first()+ if not team:+ raise ValueError(f"Team {team_id} not found")++ membership = OrganizationMembership.objects.filter(+ organization_id=team.organization_id,+ user_id=user.id,+ ).first()+ if not membership:+ raise PermissionError(f"User {email} is not a member of the organization that owns team {team_id}")++ digest = build_team_digest(team)+ accessible = _accessible_team_data(user, team.organization, membership, {team.id: digest})+ if not accessible:+ raise PermissionError(f"User {email} does not have access to team {team_id}")++ outcome = _send_digest_notification(+ user=user,+ org=team.organization,+ team_digest_data=accessible,+ variant="test",+ )+ if outcome != NotificationDigestOutcome.SENT:+ raise RuntimeError(+ f"Test digest notification not delivered for team {team_id} "+ f"(real-time-notifications disabled or no recipients)"+ )++ logger.info(+ "Sent test WA digest notification",+ mode="single_team",+ team_id=team_id,+ team_name=team.name,+ email=email,+ )+ return++ memberships = list(OrganizationMembership.objects.select_related("organization").filter(user_id=user.id))+ if not memberships:+ raise ValueError(f"User {email} has no organization memberships")++ sent_count = 0+ for membership in memberships:+ org = membership.organization+ team_digest_data = {t.id: build_team_digest(t) for t in Team.objects.filter(organization_id=org.id)}+ accessible = _accessible_team_data(user, org, membership, team_digest_data)+ if not accessible:+ continue+ outcome = _send_digest_notification(+ user=user,+ org=org,+ team_digest_data=accessible,+ variant="test",+ )+ if outcome == NotificationDigestOutcome.SENT:+ sent_count += 1++ if sent_count == 0:+ raise RuntimeError(+ f"No test digest notifications delivered for {email} "+ f"(no accessible teams, or real-time-notifications disabled in their orgs)"+ )++ logger.info(+ "Sent test WA digest notification",+ mode="full_user_digest",+ email=email,+ notifications_sent=sent_count,+ )++[email protected](name="wa-digest-notif-get-org-batch-page")+async def get_org_batch_page(input: OrgBatchPageInput) -> OrgBatchPageResult:+ return await database_sync_to_async(_get_org_batch_page, thread_sensitive=False)(input)++[email protected](name="wa-digest-notif-run-batch")+async def run_wa_digest_notification_batch(input: DigestBatchInput) -> DigestBatchResult:+ async with Heartbeater():+ return await database_sync_to_async(_run_wa_digest_notification_batch, thread_sensitive=False)(input)++[email protected](name="wa-digest-notif-send-test")+async def send_test_wa_digest_notification(input: SendTestDigestNotificationInput) -> None:+ await database_sync_to_async(_send_test_digest_notification, thread_sensitive=False)(input.email, input.team_id)diff --git a/products/web_analytics/backend/temporal/digest_notification/types.py b/products/web_analytics/backend/temporal/digest_notification/types.pynew file mode 100644index 000000000000..6662dc6354bb--- /dev/null+++ b/products/web_analytics/backend/temporal/digest_notification/types.py@@ -0,0 +1,97 @@+import dataclasses+from enum import StrEnum+++class NotificationDigestOutcome(StrEnum):+ SENT = "sent"+ CONTROL = "control"+ DRY_RUN = "dry_run"+ SKIPPED_NO_DATA = "skipped_no_data"+ FAILED = "failed"+++class WADigestNotificationInput:+ dry_run: bool = False+ batch_size: int = 25+ max_concurrent: int = 4+ failure_threshold: float = 0.2+ flag_key: str = "web-analytics-digest-notification"+ org_ids: list[str] | None = None+++class OrgBatchPageInput:+ workflow_input: WADigestNotificationInput+ cursor: str | None = None+ page_size: int = 5000+++class OrgBatchPageResult:+ batches: list[list[str]]+ cursor: str | None++ @property+ def org_count(self) -> int:+ return sum(len(batch) for batch in self.batches)++ @property+ def batch_count(self) -> int:+ return len(self.batches)+++class OrgDigestNotificationCounts:+ sent: int = 0+ control: int = 0+ skipped_no_data: int = 0+ failed: int = 0+ team_count: int = 0+ build_duration: float = 0.0+ send_duration: float = 0.0+ skipped_reason: str | None = None+++class DigestBatchInput:+ org_ids: list[str]+ dry_run: bool = False+ flag_key: str = "web-analytics-digest-notification"+++class DigestBatchResult:+ batch_size: int = 0+ orgs_processed: int = 0+ orgs_skipped: int = 0+ orgs_failed: int = 0+ notifications_sent: int = 0+ control_exposed: int = 0+ skipped_no_data: int = 0+ failed: int = 0+ build_duration: float = 0.0+ send_duration: float = 0.0++ @property+ def total_duration(self) -> float:+ return self.build_duration + self.send_duration++ @property+ def failure_rate(self) -> float:+ attempted = self.orgs_processed + self.orgs_failed+ return self.orgs_failed / attempted if attempted > 0 else 0.0++ def __iadd__(self, other: "DigestBatchResult") -> "DigestBatchResult":+ for f in dataclasses.fields(self):+ setattr(self, f.name, getattr(self, f.name) + getattr(other, f.name))+ return self+++class SendTestDigestNotificationInput:+ email: str+ team_id: int | None = None+++WA_DIGEST_NOTIF_THRESHOLD_EXCEEDED_TYPE = "WADigestNotificationThresholdExceeded"diff --git a/products/web_analytics/backend/temporal/digest_notification/workflows.py b/products/web_analytics/backend/temporal/digest_notification/workflows.pynew file mode 100644index 000000000000..bddf4556fa97--- /dev/null+++ b/products/web_analytics/backend/temporal/digest_notification/workflows.py@@ -0,0 +1,137 @@+import json+import asyncio+import dataclasses+from datetime import timedelta++from temporalio import common, workflow+from temporalio.exceptions import ApplicationError++from posthog.temporal.common.base import PostHogWorkflow++with workflow.unsafe.imports_passed_through():+ from products.web_analytics.backend.temporal.digest_common import ACTIVITY_RETRY_POLICY+ from products.web_analytics.backend.temporal.digest_notification.activities import (+ get_org_batch_page,+ run_wa_digest_notification_batch,+ send_test_wa_digest_notification,+ )+ from products.web_analytics.backend.temporal.digest_notification.types import (+ WA_DIGEST_NOTIF_THRESHOLD_EXCEEDED_TYPE,+ DigestBatchInput,+ DigestBatchResult,+ OrgBatchPageInput,+ SendTestDigestNotificationInput,+ WADigestNotificationInput,+ )++[email protected](name="wa-digest-notification")+class WADigestNotificationWorkflow(PostHogWorkflow):+ @staticmethod+ def parse_inputs(inputs: list[str]) -> WADigestNotificationInput:+ if inputs:+ data = json.loads(inputs[0])+ return WADigestNotificationInput(+ **{f.name: data[f.name] for f in dataclasses.fields(WADigestNotificationInput) if f.name in data}+ )+ return WADigestNotificationInput()++ @workflow.run+ async def run(self, input: WADigestNotificationInput | None = None) -> dict:+ if input is None:+ input = WADigestNotificationInput()++ totals = DigestBatchResult()+ failed_batches = 0+ batch_count = 0+ cursor: str | None = None+ semaphore = asyncio.Semaphore(input.max_concurrent)++ async def _run_batch(batch: list[str]) -> DigestBatchResult:+ async with semaphore:+ return await workflow.execute_activity(+ run_wa_digest_notification_batch,+ DigestBatchInput(org_ids=batch, dry_run=input.dry_run, flag_key=input.flag_key),+ start_to_close_timeout=timedelta(minutes=30),+ heartbeat_timeout=timedelta(minutes=5),+ retry_policy=ACTIVITY_RETRY_POLICY,+ )++ while True:+ page = await workflow.execute_activity(+ get_org_batch_page,+ OrgBatchPageInput(workflow_input=input, cursor=cursor),+ start_to_close_timeout=timedelta(minutes=5),+ retry_policy=ACTIVITY_RETRY_POLICY,+ )++ if page.batches:+ workflow.logger.info(+ "Fanning out WA digest notification page",+ batches=len(page.batches),+ orgs=page.org_count,+ cursor=cursor,+ next_cursor=page.cursor,+ )++ batch_count += len(page.batches)+ results = await asyncio.gather(+ *[_run_batch(b) for b in page.batches],+ return_exceptions=True,+ )++ for batch, r in zip(page.batches, results):+ if isinstance(r, BaseException):+ failed_batches += 1+ totals += DigestBatchResult(batch_size=len(batch), orgs_failed=len(batch))+ workflow.logger.error("WA digest notification batch failed: %s", str(r))+ else:+ totals += r++ if page.cursor is None:+ break+ cursor = page.cursor++ if batch_count == 0:+ workflow.logger.info("No org batches for WA digest notification")++ threshold_exceeded = totals.batch_size > 0 and totals.failure_rate > input.failure_threshold++ if threshold_exceeded:+ raise ApplicationError(+ f"WA digest notification: {totals.orgs_failed:,}/{totals.batch_size:,} orgs failed "+ f"({totals.failure_rate:.1%}), exceeds threshold {input.failure_threshold:.1%} "+ f"(skipped={totals.orgs_skipped:,} not counted toward failure rate)",+ type=WA_DIGEST_NOTIF_THRESHOLD_EXCEEDED_TYPE,+ non_retryable=True,+ )++ return {+ "orgs": totals.batch_size,+ "batches": batch_count,+ "failed_batches": failed_batches,+ "notifications_sent": totals.notifications_sent,+ "control_exposed": totals.control_exposed,+ "failed": totals.failed,+ "cumulative_duration_seconds": totals.total_duration,+ }++[email protected](name="wa-digest-notification-test")+class WADigestNotificationTestWorkflow(PostHogWorkflow):+ @staticmethod+ def parse_inputs(inputs: list[str]) -> SendTestDigestNotificationInput:+ data = json.loads(inputs[0])+ return SendTestDigestNotificationInput(+ email=data["email"],+ team_id=data.get("team_id"),+ )++ @workflow.run+ async def run(self, input: SendTestDigestNotificationInput) -> None:+ await workflow.execute_activity(+ send_test_wa_digest_notification,+ input,+ start_to_close_timeout=timedelta(minutes=10),+ retry_policy=common.RetryPolicy(maximum_attempts=1),+ )diff --git a/products/web_analytics/backend/temporal/weekly_digest/activities.py b/products/web_analytics/backend/temporal/weekly_digest/activities.pyindex 68b00c3ff1b7..c6166df9e402 100644--- a/products/web_analytics/backend/temporal/weekly_digest/activities.py+++ b/products/web_analytics/backend/temporal/weekly_digest/activities.py@@ -26,6 +26,7 @@ from posthog.tasks.email import NotificationSetting, should_send_notificationfrom posthog.temporal.common.heartbeat import Heartbeaterfrom posthog.user_permissions import UserPermissions+from products.web_analytics.backend.temporal.digest_common import paginate_index, paginate_keysetfrom products.web_analytics.backend.temporal.weekly_digest.types import (WA_DIGEST_EMAIL_UNAVAILABLE_TYPE,DigestBatchInput,@@ -58,24 +59,6 @@ def _get_org_queryset_for_digest(input: WAWeeklyDigestInput) -> tuple[QuerySet[Oreturn qs, cutoff-def _paginate_index(items: list[str], cursor: str | None, page_size: int) -> tuple[list[str], str | None]:- start = int(cursor) if cursor is not None else 0- page = items[start : start + page_size]- next_index = start + len(page)- next_cursor = str(next_index) if next_index < len(items) else None- return page, next_cursor---def _paginate_keyset(qs: QuerySet[Organization], cursor: str | None, page_size: int) -> tuple[list[str], str | None]:- if cursor is not None:- qs = qs.filter(id__gt=cursor)- fetched = [str(oid) for oid in qs.order_by("id").values_list("id", flat=True)[: page_size + 1]]- page = fetched[:page_size]- has_more = len(fetched) > page_size- next_cursor = page[-1] if has_more and page else None- return page, next_cursor--def _get_org_batch_page(input: OrgBatchPageInput) -> OrgBatchPageResult:"""Raises non-retryable `ApplicationError` when email is globally unavailable— per-org skips would silently absorb the outage.@@ -101,11 +84,11 @@ def _get_org_batch_page(input: OrgBatchPageInput) -> OrgBatchPageResult:cutoff: datetime | None = Noneif workflow_input.org_ids:- page_org_ids, next_cursor = _paginate_index(list(workflow_input.org_ids), input.cursor, input.page_size)+ page_org_ids, next_cursor = paginate_index(list(workflow_input.org_ids), input.cursor, input.page_size)source = "configured"else:qs, cutoff = _get_org_queryset_for_digest(workflow_input)- page_org_ids, next_cursor = _paginate_keyset(qs, input.cursor, input.page_size)+ page_org_ids, next_cursor = paginate_keyset(qs, input.cursor, input.page_size)source = "keyset"batches = [list(b) for b in batched(page_org_ids, workflow_input.batch_size, strict=False)]diff --git a/products/web_analytics/backend/temporal/weekly_digest/workflows.py b/products/web_analytics/backend/temporal/weekly_digest/workflows.pyindex 59518f0a715d..3f8ba9c2efcb 100644--- a/products/web_analytics/backend/temporal/weekly_digest/workflows.py+++ b/products/web_analytics/backend/temporal/weekly_digest/workflows.py@@ -9,6 +9,7 @@ from temporalio.exceptions import ApplicationErrorfrom posthog.temporal.common.base import PostHogWorkflowwith workflow.unsafe.imports_passed_through():+ from products.web_analytics.backend.temporal.digest_common import ACTIVITY_RETRY_POLICYfrom products.web_analytics.backend.temporal.weekly_digest.activities import (get_org_batch_page,push_wa_digest_metrics_activity,@@ -25,14 +26,6 @@ with workflow.unsafe.imports_passed_through():)-ACTIVITY_RETRY_POLICY = common.RetryPolicy(- maximum_attempts=3,- initial_interval=timedelta(seconds=30),- backoff_coefficient=2.0,- maximum_interval=timedelta(minutes=5),-)--@workflow.defn(name="wa-weekly-digest")class WAWeeklyDigestWorkflow(PostHogWorkflow):@staticmethoddiff --git a/products/web_analytics/backend/test/test_digest_notification_activities.py b/products/web_analytics/backend/test/test_digest_notification_activities.pynew file mode 100644index 000000000000..6a32abe83344--- /dev/null+++ b/products/web_analytics/backend/test/test_digest_notification_activities.py@@ -0,0 +1,497 @@+import uuid++from posthog.test.base import APIBaseTest+from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.clickhouse.client.execute import KillSwitchLevel+from posthog.models import OrganizationMembership, Team, User+from posthog.models.organization import Organization++from products.notifications.backend.facade.api import NotificationType, TargetType+from products.web_analytics.backend.temporal.digest_notification.activities import (+ _build_and_send_for_org,+ _expose_and_notify_user,+ _get_org_batch_page,+ _run_wa_digest_notification_batch,+ _send_test_digest_notification,+)+from products.web_analytics.backend.temporal.digest_notification.types import (+ DigestBatchInput,+ NotificationDigestOutcome,+ OrgBatchPageInput,+ OrgDigestNotificationCounts,+ WADigestNotificationInput,+)++ACTIVITIES = "products.web_analytics.backend.temporal.digest_notification.activities"+++def _make_team_digest(team, visitors=10, pageviews=100):+ return {+ "team": team,+ "visitors": {+ "current": visitors,+ "previous": 5,+ "change": {"percent": 50, "direction": "Up", "color": "#2f7d4f"},+ },+ "pageviews": {"current": pageviews, "previous": 50, "change": None},+ "sessions": {"current": 0, "previous": None, "change": None},+ "bounce_rate": {"current": 0.0, "previous": None, "change": None},+ "avg_session_duration": {"current": "0s", "previous": "0s", "change": None},+ "top_pages": [{"path": "/pricing", "visitors": visitors, "change": None}],+ "top_sources": [{"name": "google.com", "visitors": visitors, "change": None}],+ "goals": [],+ "dashboard_url": "https://example.com/project/1/web",+ }+++def _make_notification_event():+ event = MagicMock()+ event.id = uuid.uuid4()+ return event+++class _DigestNotificationTestBase(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.close_conn_patcher = patch(f"{ACTIVITIES}.close_old_connections")+ self.close_conn_patcher.start()++ self.feature_enabled_patcher = patch(f"{ACTIVITIES}.posthoganalytics.feature_enabled", return_value=True)+ self.mock_feature_enabled = self.feature_enabled_patcher.start()++ self.get_flag_patcher = patch(f"{ACTIVITIES}.posthoganalytics.get_feature_flag", return_value="test")+ self.mock_get_flag = self.get_flag_patcher.start()++ self.create_notification_patcher = patch(+ f"{ACTIVITIES}.create_notification", return_value=_make_notification_event()+ )+ self.mock_create_notification = self.create_notification_patcher.start()++ self.build_digest_patcher = patch(+ f"{ACTIVITIES}.build_team_digest",+ side_effect=lambda team: _make_team_digest(team),+ )+ self.mock_build_digest = self.build_digest_patcher.start()++ self.capture_patcher = patch(f"{ACTIVITIES}.ph_scoped_capture")+ self.mock_ph_scoped_capture = self.capture_patcher.start()+ self.mock_capture = MagicMock()+ self.mock_ph_scoped_capture.return_value.__enter__.return_value = self.mock_capture++ def tearDown(self):+ self.capture_patcher.stop()+ self.build_digest_patcher.stop()+ self.create_notification_patcher.stop()+ self.get_flag_patcher.stop()+ self.feature_enabled_patcher.stop()+ self.close_conn_patcher.stop()+ super().tearDown()+++class TestBuildAndSendForOrg(_DigestNotificationTestBase):+ def test_test_arm_sends_notification_for_busiest_team(self):+ counts = _build_and_send_for_org(str(self.organization.id), flag_key="my-flag")++ assert counts.skipped_reason is None+ assert counts.sent == 1+ assert counts.control == 0++ self.mock_create_notification.assert_called_once()+ data = self.mock_create_notification.call_args.args[0]+ assert data.notification_type == NotificationType.WEB_ANALYTICS_DIGEST+ assert data.target_type == TargetType.USER+ assert data.target_id == str(self.user.id)+ assert data.team_id == self.team.id+ assert data.resource_type == "web_analytics"+ assert "utm_source=web_analytics_digest" in data.source_url++ def test_test_arm_records_exposure_and_captures_sent_event(self):+ _build_and_send_for_org(str(self.organization.id), flag_key="my-flag")++ self.mock_get_flag.assert_called_once()+ flag_kwargs = self.mock_get_flag.call_args.kwargs+ assert flag_kwargs["send_feature_flag_events"] is True+ assert flag_kwargs["groups"] == {"organization": str(self.organization.id)}++ self.mock_capture.assert_called_once()+ capture_kwargs = self.mock_capture.call_args.kwargs+ assert capture_kwargs["event"] == "web_analytics_digest_notification_sent"+ assert capture_kwargs["distinct_id"] == str(self.user.distinct_id)+ assert capture_kwargs["properties"]["variant"] == "test"+ assert capture_kwargs["properties"]["team_id"] == self.team.id++ def test_control_arm_records_exposure_but_sends_no_notification(self):+ self.mock_get_flag.return_value = "control"++ counts = _build_and_send_for_org(str(self.organization.id), flag_key="my-flag")++ assert counts.control == 1+ assert counts.sent == 0+ self.mock_get_flag.assert_called_once()+ assert self.mock_get_flag.call_args.kwargs["send_feature_flag_events"] is True+ self.mock_create_notification.assert_not_called()++ def test_org_without_realtime_notifications_is_skipped(self):+ self.mock_feature_enabled.return_value = False++ counts = _build_and_send_for_org(str(self.organization.id), flag_key="my-flag")++ assert counts.skipped_reason == "notifications_not_enabled"+ self.mock_get_flag.assert_not_called()+ self.mock_create_notification.assert_not_called()++ def test_org_with_no_wa_data_is_skipped(self):+ self.mock_build_digest.side_effect = lambda team: _make_team_digest(team, visitors=0)++ counts = _build_and_send_for_org(str(self.organization.id), flag_key="my-flag")++ assert counts.skipped_reason == "no_wa_data"+ self.mock_create_notification.assert_not_called()++ def test_busiest_team_is_selected_when_user_has_multiple(self):+ team_b = Team.objects.create(organization=self.organization, name="Team B")++ def digest_by_team(team):+ visitors = 500 if team.id == team_b.id else 10+ return _make_team_digest(team, visitors=visitors)++ self.mock_build_digest.side_effect = digest_by_team++ counts = _build_and_send_for_org(str(self.organization.id), flag_key="my-flag")++ assert counts.sent == 1+ data = self.mock_create_notification.call_args.args[0]+ assert data.team_id == team_b.id++ def test_per_user_failure_is_isolated_and_counted(self):+ second_user = User.objects.create_user(email="[email protected]", password="x", first_name="Second")+ OrganizationMembership.objects.create(+ organization=self.organization, user=second_user, level=OrganizationMembership.Level.MEMBER+ )++ self.mock_create_notification.side_effect = [+ RuntimeError("notification backend exploded"),+ _make_notification_event(),+ ]++ counts = _build_and_send_for_org(str(self.organization.id), flag_key="my-flag")++ assert counts.failed == 1+ assert counts.sent == 1+ assert self.mock_create_notification.call_count == 2++ def test_deactivated_users_are_excluded_from_fan_out(self):+ deactivated_user = User.objects.create_user(+ email="[email protected]", password="x", first_name="Gone", is_active=False+ )+ OrganizationMembership.objects.create(+ organization=self.organization, user=deactivated_user, level=OrganizationMembership.Level.MEMBER+ )++ counts = _build_and_send_for_org(str(self.organization.id), flag_key="my-flag")++ assert counts.sent == 1+ self.mock_create_notification.assert_called_once()+ self.mock_get_flag.assert_called_once()++ def test_capture_failure_does_not_change_sent_outcome(self):+ self.mock_ph_scoped_capture.side_effect = RuntimeError("capture pipeline down")++ counts = _build_and_send_for_org(str(self.organization.id), flag_key="my-flag")++ assert counts.sent == 1+ assert counts.failed == 0+ self.mock_create_notification.assert_called_once()++ def test_dry_run_records_exposure_but_does_not_send(self):+ counts = _build_and_send_for_org(str(self.organization.id), flag_key="my-flag", dry_run=True)++ assert counts.sent == 1+ self.mock_get_flag.assert_called_once()+ self.mock_create_notification.assert_not_called()+ self.mock_capture.assert_not_called()++ @parameterized.expand(+ [+ ("variant_none", None),+ ("variant_control", "control"),+ ]+ )+ def test_non_test_variants_do_not_send(self, _name, variant):+ self.mock_get_flag.return_value = variant++ counts = _build_and_send_for_org(str(self.organization.id), flag_key="my-flag")++ assert counts.sent == 0+ self.mock_create_notification.assert_not_called()++ def test_create_notification_returning_none_yields_skipped_no_data(self):+ self.mock_create_notification.return_value = None++ counts = _build_and_send_for_org(str(self.organization.id), flag_key="my-flag")++ assert counts.sent == 0+ assert counts.skipped_no_data == 1+ self.mock_capture.assert_not_called()++ def test_org_not_found_returns_skipped_reason(self):+ counts = _build_and_send_for_org(str(uuid.uuid4()), flag_key="my-flag")++ assert counts.skipped_reason == "org_not_found"+ self.mock_create_notification.assert_not_called()++ def test_org_gate_failing_flag_eval_treats_org_as_disabled(self):+ self.mock_feature_enabled.side_effect = RuntimeError("flag service down")++ counts = _build_and_send_for_org(str(self.organization.id), flag_key="my-flag")++ assert counts.skipped_reason == "notifications_not_enabled"+ self.mock_create_notification.assert_not_called()+++class TestExposeAndNotifyUser(_DigestNotificationTestBase):+ def test_user_without_accessible_data_is_not_exposed(self):+ outcome = _expose_and_notify_user(+ user=self.user,+ org=self.organization,+ membership=self.organization_membership,+ team_digest_data={},+ flag_key="my-flag",+ dry_run=False,+ )++ assert outcome == NotificationDigestOutcome.SKIPPED_NO_DATA+ self.mock_get_flag.assert_not_called()+ self.mock_create_notification.assert_not_called()++ def test_test_arm_user_with_data_is_exposed_and_sent(self):+ outcome = _expose_and_notify_user(+ user=self.user,+ org=self.organization,+ membership=self.organization_membership,+ team_digest_data={self.team.id: _make_team_digest(self.team)},+ flag_key="my-flag",+ dry_run=False,+ )++ assert outcome == NotificationDigestOutcome.SENT+ self.mock_get_flag.assert_called_once()+ self.mock_create_notification.assert_called_once()++ def test_control_arm_user_is_exposed_but_not_sent(self):+ self.mock_get_flag.return_value = "control"++ outcome = _expose_and_notify_user(+ user=self.user,+ org=self.organization,+ membership=self.organization_membership,+ team_digest_data={self.team.id: _make_team_digest(self.team)},+ flag_key="my-flag",+ dry_run=False,+ )++ assert outcome == NotificationDigestOutcome.CONTROL+ self.mock_get_flag.assert_called_once()+ self.mock_create_notification.assert_not_called()+++class TestRunWaDigestNotificationBatch(_DigestNotificationTestBase):+ def test_aggregates_per_org_results(self):+ results_by_org = {+ "1": OrgDigestNotificationCounts(sent=3, control=2, build_duration=0.4, send_duration=0.2),+ "2": OrgDigestNotificationCounts(skipped_no_data=4, failed=1, build_duration=0.1),+ "3": OrgDigestNotificationCounts(skipped_reason="no_teams"),+ }++ with patch(+ f"{ACTIVITIES}._build_and_send_for_org",+ side_effect=lambda org_id, flag_key, dry_run: results_by_org[org_id],+ ):+ totals = _run_wa_digest_notification_batch(DigestBatchInput(org_ids=["1", "2", "3"]))++ assert totals.batch_size == 3+ assert totals.orgs_processed == 2+ assert totals.orgs_skipped == 1+ assert totals.orgs_failed == 0+ assert totals.notifications_sent == 3+ assert totals.control_exposed == 2+ assert totals.skipped_no_data == 4+ assert totals.failed == 1++ def test_isolates_per_org_failures(self):+ def fake_build_and_send(org_id, flag_key, dry_run):+ if org_id == "2":+ raise RuntimeError("clickhouse exploded for org 2")+ return OrgDigestNotificationCounts(sent=1, control=1)++ with patch(f"{ACTIVITIES}._build_and_send_for_org", side_effect=fake_build_and_send):+ totals = _run_wa_digest_notification_batch(DigestBatchInput(org_ids=["1", "2", "3"]))++ assert totals.orgs_processed == 2+ assert totals.orgs_failed == 1+ assert totals.notifications_sent == 2+ assert totals.control_exposed == 2++ def test_passes_flag_key_and_dry_run_through(self):+ captured: list[tuple[str, str, bool]] = []++ def fake_build_and_send(org_id, flag_key, dry_run):+ captured.append((org_id, flag_key, dry_run))+ return OrgDigestNotificationCounts(sent=1)++ with patch(f"{ACTIVITIES}._build_and_send_for_org", side_effect=fake_build_and_send):+ _run_wa_digest_notification_batch(DigestBatchInput(org_ids=["1"], flag_key="custom-flag", dry_run=True))++ assert captured == [("1", "custom-flag", True)]++ def test_aggregates_via_real_build_and_send(self):+ control_user = User.objects.create_user(email="[email protected]", password="x", first_name="Ctrl")+ OrganizationMembership.objects.create(+ organization=self.organization, user=control_user, level=OrganizationMembership.Level.MEMBER+ )++ def variant_by_user(flag_key, distinct_id, **kwargs):+ return "control" if distinct_id == str(control_user.distinct_id) else "test"++ self.mock_get_flag.side_effect = variant_by_user++ totals = _run_wa_digest_notification_batch(DigestBatchInput(org_ids=[str(self.organization.id)]))++ assert totals.orgs_processed == 1+ assert totals.notifications_sent == 1+ assert totals.control_exposed == 1+++class TestGetOrgBatchPage(_DigestNotificationTestBase):+ def setUp(self):+ super().setUp()+ self.kill_switch_patcher = patch(f"{ACTIVITIES}.get_kill_switch_level", return_value=KillSwitchLevel.OFF)+ self.mock_kill_switch = self.kill_switch_patcher.start()++ def tearDown(self):+ self.kill_switch_patcher.stop()+ super().tearDown()++ def test_returns_empty_when_kill_switch_active(self):+ self.mock_kill_switch.return_value = KillSwitchLevel.LIGHT++ page = _get_org_batch_page(OrgBatchPageInput(workflow_input=WADigestNotificationInput()))++ assert page.batches == []+ assert page.cursor is None++ def test_keyset_pagination_pages_through_orgs(self):+ orgs = [self.organization]+ orgs.extend(Organization.objects.create(name=f"Org {i}") for i in range(4))+ expected_ids = sorted(str(org.id) for org in orgs)++ first_page = _get_org_batch_page(+ OrgBatchPageInput(workflow_input=WADigestNotificationInput(batch_size=2), page_size=2)+ )+ assert [oid for batch in first_page.batches for oid in batch] == expected_ids[:2]+ assert first_page.cursor == expected_ids[1]++ final_ids: list[str] = []+ cursor: str | None = first_page.cursor+ while cursor is not None:+ page = _get_org_batch_page(+ OrgBatchPageInput(workflow_input=WADigestNotificationInput(batch_size=2), cursor=cursor, page_size=2)+ )+ final_ids.extend(oid for batch in page.batches for oid in batch)+ cursor = page.cursor++ assert expected_ids[:2] + final_ids == expected_ids++ def test_configured_org_ids_paginate_by_index(self):+ override = ["1111", "2222", "3333"]++ first_page = _get_org_batch_page(+ OrgBatchPageInput(workflow_input=WADigestNotificationInput(org_ids=override, batch_size=2), page_size=2)+ )+ assert [oid for batch in first_page.batches for oid in batch] == ["1111", "2222"]+ assert first_page.cursor == "2"++ second_page = _get_org_batch_page(+ OrgBatchPageInput(+ workflow_input=WADigestNotificationInput(org_ids=override, batch_size=2),+ cursor=first_page.cursor,+ page_size=2,+ )+ )+ assert [oid for batch in second_page.batches for oid in batch] == ["3333"]+ assert second_page.cursor is None+++class TestSendTestDigestNotification(_DigestNotificationTestBase):+ def test_single_team_mode_sends_to_user_with_access(self):+ _send_test_digest_notification(email=self.user.email, team_id=self.team.id)++ self.mock_create_notification.assert_called_once()+ data = self.mock_create_notification.call_args.args[0]+ assert data.target_id == str(self.user.id)+ assert data.team_id == self.team.id++ def test_single_team_mode_bypasses_holdout_flag(self):+ _send_test_digest_notification(email=self.user.email, team_id=self.team.id)++ self.mock_get_flag.assert_not_called()++ def test_single_team_email_lookup_is_case_insensitive(self):+ _send_test_digest_notification(email=self.user.email.upper(), team_id=self.team.id)++ self.mock_create_notification.assert_called_once()++ def test_raises_when_email_has_no_user(self):+ with self.assertRaises(ValueError) as cm:+ _send_test_digest_notification(email="[email protected]", team_id=self.team.id)+ assert "No active user found" in str(cm.exception)+ self.mock_create_notification.assert_not_called()++ def test_raises_when_team_not_found(self):+ with self.assertRaises(ValueError) as cm:+ _send_test_digest_notification(email=self.user.email, team_id=999_999)+ assert "Team 999999 not found" in str(cm.exception)+ self.mock_create_notification.assert_not_called()++ def test_raises_when_user_not_in_teams_org(self):+ other_org = Organization.objects.create(name="Other org")+ other_team = Team.objects.create(organization=other_org, name="Other team")+ with self.assertRaises(PermissionError) as cm:+ _send_test_digest_notification(email=self.user.email, team_id=other_team.id)+ assert "is not a member of the organization" in str(cm.exception)+ self.mock_create_notification.assert_not_called()++ def test_raises_when_delivery_not_completed(self):+ self.mock_create_notification.return_value = None+ with self.assertRaises(RuntimeError) as cm:+ _send_test_digest_notification(email=self.user.email, team_id=self.team.id)+ assert "not delivered" in str(cm.exception)++ def test_full_user_mode_sends_one_notification_per_org(self):+ other_org = Organization.objects.create(name="Other org")+ Team.objects.create(organization=other_org, name="Other team")+ OrganizationMembership.objects.create(+ organization=other_org, user=self.user, level=OrganizationMembership.Level.MEMBER+ )++ self.mock_create_notification.side_effect = lambda data: _make_notification_event()++ _send_test_digest_notification(email=self.user.email)++ assert self.mock_create_notification.call_count == 2++ def test_full_user_mode_raises_when_no_memberships(self):+ self.organization_membership.delete()+ with self.assertRaises(ValueError) as cm:+ _send_test_digest_notification(email=self.user.email)+ assert "no organization memberships" in str(cm.exception)+ self.mock_create_notification.assert_not_called()++ def test_full_user_mode_raises_when_nothing_delivered(self):+ self.mock_create_notification.return_value = None+ with self.assertRaises(RuntimeError) as cm:+ _send_test_digest_notification(email=self.user.email)+ assert "No test digest notifications delivered" in str(cm.exception)diff --git a/products/web_analytics/backend/test/test_digest_notification_workflows.py b/products/web_analytics/backend/test/test_digest_notification_workflows.pynew file mode 100644index 000000000000..e0f20040bb4d--- /dev/null+++ b/products/web_analytics/backend/test/test_digest_notification_workflows.py@@ -0,0 +1,314 @@+import uuid+import asyncio+import dataclasses++import pytest++import temporalio.worker+from temporalio import activity+from temporalio.testing import WorkflowEnvironment+from temporalio.worker import Worker++from products.web_analytics.backend.temporal.digest_notification.types import (+ WA_DIGEST_NOTIF_THRESHOLD_EXCEEDED_TYPE,+ DigestBatchInput,+ DigestBatchResult,+ OrgBatchPageInput,+ OrgBatchPageResult,+ WADigestNotificationInput,+)+from products.web_analytics.backend.temporal.digest_notification.workflows import WADigestNotificationWorkflow+++def _batch_page(batches: list[list[str]], cursor: str | None = None) -> OrgBatchPageResult:+ return OrgBatchPageResult(batches=batches, cursor=cursor)+++async def test_no_batches_returns_zeroed_summary() -> None:+ @activity.defn(name="wa-digest-notif-get-org-batch-page")+ async def _get_batch_page(input: OrgBatchPageInput) -> OrgBatchPageResult:+ return _batch_page([])++ @activity.defn(name="wa-digest-notif-run-batch")+ async def _run_batch(input: DigestBatchInput) -> DigestBatchResult:+ raise AssertionError("should not be called when there are no batches")++ task_queue = str(uuid.uuid4())+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue=task_queue,+ workflows=[WADigestNotificationWorkflow],+ activities=[_get_batch_page, _run_batch],+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),+ ):+ result = await env.client.execute_workflow(+ WADigestNotificationWorkflow.run,+ WADigestNotificationInput(dry_run=True),+ id=str(uuid.uuid4()),+ task_queue=task_queue,+ )++ assert result["orgs"] == 0+ assert result["batches"] == 0+ assert result["notifications_sent"] == 0+ assert result["control_exposed"] == 0+ assert result["failed"] == 0+++async def test_aggregates_totals_across_batches() -> None:+ batches_input = [["org-a", "org-b"], ["org-c"]]++ @activity.defn(name="wa-digest-notif-get-org-batch-page")+ async def _get_batch_page(input: OrgBatchPageInput) -> OrgBatchPageResult:+ return _batch_page(batches_input)++ @activity.defn(name="wa-digest-notif-run-batch")+ async def _run_batch(input: DigestBatchInput) -> DigestBatchResult:+ return DigestBatchResult(+ batch_size=len(input.org_ids),+ orgs_processed=len(input.org_ids),+ notifications_sent=len(input.org_ids) * 2,+ control_exposed=len(input.org_ids),+ failed=0,+ build_duration=0.5,+ send_duration=0.25,+ )++ task_queue = str(uuid.uuid4())+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue=task_queue,+ workflows=[WADigestNotificationWorkflow],+ activities=[_get_batch_page, _run_batch],+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),+ ):+ result = await env.client.execute_workflow(+ WADigestNotificationWorkflow.run,+ WADigestNotificationInput(dry_run=True),+ id=str(uuid.uuid4()),+ task_queue=task_queue,+ )++ assert result["orgs"] == 3+ assert result["batches"] == 2+ assert result["notifications_sent"] == 6 # (2 + 1) * 2+ assert result["control_exposed"] == 3+ assert result["failed_batches"] == 0+++async def test_processes_multiple_discovery_pages() -> None:+ pages_by_cursor = {+ None: _batch_page([["org-a", "org-b"], ["org-c"]], cursor="page-2"),+ "page-2": _batch_page([["org-d"], ["org-e", "org-f"]]),+ }+ seen_cursors: list[str | None] = []+ seen_orgs: set[str] = set()++ @activity.defn(name="wa-digest-notif-get-org-batch-page")+ async def _get_batch_page(input: OrgBatchPageInput) -> OrgBatchPageResult:+ seen_cursors.append(input.cursor)+ return pages_by_cursor[input.cursor]++ @activity.defn(name="wa-digest-notif-run-batch")+ async def _run_batch(input: DigestBatchInput) -> DigestBatchResult:+ seen_orgs.update(input.org_ids)+ return DigestBatchResult(+ batch_size=len(input.org_ids),+ orgs_processed=len(input.org_ids),+ notifications_sent=len(input.org_ids),+ )++ task_queue = str(uuid.uuid4())+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue=task_queue,+ workflows=[WADigestNotificationWorkflow],+ activities=[_get_batch_page, _run_batch],+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),+ ):+ result = await env.client.execute_workflow(+ WADigestNotificationWorkflow.run,+ WADigestNotificationInput(dry_run=True),+ id=str(uuid.uuid4()),+ task_queue=task_queue,+ )++ assert seen_cursors == [None, "page-2"]+ assert seen_orgs == {"org-a", "org-b", "org-c", "org-d", "org-e", "org-f"}+ assert result["orgs"] == 6+ assert result["batches"] == 4+ assert result["notifications_sent"] == 6+++class _ConcurrencyTracker:+ in_flight: int = 0+ max_in_flight: int = 0+ seen_orgs: set[str] = dataclasses.field(default_factory=set)++[email protected]("org_count,batch_size,max_concurrent", [(50, 5, 4), (200, 25, 8)])+async def test_respects_concurrency_cap(org_count: int, batch_size: int, max_concurrent: int) -> None:+ org_ids = [f"org-{i}" for i in range(org_count)]+ expected_batches = [org_ids[i : i + batch_size] for i in range(0, org_count, batch_size)]++ tracker = _ConcurrencyTracker()+ state_lock = asyncio.Lock()++ @activity.defn(name="wa-digest-notif-get-org-batch-page")+ async def _get_batch_page(input: OrgBatchPageInput) -> OrgBatchPageResult:+ return _batch_page(expected_batches)++ @activity.defn(name="wa-digest-notif-run-batch")+ async def _run_batch(input: DigestBatchInput) -> DigestBatchResult:+ async with state_lock:+ tracker.in_flight += 1+ tracker.max_in_flight = max(tracker.max_in_flight, tracker.in_flight)+ tracker.seen_orgs.update(input.org_ids)+ try:+ await asyncio.sleep(0.01)+ finally:+ async with state_lock:+ tracker.in_flight -= 1+ return DigestBatchResult(batch_size=len(input.org_ids), orgs_processed=len(input.org_ids))++ task_queue = str(uuid.uuid4())+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue=task_queue,+ workflows=[WADigestNotificationWorkflow],+ activities=[_get_batch_page, _run_batch],+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),+ max_concurrent_activities=org_count,+ ):+ await env.client.execute_workflow(+ WADigestNotificationWorkflow.run,+ WADigestNotificationInput(dry_run=True, batch_size=batch_size, max_concurrent=max_concurrent),+ id=str(uuid.uuid4()),+ task_queue=task_queue,+ )++ assert tracker.seen_orgs == set(org_ids)+ assert tracker.max_in_flight <= max_concurrent, (+ f"workflow scheduled {tracker.max_in_flight} batches concurrently "+ f"but max_concurrent={max_concurrent} — semaphore fan-out guard is missing"+ )+++async def test_isolates_failing_batch() -> None:+ batches_input = [["org-a", "org-b"], ["org-c"]]++ @activity.defn(name="wa-digest-notif-get-org-batch-page")+ async def _get_batch_page(input: OrgBatchPageInput) -> OrgBatchPageResult:+ return _batch_page(batches_input)++ @activity.defn(name="wa-digest-notif-run-batch")+ async def _run_batch(input: DigestBatchInput) -> DigestBatchResult:+ if "org-c" in input.org_ids:+ raise RuntimeError("batch blew up")+ return DigestBatchResult(+ batch_size=len(input.org_ids),+ orgs_processed=len(input.org_ids),+ notifications_sent=len(input.org_ids),+ )++ task_queue = str(uuid.uuid4())+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue=task_queue,+ workflows=[WADigestNotificationWorkflow],+ activities=[_get_batch_page, _run_batch],+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),+ ):+ result = await env.client.execute_workflow(+ WADigestNotificationWorkflow.run,+ WADigestNotificationInput(dry_run=True, failure_threshold=0.5),+ id=str(uuid.uuid4()),+ task_queue=task_queue,+ )++ assert result["failed_batches"] == 1+ assert result["notifications_sent"] == 2+++async def test_does_not_raise_when_only_skipped() -> None:+ org_ids = [f"org-{i}" for i in range(20)]+ batches = [org_ids]++ @activity.defn(name="wa-digest-notif-get-org-batch-page")+ async def _get_batch_page(input: OrgBatchPageInput) -> OrgBatchPageResult:+ return _batch_page(batches)++ @activity.defn(name="wa-digest-notif-run-batch")+ async def _run_batch(input: DigestBatchInput) -> DigestBatchResult:+ return DigestBatchResult(batch_size=len(input.org_ids), orgs_skipped=len(input.org_ids))++ task_queue = str(uuid.uuid4())+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue=task_queue,+ workflows=[WADigestNotificationWorkflow],+ activities=[_get_batch_page, _run_batch],+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),+ ):+ result = await env.client.execute_workflow(+ WADigestNotificationWorkflow.run,+ WADigestNotificationInput(dry_run=True),+ id=str(uuid.uuid4()),+ task_queue=task_queue,+ )++ assert result["orgs"] == 20+ assert result["notifications_sent"] == 0+++async def test_threshold_exceeded_raises_application_error() -> None:+ org_ids = [f"org-{i}" for i in range(20)]+ batches = [org_ids]++ @activity.defn(name="wa-digest-notif-get-org-batch-page")+ async def _get_batch_page(input: OrgBatchPageInput) -> OrgBatchPageResult:+ return _batch_page(batches)++ @activity.defn(name="wa-digest-notif-run-batch")+ async def _run_batch(input: DigestBatchInput) -> DigestBatchResult:+ return DigestBatchResult(+ batch_size=len(input.org_ids),+ orgs_processed=len(input.org_ids) // 2,+ orgs_failed=len(input.org_ids) // 2,+ )++ task_queue = str(uuid.uuid4())+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue=task_queue,+ workflows=[WADigestNotificationWorkflow],+ activities=[_get_batch_page, _run_batch],+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),+ ):+ with pytest.raises(Exception) as exc_info:+ await env.client.execute_workflow(+ WADigestNotificationWorkflow.run,+ WADigestNotificationInput(dry_run=True),+ id=str(uuid.uuid4()),+ task_queue=task_queue,+ )++ cause = exc_info.value.__cause__+ assert cause is not None and getattr(cause, "type", None) == WA_DIGEST_NOTIF_THRESHOLD_EXCEEDED_TYPE, (+ f"Expected ApplicationError type={WA_DIGEST_NOTIF_THRESHOLD_EXCEEDED_TYPE}, got {type(cause).__name__}: {cause}"+ )diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex b49c5f9fc41d..4eb96d18ea51 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -24273,6 +24273,12 @@ export namespace Schemas {_create_in_folder?: string;}+ /**+ * Optional structured payload for rich client-side rendering, specific to the notification type. For `web_analytics_digest`, holds the weekly metrics (visitors, pageviews, sessions, bounce rate, session duration with week-over-week change), top pages, and top sources used to render the digest card.+ * @nullable+ */+ export type NotificationEventMetadata = { [key: string]: unknown } | null;+/*** * `replay` - REPLAY* * `notebook` - NOTEBOOK@@ -24319,6 +24325,11 @@ export namespace Schemas {source_type: NotificationEventSourceTypeEnum | null;/** @nullable */source_id: string | null;+ /**+ * Optional structured payload for rich client-side rendering, specific to the notification type. For `web_analytics_digest`, holds the weekly metrics (visitors, pageviews, sessions, bounce rate, session duration with week-over-week change), top pages, and top sources used to render the digest card.+ * @nullable+ */+ metadata?: NotificationEventMetadata;created_at: string;}diff --git a/tach.toml b/tach.tomlindex 57c55c6f05cc..a78029e954a0 100644--- a/tach.toml+++ b/tach.toml@@ -640,6 +640,7 @@ depends_on = ["posthog","products.actions","products.analytics_platform",+ "products.notifications",]layer = "modules"