:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(web-analytics): stop failed digest queries from reporting zero traffic (#99875)
Jordan Mryyan3e0bb2abc729
diff --git a/frontend/src/scenes/web-analytics/recap/WebAnalyticsRecapScene.stories.tsx b/frontend/src/scenes/web-analytics/recap/WebAnalyticsRecapScene.stories.tsxindex 6ebe9105ea1e..8da4f3dd88ae 100644--- a/frontend/src/scenes/web-analytics/recap/WebAnalyticsRecapScene.stories.tsx+++ b/frontend/src/scenes/web-analytics/recap/WebAnalyticsRecapScene.stories.tsx@@ -95,3 +95,14 @@ export default metaexport function WeeklyRecap(): JSX.Element {return <App />}++export function LoadFailed(): JSX.Element {+ return <App />+}+LoadFailed.decorators = [+ mswDecorator({+ get: {+ '/api/projects/:team_id/web_analytics/recap/': () => [500, { detail: 'Query timed out' }],+ },+ }),+]diff --git a/frontend/src/scenes/web-analytics/recap/WebAnalyticsRecapScene.tsx b/frontend/src/scenes/web-analytics/recap/WebAnalyticsRecapScene.tsxindex 429e846d678c..5440be329e98 100644--- a/frontend/src/scenes/web-analytics/recap/WebAnalyticsRecapScene.tsx+++ b/frontend/src/scenes/web-analytics/recap/WebAnalyticsRecapScene.tsx@@ -143,11 +143,33 @@ function LeaderboardRow({)}+function RecapPlaceholder({+ title,+ description,+ action,+ icon,+}: {+ title: string+ description: string+ action: React.ReactNode+ icon?: React.ReactNode+}): JSX.Element {+ return (+ <div className="flex flex-col items-center justify-center h-full gap-2 text-center px-4">+ {icon}+ <h2>{title}</h2>+ <p className="text-secondary max-w-md">{description}</p>+ {action}+ </div>+ )+}+export function WebAnalyticsRecapScene(): JSX.Element {const { featureFlags } = useValues(featureFlagLogic)- const { recap: loadedRecap, recapLoading } = useValues(webAnalyticsRecapLogic)+ const { recap: loadedRecap, recapLoading, recapLoadFailed } = useValues(webAnalyticsRecapLogic)const recap = loadedRecap as WebAnalyticsRecapResponseApi | nullconst {+ loadRecap,recordReachedEnd,recordCtaClicked,copyRecapLink,@@ -200,18 +222,37 @@ export function WebAnalyticsRecapScene(): JSX.Element {)}+ if (recapLoadFailed && !recap) {+ return (+ <RecapPlaceholder+ title="Couldn't load your recap"+ description="Something went wrong while building this recap. Try again, and if it keeps happening contact support."+ action={+ <LemonButton+ type="primary"+ loading={recapLoading}+ onClick={() => loadRecap()}+ data-attr="web-analytics-recap-retry"+ >+ Try again+ </LemonButton>+ }+ />+ )+ }+if (!recap) {return (- <div className="flex flex-col items-center justify-center h-full gap-2 text-center px-4">- <span className="text-2xl">🦔</span>- <h2>Your recap isn't ready yet</h2>- <p className="text-secondary max-w-md">- We couldn't build a recap for this project right now. Once there's some traffic, check back here.- </p>- <LemonButton type="primary" onClick={() => goToWebAnalytics('go_to_web_analytics')}>- Go to web analytics- </LemonButton>- </div>+ <RecapPlaceholder+ icon={<span className="text-2xl">🦔</span>}+ title="Your recap isn't ready yet"+ description="We couldn't build a recap for this project right now. Once there's some traffic, check back here."+ action={+ <LemonButton type="primary" onClick={() => goToWebAnalytics('go_to_web_analytics')}>+ Go to web analytics+ </LemonButton>+ }+ />)}diff --git a/frontend/src/scenes/web-analytics/recap/webAnalyticsRecapLogic.test.ts b/frontend/src/scenes/web-analytics/recap/webAnalyticsRecapLogic.test.tsindex b2d95ffb0d72..b3d72409e0ea 100644--- a/frontend/src/scenes/web-analytics/recap/webAnalyticsRecapLogic.test.ts+++ b/frontend/src/scenes/web-analytics/recap/webAnalyticsRecapLogic.test.ts@@ -91,6 +91,23 @@ describe('webAnalyticsRecapLogic', () => {)})+ it('keeps a failed load distinct from an empty recap until a retry succeeds', async () => {+ mockRecap.mockRejectedValueOnce(new Error('Query timed out'))+ logic = webAnalyticsRecapLogic()+ logic.mount()++ await expectLogic(logic)+ .toDispatchActions(['markRecapLoadFailed', 'loadRecapSuccess'])+ .toMatchValues({ recap: null, recapLoadFailed: true, recapLoading: false })++ mockRecap.mockResolvedValue(makeRecap())+ logic.actions.loadRecap()++ await expectLogic(logic)+ .toDispatchActions(['loadRecap', 'loadRecapSuccess'])+ .toMatchValues({ recapLoadFailed: false, recap: expect.objectContaining({ project_name: 'Test' }) })+ })+it('copies the recap link and records the share', async () => {mockRecap.mockResolvedValue(makeRecap())logic = webAnalyticsRecapLogic()diff --git a/frontend/src/scenes/web-analytics/recap/webAnalyticsRecapLogic.ts b/frontend/src/scenes/web-analytics/recap/webAnalyticsRecapLogic.tsindex 46d4f2284402..79283358dbbb 100644--- a/frontend/src/scenes/web-analytics/recap/webAnalyticsRecapLogic.ts+++ b/frontend/src/scenes/web-analytics/recap/webAnalyticsRecapLogic.ts@@ -1,4 +1,4 @@-import { MakeLogicType, actions, afterMount, connect, kea, listeners, path } from 'kea'+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers } from 'kea'import { loaders } from 'kea-loaders'import { router } from 'kea-router'import posthog from 'posthog-js'@@ -65,6 +65,7 @@ function buildEmailCopy(recap: WebAnalyticsRecapResponseApi): string {export interface webAnalyticsRecapLogicValues {currentProjectId: number | null // projectLogicrecap: WebAnalyticsRecapResponseApi | null+ recapLoadFailed: booleanrecapLoading: boolean}@@ -97,6 +98,9 @@ export interface webAnalyticsRecapLogicActions {recap: WebAnalyticsRecapResponseApi | nullpayload?: any}+ markRecapLoadFailed: () => {+ value: true+ }recordButtonClicked: (button: RecapButton) => {button: RecapButton}@@ -131,8 +135,9 @@ export const webAnalyticsRecapLogic = kea<webAnalyticsRecapLogicType>([copyRecapForSlack: true,copyRecapForEmail: true,goToWebAnalytics: (cta: Extract<RecapCta, 'view_dashboard' | 'go_to_web_analytics'>) => ({ cta }),+ markRecapLoadFailed: true,}),- loaders(({ values }) => ({+ loaders(({ values, actions }) => ({recap: [null as WebAnalyticsRecapResponseApi | null,{@@ -141,11 +146,25 @@ export const webAnalyticsRecapLogic = kea<webAnalyticsRecapLogicType>([if (projectId == null) {return null}- return await webAnalyticsRecap(String(projectId), { days: RECAP_DAYS })+ try {+ return await webAnalyticsRecap(String(projectId), { days: RECAP_DAYS })+ } catch {+ actions.markRecapLoadFailed()+ return null+ }},},],})),+ reducers({+ recapLoadFailed: [+ false,+ {+ loadRecap: () => false,+ markRecapLoadFailed: () => true,+ },+ ],+ }),listeners(({ values, actions }) => {const recapProperties = (): RecapEventProperties => {const recap = values.recapdiff --git a/posthog/templates/email/web_analytics_weekly_digest.html b/products/web_analytics/backend/templates/email/web_analytics_weekly_digest.htmlsimilarity index 94%rename from posthog/templates/email/web_analytics_weekly_digest.htmlrename to products/web_analytics/backend/templates/email/web_analytics_weekly_digest.htmlindex 3cc28b9de370..9a542041e566 100644--- a/posthog/templates/email/web_analytics_weekly_digest.html+++ b/products/web_analytics/backend/templates/email/web_analytics_weekly_digest.html@@ -312,7 +312,7 @@</table></div>{% endfor %}- {% if disabled_project_names %}+ {% if disabled_project_names or unavailable_project_names %}<table width="100%"cellpadding="0"cellspacing="0"@@ -334,15 +334,28 @@border-radius: 8px;padding: 20px;margin-bottom: 16px">- <p style="margin: 0 0 8px 0; font-size: 0.9em; color: #6b7280;">This report did not include the following projects because they are disabled in your settings:</p>- <ul style="margin: 0;- padding-left: 20px;- color: #6b7280;- font-size: 0.9em">- {% for name in disabled_project_names %}- <li>{{ name }}</li>- {% endfor %}- </ul>+ {% if disabled_project_names %}+ <p style="margin: 0 0 8px 0; font-size: 0.9em; color: #6b7280;">This report did not include the following projects because they are disabled in your settings:</p>+ <ul style="margin: 0 0 8px 0;+ padding-left: 20px;+ color: #6b7280;+ font-size: 0.9em">+ {% for name in disabled_project_names %}+ <li>{{ name }}</li>+ {% endfor %}+ </ul>+ {% endif %}+ {% if unavailable_project_names %}+ <p style="margin: 0 0 8px 0; font-size: 0.9em; color: #6b7280;">We couldn't load data for the following projects this week. Their numbers are available on the dashboard:</p>+ <ul style="margin: 0;+ padding-left: 20px;+ color: #6b7280;+ font-size: 0.9em">+ {% for name in unavailable_project_names %}+ <li>{{ name }}</li>+ {% endfor %}+ </ul>+ {% endif %}</div>{% endif %}<div style="margin-bottom: 16px; text-align: center;">diff --git a/products/web_analytics/backend/temporal/digest_common.py b/products/web_analytics/backend/temporal/digest_common.pyindex b7c532bfd067..0d0d6a2c25ac 100644--- a/products/web_analytics/backend/temporal/digest_common.py+++ b/products/web_analytics/backend/temporal/digest_common.py@@ -1,4 +1,6 @@+import dataclassesfrom datetime import timedelta+from typing import Selffrom django.db.models import QuerySet@@ -14,6 +16,51 @@ ACTIVITY_RETRY_POLICY = common.RetryPolicy()[email protected](frozen=True)+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)++[email protected](frozen=False)+class DigestBatchTotals:+ """`failure_rate` excludes `orgs_skipped`: digest skips are benign+ pre-processing exclusions (no targeted members, no teams, race-deleted+ org), not detector errors, so they shouldn't trip the workflow's threshold+ alarm.+ """++ batch_size: int = 0+ orgs_processed: int = 0+ orgs_skipped: int = 0+ orgs_failed: int = 0+ teams_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: Self) -> Self:+ for f in dataclasses.fields(self):+ setattr(self, f.name, getattr(self, f.name) + getattr(other, f.name))+ return self++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 0page = items[start : start + page_size]diff --git a/products/web_analytics/backend/temporal/digest_notification/activities.py b/products/web_analytics/backend/temporal/digest_notification/activities.pyindex a01b123eab2a..ba2448673774 100644--- a/products/web_analytics/backend/temporal/digest_notification/activities.py+++ b/products/web_analytics/backend/temporal/digest_notification/activities.py@@ -27,17 +27,16 @@ from products.notifications.backend.facade.api import (TargetType,create_notification,)-from products.web_analytics.backend.temporal.digest_common import paginate_index, paginate_keyset+from products.web_analytics.backend import weekly_digest+from products.web_analytics.backend.temporal.digest_common import OrgBatchPageResult, paginate_index, paginate_keysetfrom 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_digestlogger = structlog.get_logger(__name__)@@ -273,17 +272,6 @@ def _expose_and_notify_user(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()@@ -304,8 +292,17 @@ def _build_and_send_for_org(org_id: str, flag_key: str, dry_run: bool = False) -counts.skipped_reason = "no_teams"return counts- team_digest_data, counts.team_count, counts.build_duration = _build_team_digest_data(org)+ build_start = time.monotonic()+ build = weekly_digest.build_team_digests(Team.objects.filter(organization_id=org.id))+ team_digest_data = {+ team_id: digest for team_id, digest in build.digests.items() if (digest["visitors"]["current"] or 0) > 0+ }+ counts.build_duration = time.monotonic() - build_start+ counts.team_count = len(team_digest_data)+ counts.teams_failed = len(build.failed_teams)if not team_digest_data:+ if build.failed_teams:+ raise RuntimeError("WA digest notification: no team with web analytics data could be built")counts.skipped_reason = "no_wa_data"return counts@@ -350,6 +347,7 @@ def _build_and_send_for_org(org_id: str, flag_key: str, dry_run: bool = False) -skipped_no_data=counts.skipped_no_data,failed=counts.failed,team_count=counts.team_count,+ teams_failed=counts.teams_failed,)return counts@@ -383,6 +381,7 @@ def _run_wa_digest_notification_batch(input: DigestBatchInput) -> DigestBatchRestotals.control_exposed += org_counts.controltotals.skipped_no_data += org_counts.skipped_no_datatotals.failed += org_counts.failed+ totals.teams_failed += org_counts.teams_failedtotals.build_duration += org_counts.build_durationtotals.send_duration += org_counts.send_duration@@ -441,7 +440,7 @@ def _send_test_digest_notification(email: str, team_id: int | None = None) -> Noif not membership:raise PermissionError(f"User {email} is not a member of the organization that owns team {team_id}")- digest = build_team_digest(team)+ digest = weekly_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}")@@ -474,7 +473,9 @@ def _send_test_digest_notification(email: str, team_id: int | None = None) -> Nosent_count = 0for 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)}+ team_digest_data = {+ t.id: weekly_digest.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:continuediff --git a/products/web_analytics/backend/temporal/digest_notification/types.py b/products/web_analytics/backend/temporal/digest_notification/types.pyindex 6662dc6354bb..f47599758a45 100644--- a/products/web_analytics/backend/temporal/digest_notification/types.py+++ b/products/web_analytics/backend/temporal/digest_notification/types.py@@ -1,6 +1,8 @@import dataclassesfrom enum import StrEnum+from products.web_analytics.backend.temporal.digest_common import DigestBatchTotals+class NotificationDigestOutcome(StrEnum):SENT = "sent"@@ -27,27 +29,14 @@ class OrgBatchPageInput: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)--[email protected](frozen=False)class OrgDigestNotificationCounts:sent: int = 0control: int = 0skipped_no_data: int = 0failed: int = 0team_count: int = 0+ teams_failed: int = 0build_duration: float = 0.0send_duration: float = 0.0skipped_reason: str | None = None@@ -60,32 +49,12 @@ class DigestBatchInput: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[email protected](frozen=False)+class DigestBatchResult(DigestBatchTotals):notifications_sent: int = 0control_exposed: int = 0skipped_no_data: int = 0failed: 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@dataclasses.dataclassdiff --git a/products/web_analytics/backend/temporal/digest_notification/workflows.py b/products/web_analytics/backend/temporal/digest_notification/workflows.pyindex 54078de69a59..71ed9e00b2b9 100644--- a/products/web_analytics/backend/temporal/digest_notification/workflows.py+++ b/products/web_analytics/backend/temporal/digest_notification/workflows.py@@ -115,6 +115,7 @@ class WADigestNotificationWorkflow(PostHogWorkflow):"notifications_sent": totals.notifications_sent,"control_exposed": totals.control_exposed,"failed": totals.failed,+ "teams_failed": totals.teams_failed,"cumulative_duration_seconds": totals.total_duration,}diff --git a/products/web_analytics/backend/temporal/weekly_digest/activities.py b/products/web_analytics/backend/temporal/weekly_digest/activities.pyindex a4685bb5c996..0663e624ea95 100644--- a/products/web_analytics/backend/temporal/weekly_digest/activities.py+++ b/products/web_analytics/backend/temporal/weekly_digest/activities.py@@ -1,4 +1,5 @@import time+from collections.abc import Sequencefrom datetime import datetime, timedeltafrom itertools import batched@@ -26,20 +27,19 @@ 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 import weekly_digestfrom products.web_analytics.backend.recap import recap_url_for_team-from products.web_analytics.backend.temporal.digest_common import paginate_index, paginate_keyset+from products.web_analytics.backend.temporal.digest_common import OrgBatchPageResult, paginate_index, paginate_keysetfrom products.web_analytics.backend.temporal.weekly_digest.types import (WA_DIGEST_EMAIL_UNAVAILABLE_TYPE,DigestBatchInput,DigestBatchResult,DigestOutcome,OrgBatchPageInput,- OrgBatchPageResult,OrgDigestCounts,SendTestDigestInput,WAWeeklyDigestInput,)-from products.web_analytics.backend.weekly_digest import auto_select_project_for_user, build_team_digestlogger = structlog.get_logger(__name__)@@ -121,6 +121,7 @@ def _send_digest_for_user(date_suffix: str,dry_run: bool = False,test: bool = False,+ failed_teams: Sequence[Team] = (),) -> DigestOutcome:"""`test=True` bypasses notification opt-ins and forces a uniquecampaign_key so dedupe never blocks delivery. Team-access checks are always@@ -130,22 +131,25 @@ def _send_digest_for_user(return DigestOutcome.SKIPPED_OPTOUTuser_perms = UserPermissions(user)- accessible_team_data: 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_data[team_id] = data+ def has_access(team: Team) -> bool:+ return user_perms.team(team).effective_membership_level_for_parent_membership(org, membership) is not None++ def is_enabled(team_id: int) -> bool:+ return test or should_send_notification(user, NotificationSetting.WEB_ANALYTICS_WEEKLY_DIGEST.value, team_id)++ accessible_team_data = {team_id: data for team_id, data in team_digest_data.items() if has_access(data["team"])}if not accessible_team_data:return DigestOutcome.SKIPPED_NO_DATA- if auto_select_project_for_user(user, accessible_team_data):+ accessible_failed_teams = [team for team in failed_teams if has_access(team)]+ if not accessible_failed_teams and weekly_digest.auto_select_project_for_user(user, accessible_team_data):user.refresh_from_db(fields=["partial_notification_settings"])user_team_sections = []disabled_team_names = []for team_id, data in accessible_team_data.items():- if test or should_send_notification(user, NotificationSetting.WEB_ANALYTICS_WEEKLY_DIGEST.value, team_id):+ if is_enabled(team_id):user_team_sections.append(data)else:disabled_team_names.append(data["team"].name)@@ -162,6 +166,8 @@ def _send_digest_for_user(if dry_run:return DigestOutcome.DRY_RUN+ unavailable_team_names = [team.name for team in accessible_failed_teams if is_enabled(team.id)]+# When the recap experience is enabled for this user, the email CTA points at the recap page.recap_enabled = _is_user_recap_enabled(user, str(org.id))if recap_enabled:@@ -179,6 +185,7 @@ def _send_digest_for_user("organization": org,"project_sections": user_team_sections,"disabled_project_names": disabled_team_names,+ "unavailable_project_names": unavailable_team_names,"recap_enabled": recap_enabled,"settings_url": f"{settings.SITE_URL}/settings/user-notifications?highlight=wa-weekly-digest",},@@ -255,9 +262,10 @@ def _build_and_send_for_org(org_id: str, dry_run: bool = False) -> OrgDigestCounreturn countsbuild_start = time.monotonic()- team_digest_data: dict[int, dict] = {team.id: build_team_digest(team) for team in all_org_teams}+ build = weekly_digest.build_team_digests(all_org_teams)counts.build_duration = time.monotonic() - build_start- counts.team_count = len(team_digest_data)+ counts.team_count = len(build.digests)+ counts.teams_failed = len(build.failed_teams)date_suffix = timezone.now().strftime("%Y-%W")@@ -267,9 +275,10 @@ def _build_and_send_for_org(org_id: str, dry_run: bool = False) -> OrgDigestCounuser=membership.user,org=org,membership=membership,- team_digest_data=team_digest_data,+ team_digest_data=build.digests,date_suffix=date_suffix,dry_run=dry_run,+ failed_teams=build.failed_teams,)if outcome in (DigestOutcome.SENT, DigestOutcome.DRY_RUN):counts.sent += 1@@ -289,6 +298,7 @@ def _build_and_send_for_org(org_id: str, dry_run: bool = False) -> OrgDigestCounskipped_no_data=counts.skipped_no_data,failed=counts.failed,team_count=counts.team_count,+ teams_failed=counts.teams_failed,)return counts@@ -322,6 +332,7 @@ def _run_wa_digest_batch(input: DigestBatchInput) -> DigestBatchResult:totals.emails_skipped_optout += org_counts.skipped_optouttotals.emails_skipped_no_data += org_counts.skipped_no_datatotals.emails_failed += org_counts.failed+ totals.teams_failed += org_counts.teams_failedtotals.build_duration += org_counts.build_durationtotals.send_duration += org_counts.send_duration@@ -444,7 +455,7 @@ def _send_test_digest(email: str, team_id: int | None = None) -> None:user=user,org=team.organization,membership=membership,- team_digest_data={team.id: build_team_digest(team)},+ team_digest_data={team.id: weekly_digest.build_team_digest(team)},date_suffix=date_suffix,test=True,)@@ -470,7 +481,7 @@ def _send_test_digest(email: str, team_id: int | None = None) -> None:org_teams = list(Team.objects.filter(organization_id=org.id))if not org_teams:continue- team_digest_data = {t.id: build_team_digest(t) for t in org_teams}+ team_digest_data = {t.id: weekly_digest.build_team_digest(t) for t in org_teams}outcome = _send_digest_for_user(user=user,org=org,diff --git a/products/web_analytics/backend/temporal/weekly_digest/types.py b/products/web_analytics/backend/temporal/weekly_digest/types.pyindex eaa2c86c2bf3..b2d56027758c 100644--- a/products/web_analytics/backend/temporal/weekly_digest/types.py+++ b/products/web_analytics/backend/temporal/weekly_digest/types.py@@ -1,6 +1,8 @@import dataclassesfrom enum import StrEnum+from products.web_analytics.backend.temporal.digest_common import DigestBatchTotals+class DigestOutcome(StrEnum):"""Outcome of attempting to send a single digest email to a single user."""@@ -12,7 +14,7 @@ class DigestOutcome(StrEnum):FAILED = "failed"[email protected](frozen=False)class OrgDigestCounts:"""`skipped_reason` is set when the org was skipped before any email attempt(no teams, no targeted members, etc.) — present means the org should be@@ -24,6 +26,7 @@ class OrgDigestCounts:skipped_no_data: int = 0failed: int = 0team_count: int = 0+ teams_failed: int = 0build_duration: float = 0.0send_duration: float = 0.0skipped_reason: str | None = None@@ -46,58 +49,18 @@ class OrgBatchPageInput: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)--@dataclasses.dataclassclass DigestBatchInput:org_ids: list[str]dry_run: bool = False-class DigestBatchResult:- """`failure_rate` excludes `orgs_skipped`: digest skips are benign- pre-processing exclusions (no targeted members, no teams, race-deleted- org), not detector errors, so they shouldn't trip the workflow's threshold- alarm.- """-- batch_size: int = 0- orgs_processed: int = 0- orgs_skipped: int = 0- orgs_failed: int = 0[email protected](frozen=False)+class DigestBatchResult(DigestBatchTotals):emails_sent: int = 0emails_skipped_optout: int = 0emails_skipped_no_data: int = 0emails_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@dataclasses.dataclassdiff --git a/products/web_analytics/backend/temporal/weekly_digest/workflows.py b/products/web_analytics/backend/temporal/weekly_digest/workflows.pyindex 126d5cd70c7a..9a66df2875c6 100644--- a/products/web_analytics/backend/temporal/weekly_digest/workflows.py+++ b/products/web_analytics/backend/temporal/weekly_digest/workflows.py@@ -122,6 +122,7 @@ class WAWeeklyDigestWorkflow(PostHogWorkflow):"failed_batches": failed_batches,"emails_sent": totals.emails_sent,"emails_failed": totals.emails_failed,+ "teams_failed": totals.teams_failed,"cumulative_duration_seconds": totals.total_duration,}diff --git a/products/web_analytics/backend/test/test_digest_notification_activities.py b/products/web_analytics/backend/test/test_digest_notification_activities.pyindex 1cbc97c814f2..4e876eafef98 100644--- a/products/web_analytics/backend/test/test_digest_notification_activities.py+++ b/products/web_analytics/backend/test/test_digest_notification_activities.py@@ -71,7 +71,7 @@ class _DigestNotificationTestBase(APIBaseTest):self.mock_create_notification = self.create_notification_patcher.start()self.build_digest_patcher = patch(- f"{ACTIVITIES}.build_team_digest",+ "products.web_analytics.backend.weekly_digest.build_team_digest",side_effect=lambda team: _make_team_digest(team),)self.mock_build_digest = self.build_digest_patcher.start()@@ -151,6 +151,45 @@ class TestBuildAndSendForOrg(_DigestNotificationTestBase):assert counts.skipped_reason == "no_wa_data"self.mock_create_notification.assert_not_called()+ def test_a_failing_team_is_left_out_and_counted(self):+ broken_team = Team.objects.create(organization=self.organization, name="Broken team")++ def build(team):+ if team.id == broken_team.id:+ raise TimeoutError("Query timed out")+ return _make_team_digest(team)++ self.mock_build_digest.side_effect = build++ counts = _build_and_send_for_org(str(self.organization.id), flag_key="my-flag")++ assert counts.sent == 1+ assert counts.teams_failed == 1+ assert self.mock_create_notification.call_args.args[0].team_id == self.team.id++ def test_raises_instead_of_skipping_when_every_team_fails(self):+ self.mock_build_digest.side_effect = TimeoutError("Query timed out")++ with self.assertRaises(RuntimeError):+ _build_and_send_for_org(str(self.organization.id), flag_key="my-flag")++ self.mock_create_notification.assert_not_called()++ def test_raises_when_the_only_teams_with_data_may_be_the_failed_ones(self):+ broken_team = Team.objects.create(organization=self.organization, name="Broken team")++ def build(team):+ if team.id == broken_team.id:+ raise TimeoutError("Query timed out")+ return _make_team_digest(team, visitors=0)++ self.mock_build_digest.side_effect = build++ with self.assertRaises(RuntimeError):+ _build_and_send_for_org(str(self.organization.id), flag_key="my-flag")++ 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")diff --git a/products/web_analytics/backend/test/test_digest_notification_workflows.py b/products/web_analytics/backend/test/test_digest_notification_workflows.pyindex ec6705c86535..df6689c3d741 100644--- a/products/web_analytics/backend/test/test_digest_notification_workflows.py+++ b/products/web_analytics/backend/test/test_digest_notification_workflows.py@@ -9,12 +9,12 @@ from temporalio import activityfrom temporalio.testing import WorkflowEnvironmentfrom temporalio.worker import Worker+from products.web_analytics.backend.temporal.digest_common import OrgBatchPageResultfrom 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 WADigestNotificationWorkflowdiff --git a/products/web_analytics/backend/test/test_weekly_digest.py b/products/web_analytics/backend/test/test_weekly_digest.pyindex 614e388a7d47..92a78657b115 100644--- a/products/web_analytics/backend/test/test_weekly_digest.py+++ b/products/web_analytics/backend/test/test_weekly_digest.py@@ -1,17 +1,31 @@+from collections.abc import Callablefrom datetime import timedeltaimport time_machinefrom posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person, flush_persons_and_events+from unittest.mock import patch+from django.test import SimpleTestCasefrom django.utils import timezonefrom parameterized import parameterized+from posthog.schema import (+ CacheMissResponse,+ QueryStatus,+ QueryStatusResponse,+ WebGoalsQueryResponse,+ WebOverviewQueryResponse,+ WebStatsTableQueryResponse,+)+from posthog.models import Teamfrom posthog.models.utils import uuid7from products.actions.backend.models.action import Action+from products.web_analytics.backend.hogql_queries.web_goals import NoActionsErrorfrom products.web_analytics.backend.weekly_digest import (+ _default_overview,_format_duration,auto_select_project_for_user,build_team_digest,@@ -23,6 +37,55 @@ from products.web_analytics.backend.weekly_digest import (QUERY_TIMESTAMP = "2025-01-29"+DIGEST_QUERY_CASES = [+ (get_overview_for_team, "WebOverviewQueryRunner", WebOverviewQueryResponse, _default_overview()),+ (get_top_pages, "WebStatsTableQueryRunner", WebStatsTableQueryResponse, []),+ (get_top_sources, "WebStatsTableQueryRunner", WebStatsTableQueryResponse, []),+ (get_goals_for_team, "WebGoalsQueryRunner", WebGoalsQueryResponse, []),+]+++class TestDigestQueryFailures(SimpleTestCase):+ @parameterized.expand(DIGEST_QUERY_CASES)+ def test_query_exceptions_are_not_zero_traffic(+ self, query: Callable[..., object], runner_name: str, *_: object+ ) -> None:+ with patch(f"products.web_analytics.backend.weekly_digest.{runner_name}") as runner:+ runner.return_value.run.side_effect = TimeoutError("Query timed out")+ with self.assertRaises(TimeoutError):+ query(Team(pk=1))++ @parameterized.expand(DIGEST_QUERY_CASES)+ def test_empty_results_are_distinct_from_failed_or_missing_results(+ self, query: Callable[..., object], runner_name: str, response_type: type, expected_empty: object+ ) -> None:+ with patch(f"products.web_analytics.backend.weekly_digest.{runner_name}") as runner:+ for response in [+ CacheMissResponse(),+ QueryStatusResponse(query_status=QueryStatus(id="pending-query", team_id=1, complete=False)),+ response_type(results=[], error="Query failed"),+ ]:+ with self.subTest(response=type(response).__name__):+ runner.return_value.run.return_value = response+ with self.assertRaises(ValueError):+ query(Team(pk=1))++ runner.return_value.run.return_value = response_type(results=[])+ assert query(Team(pk=1)) == expected_empty++ def test_no_configured_actions_is_a_valid_empty_goals_section(self) -> None:+ with patch("products.web_analytics.backend.weekly_digest.WebGoalsQueryRunner") as runner:+ runner.return_value.run.side_effect = NoActionsError()+ assert get_goals_for_team(Team(pk=1)) == []++ def test_an_incomplete_section_stops_digest_construction(self) -> None:+ with (+ patch("products.web_analytics.backend.weekly_digest.get_overview_for_team", return_value={}),+ patch("products.web_analytics.backend.weekly_digest.get_top_pages", side_effect=TimeoutError),+ ):+ with self.assertRaises(TimeoutError):+ build_team_digest(Team(pk=1))+def _create_pageview(team,diff --git a/products/web_analytics/backend/test/test_weekly_digest_activities.py b/products/web_analytics/backend/test/test_weekly_digest_activities.pyindex 160076ab995c..833680a79088 100644--- a/products/web_analytics/backend/test/test_weekly_digest_activities.py+++ b/products/web_analytics/backend/test/test_weekly_digest_activities.py@@ -13,6 +13,7 @@ from posthog.models import OrganizationMembership, Team, Userfrom posthog.models.organization import Organizationfrom products.web_analytics.backend.temporal.weekly_digest.activities import (+ _build_and_send_for_org,_get_org_batch_page,_is_user_targeted_for_digest,_run_wa_digest_batch,@@ -228,11 +229,56 @@ class TestSendDigestForUser(_DigestTestBase):assert [s["team"].id for s in sections] == [team_b.id, team_c.id, self.team.id]+class TestBuildAndSendForOrg(_DigestTestBase):+ def setUp(self):+ super().setUp()+ flag_patcher = patch(+ "products.web_analytics.backend.temporal.weekly_digest.activities.posthoganalytics.feature_enabled",+ return_value=True,+ )+ flag_patcher.start()+ self.addCleanup(flag_patcher.stop)+ build_digest_patcher = patch(+ "products.web_analytics.backend.weekly_digest.build_team_digest",+ side_effect=lambda team: _make_team_digest(team),+ )+ self.mock_build_digest = build_digest_patcher.start()+ self.addCleanup(build_digest_patcher.stop)++ def test_a_failing_team_is_left_out_and_disclosed(self):+ broken_team = Team.objects.create(organization=self.organization, name="Broken team")++ def build(team):+ if team.id == broken_team.id:+ raise TimeoutError("Query timed out")+ return _make_team_digest(team)++ self.mock_build_digest.side_effect = build+ counts = _build_and_send_for_org(str(self.organization.id))++ assert counts.sent == 1+ assert counts.team_count == 1+ assert counts.teams_failed == 1+ context = self.mock_email_class.call_args.kwargs["template_context"]+ assert [s["team"].id for s in context["project_sections"]] == [self.team.id]+ assert context["unavailable_project_names"] == ["Broken team"]+ self.user.refresh_from_db()+ assert "web_analytics_weekly_digest_project_enabled" not in (self.user.partial_notification_settings or {})++ def test_raises_when_no_team_section_can_be_built(self):+ self.mock_build_digest.side_effect = TimeoutError("Query timed out")++ with self.assertRaises(RuntimeError):+ _build_and_send_for_org(str(self.organization.id))++ self.mock_email_class.assert_not_called()++class TestSendTestDigestSingleTeamMode(_DigestTestBase):def setUp(self):super().setUp()self.build_digest_patcher = patch(- "products.web_analytics.backend.temporal.weekly_digest.activities.build_team_digest",+ "products.web_analytics.backend.weekly_digest.build_team_digest",side_effect=lambda team: _make_team_digest(team),)self.build_digest_patcher.start()@@ -283,7 +329,7 @@ class TestSendTestDigestFullUserMode(_DigestTestBase):def setUp(self):super().setUp()self.build_digest_patcher = patch(- "products.web_analytics.backend.temporal.weekly_digest.activities.build_team_digest",+ "products.web_analytics.backend.weekly_digest.build_team_digest",side_effect=lambda team: _make_team_digest(team),)self.build_digest_patcher.start()@@ -557,7 +603,7 @@ class TestRunWaDigestBatch(APIBaseTest):return_value=True,),patch(- "products.web_analytics.backend.temporal.weekly_digest.activities.build_team_digest",+ "products.web_analytics.backend.weekly_digest.build_team_digest",side_effect=lambda team: _make_team_digest(team),),patch("products.web_analytics.backend.temporal.weekly_digest.activities.EmailMessage") as mock_email_class,diff --git a/products/web_analytics/backend/test/test_weekly_digest_workflows.py b/products/web_analytics/backend/test/test_weekly_digest_workflows.pyindex edc2b20f3f04..2871e3c9a78b 100644--- a/products/web_analytics/backend/test/test_weekly_digest_workflows.py+++ b/products/web_analytics/backend/test/test_weekly_digest_workflows.py@@ -9,12 +9,12 @@ from temporalio import activityfrom temporalio.testing import WorkflowEnvironmentfrom temporalio.worker import Worker+from products.web_analytics.backend.temporal.digest_common import OrgBatchPageResultfrom products.web_analytics.backend.temporal.weekly_digest.types import (WA_DIGEST_THRESHOLD_EXCEEDED_TYPE,DigestBatchInput,DigestBatchResult,OrgBatchPageInput,- OrgBatchPageResult,WAWeeklyDigestInput,)from products.web_analytics.backend.temporal.weekly_digest.workflows import WAWeeklyDigestWorkflowdiff --git a/products/web_analytics/backend/weekly_digest.py b/products/web_analytics/backend/weekly_digest.pyindex 5db6da2f796a..84c2973f76a3 100644--- a/products/web_analytics/backend/weekly_digest.py+++ b/products/web_analytics/backend/weekly_digest.py@@ -1,20 +1,30 @@+from collections.abc import Iterable+from typing import TypeVar+from django.conf import settingsimport structlogfrom posthog.schema import (+ CacheMissResponse,CompareFilter,DateRange,ProductKey,+ QueryStatusResponse,WebAnalyticsOrderByDirection,WebAnalyticsOrderByFields,WebGoalsQuery,+ WebGoalsQueryResponse,WebOverviewQuery,+ WebOverviewQueryResponse,WebStatsBreakdown,WebStatsTableQuery,+ WebStatsTableQueryResponse,)from posthog.clickhouse.query_tagging import tag_queries+from posthog.dataclasses import frozen+from posthog.exceptions_capture import capture_exceptionfrom posthog.hogql_queries.query_runner import ExecutionModefrom posthog.models import Teamfrom posthog.models.user import User@@ -29,6 +39,17 @@ logger = structlog.get_logger(__name__)DEFAULT_DIGEST_EXECUTION_MODE = ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE+DigestResponse = TypeVar("DigestResponse", WebOverviewQueryResponse, WebStatsTableQueryResponse, WebGoalsQueryResponse)+++def _require_digest_response(+ response: DigestResponse | CacheMissResponse | QueryStatusResponse,+) -> DigestResponse:+ if isinstance(response, CacheMissResponse | QueryStatusResponse) or response.error:+ raise ValueError("Web analytics digest query did not return a successful result")+ return response++def _default_overview() -> dict:return {"visitors": {"current": 0, "previous": None, "change": None},@@ -50,24 +71,16 @@ def get_overview_for_team(tag_queries(product=ProductKey.WEB_ANALYTICS, team_id=team.pk, name="weekly_digest:web_overview")result = _default_overview()- try:- query = WebOverviewQuery(- dateRange=DateRange(date_from=f"-{days}d"),- compareFilter=CompareFilter(compare=compare),- filterTestAccounts=True,- properties=[],- )- runner = WebOverviewQueryRunner(team=team, query=query)- response = runner.run(execution_mode=execution_mode, user=user)- except Exception:- logger.exception("failed to query web overview", team_id=team.pk)- return result-- results = getattr(response, "results", None)- if not results:- return result+ query = WebOverviewQuery(+ dateRange=DateRange(date_from=f"-{days}d"),+ compareFilter=CompareFilter(compare=compare),+ filterTestAccounts=True,+ properties=[],+ )+ runner = WebOverviewQueryRunner(team=team, query=query)+ response = _require_digest_response(runner.run(execution_mode=execution_mode, user=user))- items_by_key = {item.key: item for item in results}+ items_by_key = {item.key: item for item in response.results}for key, output_key, higher_is_better in [("visitors", "visitors", True),@@ -129,6 +142,29 @@ def _format_duration(seconds: float | None) -> str:return f"{minutes}m {secs}s"+def _run_stats_table_query(+ team: Team,+ breakdown_by: WebStatsBreakdown,+ limit: int,+ days: int,+ compare: bool,+ *,+ execution_mode: ExecutionMode,+ user: User | None,+) -> WebStatsTableQueryResponse:+ query = WebStatsTableQuery(+ breakdownBy=breakdown_by,+ dateRange=DateRange(date_from=f"-{days}d"),+ compareFilter=CompareFilter(compare=compare),+ limit=limit,+ orderBy=[WebAnalyticsOrderByFields.VISITORS, WebAnalyticsOrderByDirection.DESC],+ filterTestAccounts=True,+ properties=[],+ )+ runner = WebStatsTableQueryRunner(team=team, query=query)+ return _require_digest_response(runner.run(execution_mode=execution_mode, user=user))++def get_top_pages(team: Team,limit: int = 5,@@ -139,36 +175,19 @@ def get_top_pages(user: User | None = None,) -> list[dict]:tag_queries(product=ProductKey.WEB_ANALYTICS, team_id=team.pk, name="weekly_digest:top_pages")+ response = _run_stats_table_query(+ team, WebStatsBreakdown.PAGE, limit, days, compare, execution_mode=execution_mode, user=user+ )- try:- query = WebStatsTableQuery(- breakdownBy=WebStatsBreakdown.PAGE,- dateRange=DateRange(date_from=f"-{days}d"),- compareFilter=CompareFilter(compare=compare),- limit=limit,- orderBy=[WebAnalyticsOrderByFields.VISITORS, WebAnalyticsOrderByDirection.DESC],- filterTestAccounts=True,- properties=[],- )- runner = WebStatsTableQueryRunner(team=team, query=query)- response = runner.run(execution_mode=execution_mode, user=user)-- results = getattr(response, "results", None)- if not results:- return []-- return [- {- "host": "",- "path": row[0] or "",- "visitors": row[1][0],- "change": compute_week_over_week_change(row[1][0], row[1][1], higher_is_better=True),- }- for row in results- ]- except Exception:- logger.exception("failed to query top pages", team_id=team.pk)- return []+ return [+ {+ "host": "",+ "path": row[0] or "",+ "visitors": row[1][0],+ "change": compute_week_over_week_change(row[1][0], row[1][1], higher_is_better=True),+ }+ for row in response.results+ ]def get_top_sources(@@ -181,36 +200,19 @@ def get_top_sources(user: User | None = None,) -> list[dict]:tag_queries(product=ProductKey.WEB_ANALYTICS, team_id=team.pk, name="weekly_digest:top_sources")+ response = _run_stats_table_query(+ team, WebStatsBreakdown.INITIAL_REFERRING_DOMAIN, limit, days, compare, execution_mode=execution_mode, user=user+ )- try:- query = WebStatsTableQuery(- breakdownBy=WebStatsBreakdown.INITIAL_REFERRING_DOMAIN,- dateRange=DateRange(date_from=f"-{days}d"),- compareFilter=CompareFilter(compare=compare),- limit=limit,- orderBy=[WebAnalyticsOrderByFields.VISITORS, WebAnalyticsOrderByDirection.DESC],- filterTestAccounts=True,- properties=[],- )- runner = WebStatsTableQueryRunner(team=team, query=query)- response = runner.run(execution_mode=execution_mode, user=user)-- results = getattr(response, "results", None)- if not results:- return []-- return [- {- "name": row[0] or "",- "visitors": row[1][0],- "change": compute_week_over_week_change(row[1][0], row[1][1], higher_is_better=True),- }- for row in results- if row[0]- ]- except Exception:- logger.exception("failed to query top sources", team_id=team.pk)- return []+ return [+ {+ "name": row[0] or "",+ "visitors": row[1][0],+ "change": compute_week_over_week_change(row[1][0], row[1][1], higher_is_better=True),+ }+ for row in response.results+ if row[0]+ ]def get_goals_for_team(@@ -231,15 +233,12 @@ def get_goals_for_team(properties=[],)runner = WebGoalsQueryRunner(team=team, query=query)- response = runner.run(execution_mode=execution_mode, user=user)+ response = _require_digest_response(runner.run(execution_mode=execution_mode, user=user))except NoActionsError:return []- except Exception:- logger.exception("failed to query goals", team_id=team.pk)- return []results = []- for row in (getattr(response, "results", None) or [])[:limit]:+ for row in response.results[:limit]:name, _converting_users, (total_current, total_prev), _conversion_rate = rowresults.append({@@ -278,6 +277,27 @@ def build_team_digest(}+@frozen+class TeamDigestBuild:+ digests: dict[int, dict]+ failed_teams: list[Team]+++def build_team_digests(teams: Iterable[Team]) -> TeamDigestBuild:+ digests: dict[int, dict] = {}+ failed_teams: list[Team] = []+ for team in teams:+ try:+ digests[team.id] = build_team_digest(team)+ except Exception as e:+ logger.warning("WA digest could not build a team section", team_id=team.id, error=str(e))+ capture_exception(e, {"team_id": team.id})+ failed_teams.append(team)+ if failed_teams and not digests:+ raise RuntimeError("WA digest: no team section could be built")+ return TeamDigestBuild(digests=digests, failed_teams=failed_teams)++def auto_select_project_for_user(user: User, team_traffic_data: dict[int, dict]) -> bool:"""For first-time users who have no WA digest project settings, auto-select the project with the most visitors.