: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
chore(web-analytics): Refactor WA digest orchestration (#58038)
Jordan Mryyan7a2931f0b940
diff --git a/posthog/temporal/common/rollout.py b/posthog/temporal/common/rollout.pynew file mode 100644index 000000000000..09eceb62566f--- /dev/null+++ b/posthog/temporal/common/rollout.py@@ -0,0 +1,26 @@+from __future__ import annotations++import math+import hashlib+from typing import TypeVar++T = TypeVar("T")+++def _rollout_rank(value: object) -> int:+ digest = hashlib.sha256(str(value).encode()).digest()+ return int.from_bytes(digest[:8], byteorder="big")+++def filter_ids_for_rollout(ids: list[T], rollout_percentage: float) -> list[T]:+ """Same `ids` + same percentage always yields the same subset, so canaries are stable across runs."""+ if rollout_percentage <= 0 or rollout_percentage > 1:+ raise ValueError(f"rollout_percentage must be in (0, 1], got {rollout_percentage}")+ if not ids:+ return []+ if rollout_percentage >= 1.0:+ return ids++ target_count = max(1, math.ceil(len(ids) * rollout_percentage))+ ranked = sorted(ids, key=lambda x: (_rollout_rank(x), str(x)))+ return ranked[:target_count]diff --git a/posthog/temporal/health_checks/activities.py b/posthog/temporal/health_checks/activities.pyindex 36149848a024..23e8b1eded27 100644--- a/posthog/temporal/health_checks/activities.py+++ b/posthog/temporal/health_checks/activities.py@@ -1,5 +1,3 @@-import math-import hashlibimport dataclassesfrom datetime import timedeltafrom itertools import batched@@ -16,6 +14,7 @@ from posthog.clickhouse.query_tagging import Feature, tag_queriesfrom posthog.dags.common.health.observability import push_health_check_metricsfrom posthog.models.organization import OrganizationMembershipfrom posthog.sync import database_sync_to_async+from posthog.temporal.common.rollout import filter_ids_for_rolloutfrom posthog.temporal.health_checks.models import BatchResult, HealthCheckWorkflowInputsfrom posthog.temporal.health_checks.processing import _process_batch_detectionfrom posthog.temporal.health_checks.registry import ensure_registry_loaded, get_detect_fn, get_product@@ -23,24 +22,6 @@ from posthog.temporal.health_checks.registry import ensure_registry_loaded, get_logger = structlog.get_logger(__name__)-def _team_rollout_rank(team_id: int) -> int:- digest = hashlib.sha256(str(team_id).encode()).digest()- return int.from_bytes(digest[:8], byteorder="big")---def _filter_team_ids_for_rollout(team_ids: list[int], rollout_percentage: float) -> list[int]:- if rollout_percentage <= 0 or rollout_percentage > 1:- raise ValueError(f"rollout_percentage must be in (0, 1], got {rollout_percentage}")- if not team_ids:- return []- if rollout_percentage >= 1.0:- return team_ids-- target_count = max(1, math.ceil(len(team_ids) * rollout_percentage))- ranked_team_ids = sorted(team_ids, key=lambda team_id: (_team_rollout_rank(team_id), team_id))- return ranked_team_ids[:target_count]--@database_sync_to_asyncdef _get_team_id_batches_sync(inputs: HealthCheckWorkflowInputs) -> list[list[int]]:from posthog.models.team import Team@@ -83,7 +64,7 @@ def _get_team_id_batches_sync(inputs: HealthCheckWorkflowInputs) -> list[list[in)if inputs.rollout_percentage < 1.0:- team_ids = _filter_team_ids_for_rollout(team_ids, inputs.rollout_percentage)+ team_ids = filter_ids_for_rollout(team_ids, inputs.rollout_percentage)logger.info("after rollout filtering", rollout_pct=inputs.rollout_percentage, count=len(team_ids))batches = [list(b) for b in batched(team_ids, inputs.batch_size)]diff --git a/products/web_analytics/backend/temporal/weekly_digest/__init__.py b/products/web_analytics/backend/temporal/weekly_digest/__init__.pyindex 105e51fdfcd1..8b5177622109 100644--- a/products/web_analytics/backend/temporal/weekly_digest/__init__.py+++ b/products/web_analytics/backend/temporal/weekly_digest/__init__.py@@ -1,6 +1,7 @@from products.web_analytics.backend.temporal.weekly_digest.activities import (- build_and_send_wa_digest_for_org,- get_orgs_for_wa_digest,+ get_org_id_batches,+ push_wa_digest_metrics_activity,+ run_wa_digest_batch,send_test_wa_digest,)from products.web_analytics.backend.temporal.weekly_digest.workflows import (@@ -9,4 +10,9 @@ from products.web_analytics.backend.temporal.weekly_digest.workflows import ()WORKFLOWS = [WAWeeklyDigestWorkflow, WAWeeklyDigestTestWorkflow]-ACTIVITIES = [get_orgs_for_wa_digest, build_and_send_wa_digest_for_org, send_test_wa_digest]+ACTIVITIES = [+ get_org_id_batches,+ run_wa_digest_batch,+ push_wa_digest_metrics_activity,+ send_test_wa_digest,+]diff --git a/products/web_analytics/backend/temporal/weekly_digest/activities.py b/products/web_analytics/backend/temporal/weekly_digest/activities.pyindex 20b120fe37cd..20b5c205b048 100644--- a/products/web_analytics/backend/temporal/weekly_digest/activities.py+++ b/products/web_analytics/backend/temporal/weekly_digest/activities.py@@ -1,58 +1,116 @@+import time+from datetime import timedelta+from itertools import batched+from django.conf import settingsfrom django.db import close_old_connections+from django.db.models import Exists, OuterReffrom django.utils import timezoneimport structlogimport posthoganalytics+from prometheus_client import Gaugefrom temporalio import activity+from temporalio.exceptions import ApplicationError+from posthog.clickhouse.client.execute import KillSwitchLevel, get_kill_switch_level+from posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom posthog.email import EmailMessage, is_email_available+from posthog.exceptions_capture import capture_exception+from posthog.metrics import pushed_metrics_registryfrom posthog.models import Teamfrom posthog.models.organization import Organization, OrganizationMembershipfrom posthog.models.user import Userfrom posthog.sync import database_sync_to_asyncfrom posthog.tasks.email import NotificationSetting, should_send_notificationfrom posthog.temporal.common.heartbeat import Heartbeater+from posthog.temporal.common.rollout import filter_ids_for_rolloutfrom posthog.user_permissions import UserPermissionsfrom products.web_analytics.backend.temporal.weekly_digest.types import (- BuildAndSendDigestForOrgInput,+ WA_DIGEST_EMAIL_UNAVAILABLE_TYPE,+ DigestBatchInput,+ DigestBatchResult,+ DigestOutcome,+ OrgDigestCounts,SendTestDigestInput,+ WAWeeklyDigestInput,)from products.web_analytics.backend.weekly_digest import auto_select_project_for_user, build_team_digestlogger = structlog.get_logger(__name__)-def _get_orgs_for_wa_digest() -> list[str]:- """Synchronous implementation: discover orgs with the digest flag enabled."""+def _get_org_id_batches(input: WAWeeklyDigestInput) -> list[list[str]]:+ """Raises non-retryable `ApplicationError` when email is globally unavailable+ — per-org skips would silently absorb the outage.+ """close_old_connections()- org_ids = [str(oid) for oid in Organization.objects.values_list("id", flat=True)]- targeted_org_ids = [- org_id- for org_id in org_ids- if posthoganalytics.feature_enabled(- "web-analytics-weekly-digest",- distinct_id=f"digest-worker-{org_id}",- groups={"organization": org_id},- only_evaluate_locally=True,- send_feature_flag_events=False,+ kill_switch_level = get_kill_switch_level()+ if kill_switch_level != KillSwitchLevel.OFF:+ logger.info(+ "skipping wa weekly digest due to clickhouse kill switch",+ kill_switch_level=kill_switch_level.value,)- ]+ return []- logger.info(- "Discovered orgs for WA digest",- targeted=len(targeted_org_ids),- total=len(org_ids),- )- return targeted_org_ids+ if not is_email_available(with_absolute_urls=True):+ raise ApplicationError(+ "WA weekly digest: email service is unavailable",+ type=WA_DIGEST_EMAIL_UNAVAILABLE_TYPE,+ non_retryable=True,+ )+ if input.org_ids:+ org_ids = list(input.org_ids)+ logger.info("processing configured orgs for WA digest", count=len(org_ids))+ else:+ qs = Organization.objects.all()+ cutoff = None+ if input.active_since_days is not None and input.active_since_days > 0:+ cutoff = timezone.now() - timedelta(days=input.active_since_days)+ qs = qs.filter(+ Exists(+ OrganizationMembership.objects.filter(+ organization_id=OuterRef("id"),+ user__last_login__gte=cutoff,+ )+ )+ )+ all_org_ids = [str(oid) for oid in qs.values_list("id", flat=True)]++ org_ids = [+ org_id+ for org_id in all_org_ids+ if posthoganalytics.feature_enabled(+ "web-analytics-weekly-digest",+ distinct_id=f"digest-worker-{org_id}",+ groups={"organization": org_id},+ only_evaluate_locally=True,+ send_feature_flag_events=False,+ )+ ]+ logger.info(+ "wa digest org query complete",+ total=len(all_org_ids),+ after_flag=len(org_ids),+ active_since_days=input.active_since_days,+ cutoff=cutoff.isoformat() if cutoff else None,+ )++ if input.rollout_percentage < 1.0:+ org_ids = filter_ids_for_rollout(org_ids, input.rollout_percentage)+ logger.info("after rollout filtering", rollout_pct=input.rollout_percentage, count=len(org_ids))[email protected](name="wa-digest-get-orgs")-async def get_orgs_for_wa_digest() -> list[str]:- """Discover orgs where the web-analytics-weekly-digest flag is enabled."""- return await database_sync_to_async(_get_orgs_for_wa_digest, thread_sensitive=False)()+ batches = [list(b) for b in batched(org_ids, input.batch_size)]+ logger.info("created wa digest batches", batch_count=len(batches), batch_size=input.batch_size)+ return batches++[email protected](name="wa-digest-get-org-batches")+async def get_org_id_batches(input: WAWeeklyDigestInput) -> list[list[str]]:+ return await database_sync_to_async(_get_org_id_batches, thread_sensitive=False)(input)def _send_digest_for_user(@@ -64,12 +122,13 @@ def _send_digest_for_user(date_suffix: str,dry_run: bool = False,test: bool = False,-) -> bool:- """`test=True` bypasses notification opt-ins and forces a unique campaign_key so- dedupe never blocks delivery. The team-access check is always enforced.+) -> DigestOutcome:+ """`test=True` bypasses notification opt-ins and forces a unique+ campaign_key so dedupe never blocks delivery. Team-access checks are always+ enforced."""if not test and not should_send_notification(user, NotificationSetting.WEB_ANALYTICS_WEEKLY_DIGEST.value):- return False+ return DigestOutcome.SKIPPED_OPTOUTuser_perms = UserPermissions(user)accessible_team_data: dict[int, dict] = {}@@ -79,7 +138,7 @@ def _send_digest_for_user(accessible_team_data[team_id] = dataif not accessible_team_data:- return False+ return DigestOutcome.SKIPPED_NO_DATAif auto_select_project_for_user(user, accessible_team_data):user.refresh_from_db(fields=["partial_notification_settings"])@@ -93,7 +152,7 @@ def _send_digest_for_user(disabled_team_names.append(data["team"].name)if not user_team_sections:- return False+ return DigestOutcome.SKIPPED_NO_DATAuser_team_sections.sort(key=lambda d: d.get("visitors", {}).get("current", 0), reverse=True)@@ -102,39 +161,48 @@ def _send_digest_for_user(campaign_key = f"{campaign_key}_test_{int(timezone.now().timestamp())}"if dry_run:- return True-- message = EmailMessage(- campaign_key=campaign_key,- subject=f"Web analytics weekly digest for {org.name}",- template_name="web_analytics_weekly_digest",- template_context={- "organization": org,- "project_sections": user_team_sections,- "disabled_project_names": disabled_team_names,- "settings_url": f"{settings.SITE_URL}/settings/user-notifications?highlight=wa-weekly-digest",- },- )- message.add_user_recipient(user)- message.send()- return True+ return DigestOutcome.DRY_RUN+ try:+ message = EmailMessage(+ campaign_key=campaign_key,+ subject=f"Web analytics weekly digest for {org.name}",+ template_name="web_analytics_weekly_digest",+ template_context={+ "organization": org,+ "project_sections": user_team_sections,+ "disabled_project_names": disabled_team_names,+ "settings_url": f"{settings.SITE_URL}/settings/user-notifications?highlight=wa-weekly-digest",+ },+ )+ message.add_user_recipient(user)+ message.send()+ except Exception as e:+ if test:+ raise+ logger.warning(+ "failed to send wa digest email",+ 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)})+ return DigestOutcome.FAILED-def _build_and_send_for_org(org_id: str, dry_run: bool = False) -> dict:- """Synchronous implementation: compute digests per team, send email per member.+ return DigestOutcome.SENT- Runs on a thread via database_sync_to_async.- """++def _build_and_send_for_org(org_id: str, dry_run: bool = False) -> OrgDigestCounts:close_old_connections()- if not is_email_available(with_absolute_urls=True):- return {"sent_count": 0, "team_count": 0, "skipped": "email_unavailable"}+ counts = OrgDigestCounts()try:org = Organization.objects.get(id=org_id)except Organization.DoesNotExist:logger.warning("Organization not found for WA weekly digest", org_id=org_id)- return {"sent_count": 0, "team_count": 0, "skipped": "org_not_found"}+ counts.skipped_reason = "org_not_found"+ return countsmemberships = list(OrganizationMembership.objects.prefetch_related("user").filter(organization_id=org.id))targeted_memberships = [@@ -149,43 +217,171 @@ def _build_and_send_for_org(org_id: str, dry_run: bool = False) -> dict:)]if not targeted_memberships:- return {"sent_count": 0, "team_count": 0, "skipped": "no_targeted_memberships"}+ counts.skipped_reason = "no_targeted_memberships"+ return countsall_org_teams = list(Team.objects.filter(organization_id=org.id))if not all_org_teams:- return {"sent_count": 0, "team_count": 0, "skipped": "no_teams"}+ counts.skipped_reason = "no_teams"+ return counts+ build_start = time.monotonic()team_digest_data: dict[int, dict] = {team.id: build_team_digest(team) for team in all_org_teams}+ counts.build_duration = time.monotonic() - build_start+ counts.team_count = len(team_digest_data)+date_suffix = timezone.now().strftime("%Y-%W")- sent_count = 0+ send_start = time.monotonic()for membership in targeted_memberships:- if _send_digest_for_user(+ outcome = _send_digest_for_user(user=membership.user,org=org,membership=membership,team_digest_data=team_digest_data,date_suffix=date_suffix,dry_run=dry_run,- ):- sent_count += 1+ )+ if outcome in (DigestOutcome.SENT, DigestOutcome.DRY_RUN):+ counts.sent += 1+ elif outcome == DigestOutcome.SKIPPED_OPTOUT:+ counts.skipped_optout += 1+ elif outcome == DigestOutcome.SKIPPED_NO_DATA:+ counts.skipped_no_data += 1+ elif outcome == DigestOutcome.FAILED:+ counts.failed += 1+ counts.send_duration = time.monotonic() - send_startlogger.info("Sent WA weekly digest for org",org_id=org_id,- sent_count=sent_count,- team_count=len(team_digest_data),+ sent_count=counts.sent,+ skipped_optout=counts.skipped_optout,+ skipped_no_data=counts.skipped_no_data,+ failed=counts.failed,+ team_count=counts.team_count,+ )+ return counts+++def _run_wa_digest_batch(input: DigestBatchInput) -> DigestBatchResult:+ close_old_connections()++ tag_queries(+ product=Product.WEB_ANALYTICS,+ feature=Feature.DIGEST,+ name="wa_weekly_digest",)- return {"sent_count": sent_count, "team_count": len(team_digest_data)}+ totals = DigestBatchResult(batch_size=len(input.org_ids))[email protected](name="wa-digest-build-and-send-for-org")-async def build_and_send_wa_digest_for_org(input: BuildAndSendDigestForOrgInput) -> dict:- """Process a single org: compute digests per team, send email per member."""+ for org_id in input.org_ids:+ try:+ org_counts = _build_and_send_for_org(org_id, dry_run=input.dry_run)+ except Exception as e:+ logger.exception("WA digest 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.emails_sent += org_counts.sent+ totals.emails_skipped_optout += org_counts.skipped_optout+ totals.emails_skipped_no_data += org_counts.skipped_no_data+ totals.emails_failed += org_counts.failed+ totals.build_duration += org_counts.build_duration+ totals.send_duration += org_counts.send_duration++ return totals++[email protected](name="wa-digest-run-batch")+async def run_wa_digest_batch(input: DigestBatchInput) -> DigestBatchResult:+ """Per-org failures are isolated (logged and counted) so one bad org never poisons the batch."""async with Heartbeater():- return await database_sync_to_async(_build_and_send_for_org, thread_sensitive=False)(- input.org_id, input.dry_run- )+ return await database_sync_to_async(_run_wa_digest_batch, thread_sensitive=False)(input)+++def _push_wa_digest_metrics(totals: DigestBatchResult, success: bool) -> None:+ if not settings.PROM_PUSHGATEWAY_ADDRESS:+ return++ try:+ with pushed_metrics_registry("wa_weekly_digest") as registry:+ duration_gauge = Gauge(+ "posthog_wa_digest_duration_seconds",+ "Time spent in each phase of the WA weekly digest run (work time, summed across concurrent batches — not wall-clock)",+ labelnames=["phase"],+ registry=registry,+ )+ for phase, value in [+ ("build", totals.build_duration),+ ("send", totals.send_duration),+ ("cumulative", totals.total_duration),+ ]:+ duration_gauge.labels(phase=phase).set(value)++ orgs_gauge = Gauge(+ "posthog_wa_digest_orgs",+ "Org outcomes for a WA weekly digest run",+ labelnames=["outcome"],+ registry=registry,+ )+ for outcome, value in [+ ("total", totals.batch_size),+ ("processed", totals.orgs_processed),+ ("skipped", totals.orgs_skipped),+ ("failed", totals.orgs_failed),+ ]:+ orgs_gauge.labels(outcome=outcome).set(value)++ emails_gauge = Gauge(+ "posthog_wa_digest_emails",+ "Email outcomes for a WA weekly digest run",+ labelnames=["outcome"],+ registry=registry,+ )+ for outcome, value in [+ ("sent", totals.emails_sent),+ ("skipped_optout", totals.emails_skipped_optout),+ ("skipped_no_data", totals.emails_skipped_no_data),+ ("failed", totals.emails_failed),+ ]:+ emails_gauge.labels(outcome=outcome).set(value)++ success_gauge = Gauge(+ "posthog_wa_digest_success",+ "1 if the WA weekly digest run completed within failure threshold, else 0",+ registry=registry,+ )+ success_gauge.set(1 if success else 0)++ failure_rate_gauge = Gauge(+ "posthog_wa_digest_failure_rate",+ "Fraction of orgs whose processing raised an exception in the WA weekly digest",+ registry=registry,+ )+ failure_rate_gauge.set(totals.failure_rate)++ last_run_gauge = Gauge(+ "posthog_wa_digest_last_run_timestamp",+ "Unix timestamp of the most recent WA weekly digest run",+ registry=registry,+ )+ last_run_gauge.set(time.time())+ except Exception as e:+ logger.warning("Failed to push WA digest metrics to Pushgateway", error=str(e))+ capture_exception(e)++[email protected](name="wa-digest-push-metrics")+async def push_wa_digest_metrics_activity(totals_dict: dict, success: bool) -> None:+ totals = DigestBatchResult(**totals_dict)+ await database_sync_to_async(_push_wa_digest_metrics, thread_sensitive=False)(totals, success)def _send_test_digest(email: str, team_id: int | None = None) -> None:@@ -215,7 +411,7 @@ def _send_test_digest(email: str, team_id: int | None = None) -> None:if not membership:raise PermissionError(f"User {email} is not a member of the organization that owns team {team_id}")- sent = _send_digest_for_user(+ outcome = _send_digest_for_user(user=user,org=team.organization,membership=membership,@@ -223,7 +419,7 @@ def _send_test_digest(email: str, team_id: int | None = None) -> None:date_suffix=date_suffix,test=True,)- if not sent:+ if outcome != DigestOutcome.SENT:raise PermissionError(f"User {email} does not have access to team {team_id}")logger.info(@@ -246,14 +442,15 @@ def _send_test_digest(email: str, team_id: int | None = None) -> None:if not org_teams:continueteam_digest_data = {t.id: build_team_digest(t) for t in org_teams}- if _send_digest_for_user(+ outcome = _send_digest_for_user(user=user,org=org,membership=membership,team_digest_data=team_digest_data,date_suffix=date_suffix,test=True,- ):+ )+ if outcome == DigestOutcome.SENT:sent_count += 1if sent_count == 0:diff --git a/products/web_analytics/backend/temporal/weekly_digest/types.py b/products/web_analytics/backend/temporal/weekly_digest/types.pyindex 63f21f5b57af..3c34491b4eb5 100644--- a/products/web_analytics/backend/temporal/weekly_digest/types.py+++ b/products/web_analytics/backend/temporal/weekly_digest/types.py@@ -1,20 +1,83 @@import dataclasses+from enum import StrEnum+++class DigestOutcome(StrEnum):+ """Outcome of attempting to send a single digest email to a single user."""++ SENT = "sent"+ DRY_RUN = "dry_run"+ SKIPPED_OPTOUT = "skipped_optout"+ SKIPPED_NO_DATA = "skipped_no_data"+ FAILED = "failed"+++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+ counted as skipped, not processed.+ """++ sent: int = 0+ skipped_optout: 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@dataclasses.dataclassclass WAWeeklyDigestInput:- """Top-level input for the WA weekly digest coordinator workflow."""+ dry_run: bool = False+ batch_size: int = 25+ max_concurrent: int = 4+ rollout_percentage: float = 1.0+ failure_threshold: float = 0.2+ active_since_days: int | None = 30+ org_ids: list[str] | None = None++class DigestBatchInput:+ org_ids: list[str]dry_run: bool = False- max_concurrent: int = 10@dataclasses.dataclass-class BuildAndSendDigestForOrgInput:- """Input for the per-org activity."""+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.+ """- org_id: str- dry_run: bool = False+ batch_size: int = 0+ orgs_processed: int = 0+ orgs_skipped: int = 0+ orgs_failed: int = 0+ emails_sent: int = 0+ emails_skipped_optout: int = 0+ emails_skipped_no_data: int = 0+ emails_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.dataclass@@ -31,3 +94,7 @@ class SendTestDigestInput:email: strteam_id: int | None = None+++WA_DIGEST_THRESHOLD_EXCEEDED_TYPE = "WADigestThresholdExceeded"+WA_DIGEST_EMAIL_UNAVAILABLE_TYPE = "WADigestEmailUnavailable"diff --git a/products/web_analytics/backend/temporal/weekly_digest/workflows.py b/products/web_analytics/backend/temporal/weekly_digest/workflows.pyindex 47cc97f6c42a..c5df1feb67c6 100644--- a/products/web_analytics/backend/temporal/weekly_digest/workflows.py+++ b/products/web_analytics/backend/temporal/weekly_digest/workflows.py@@ -1,32 +1,42 @@+import jsonimport asyncio+import dataclassesfrom datetime import timedeltafrom temporalio import common, workflow+from temporalio.exceptions import ApplicationErrorfrom posthog.temporal.common.base import PostHogWorkflowwith workflow.unsafe.imports_passed_through():from products.web_analytics.backend.temporal.weekly_digest.activities import (- build_and_send_wa_digest_for_org,- get_orgs_for_wa_digest,+ get_org_id_batches,+ push_wa_digest_metrics_activity,+ run_wa_digest_batch,send_test_wa_digest,)from products.web_analytics.backend.temporal.weekly_digest.types import (- BuildAndSendDigestForOrgInput,+ WA_DIGEST_THRESHOLD_EXCEEDED_TYPE,+ DigestBatchInput,+ DigestBatchResult,SendTestDigestInput,WAWeeklyDigestInput,)+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):@staticmethoddef parse_inputs(inputs: list[str]) -> WAWeeklyDigestInput:- """Parse inputs from the management command CLI."""if inputs:- import json- import dataclasses-data = json.loads(inputs[0])return WAWeeklyDigestInput(**{f.name: data[f.name] for f in dataclasses.fields(WAWeeklyDigestInput) if f.name in data}@@ -34,54 +44,78 @@ class WAWeeklyDigestWorkflow(PostHogWorkflow):return WAWeeklyDigestInput()@workflow.run- async def run(self, input: WAWeeklyDigestInput) -> None:- org_ids = await workflow.execute_activity(- get_orgs_for_wa_digest,- start_to_close_timeout=timedelta(minutes=10),- retry_policy=common.RetryPolicy(maximum_attempts=3),+ async def run(self, input: WAWeeklyDigestInput) -> dict:+ batches = await workflow.execute_activity(+ get_org_id_batches,+ input,+ start_to_close_timeout=timedelta(minutes=5),+ retry_policy=ACTIVITY_RETRY_POLICY,)- if not org_ids:- workflow.logger.info("No orgs targeted for WA weekly digest")- return+ if not batches:+ workflow.logger.info("No org batches for WA weekly digest")+ return {"orgs": 0, "batches": 0}- workflow.logger.info("Fanning out WA digest to %d orgs", len(org_ids))+ workflow.logger.info(+ "Fanning out WA digest",+ batches=len(batches),+ orgs=sum(len(b) for b in batches),+ )semaphore = asyncio.Semaphore(input.max_concurrent)- async def _run_for_org(org_id: str) -> dict:+ async def _run_batch(batch: list[str]) -> DigestBatchResult:async with semaphore:return await workflow.execute_activity(- build_and_send_wa_digest_for_org,- BuildAndSendDigestForOrgInput(org_id=org_id, dry_run=input.dry_run),+ run_wa_digest_batch,+ DigestBatchInput(org_ids=batch, dry_run=input.dry_run),start_to_close_timeout=timedelta(minutes=30),heartbeat_timeout=timedelta(minutes=5),- retry_policy=common.RetryPolicy(- maximum_attempts=2,- initial_interval=timedelta(minutes=2),- ),+ retry_policy=ACTIVITY_RETRY_POLICY,)results = await asyncio.gather(- *[_run_for_org(org_id) for org_id in org_ids],+ *[_run_batch(b) for b in batches],return_exceptions=True,)- successes = 0- failures = 0- for org_id, result in zip(org_ids, results):- if isinstance(result, BaseException):- failures += 1- workflow.logger.error("WA digest failed for org %s: %s", org_id, str(result))+ totals = DigestBatchResult()+ failed_batches = 0+ for batch, r in zip(batches, results):+ if isinstance(r, BaseException):+ failed_batches += 1+ totals += DigestBatchResult(batch_size=len(batch), orgs_failed=len(batch))+ workflow.logger.error("WA digest batch failed: %s", str(r))else:- successes += 1+ totals += r- workflow.logger.info(- "WA weekly digest complete: %d succeeded, %d failed",- successes,- failures,+ threshold_exceeded = totals.batch_size > 0 and totals.failure_rate > input.failure_threshold++ await workflow.execute_activity(+ push_wa_digest_metrics_activity,+ args=[dataclasses.asdict(totals), not threshold_exceeded],+ start_to_close_timeout=timedelta(minutes=2),+ retry_policy=ACTIVITY_RETRY_POLICY,)+ if threshold_exceeded:+ raise ApplicationError(+ f"WA weekly digest: {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_THRESHOLD_EXCEEDED_TYPE,+ non_retryable=True,+ )++ return {+ "orgs": totals.batch_size,+ "batches": len(batches),+ "failed_batches": failed_batches,+ "emails_sent": totals.emails_sent,+ "emails_failed": totals.emails_failed,+ "cumulative_duration_seconds": totals.total_duration,+ }+@workflow.defn(name="wa-weekly-digest-test")class WAWeeklyDigestTestWorkflow(PostHogWorkflow):@@ -95,8 +129,6 @@ class WAWeeklyDigestTestWorkflow(PostHogWorkflow):manage.py start_temporal_workflow wa-weekly-digest-test '{"email": "[email protected]"}'manage.py start_temporal_workflow wa-weekly-digest-test '{"email": "[email protected]", "team_id": 1}'"""- import json-data = json.loads(inputs[0])return SendTestDigestInput(email=data["email"],diff --git a/products/web_analytics/backend/test/test_weekly_digest_activities.py b/products/web_analytics/backend/test/test_weekly_digest_activities.pyindex 251dfdbe7b4a..7f134d519af6 100644--- a/products/web_analytics/backend/test/test_weekly_digest_activities.py+++ b/products/web_analytics/backend/test/test_weekly_digest_activities.py@@ -1,10 +1,32 @@+import math+from datetime import timedelta+from posthog.test.base import APIBaseTestfrom unittest.mock import MagicMock, patch-from posthog.models import OrganizationMembership, Team+from django.utils import timezone++from parameterized import parameterized+from temporalio.exceptions import ApplicationError++from posthog.clickhouse.client.execute import KillSwitchLevel+from posthog.models import OrganizationMembership, Team, Userfrom posthog.models.organization import Organization-from products.web_analytics.backend.temporal.weekly_digest.activities import _send_digest_for_user, _send_test_digest+from products.web_analytics.backend.temporal.weekly_digest.activities import (+ _get_org_id_batches,+ _run_wa_digest_batch,+ _send_digest_for_user,+ _send_test_digest,+)+from products.web_analytics.backend.temporal.weekly_digest.types import (+ WA_DIGEST_EMAIL_UNAVAILABLE_TYPE,+ DigestBatchInput,+ DigestBatchResult,+ DigestOutcome,+ OrgDigestCounts,+ WAWeeklyDigestInput,+)def _make_team_digest(team, visitors=10):@@ -52,14 +74,14 @@ class _DigestTestBase(APIBaseTest):class TestSendDigestForUser(_DigestTestBase):def test_sends_email_with_default_notification_settings(self):- sent = _send_digest_for_user(+ outcome = _send_digest_for_user(user=self.user,org=self.organization,membership=self.organization_membership,team_digest_data={self.team.id: _make_team_digest(self.team)},date_suffix="2025-15",)- assert sent is True+ assert outcome == DigestOutcome.SENTself.mock_email_class.assert_called_once()kwargs = self.mock_email_class.call_args.kwargsassert kwargs["subject"] == f"Web analytics weekly digest for {self.organization.name}"@@ -70,20 +92,20 @@ class TestSendDigestForUser(_DigestTestBase):def test_skips_when_org_level_opt_out_and_not_test(self):self.user.partial_notification_settings = {"web_analytics_weekly_digest": False}self.user.save()- sent = _send_digest_for_user(+ outcome = _send_digest_for_user(user=self.user,org=self.organization,membership=self.organization_membership,team_digest_data={self.team.id: _make_team_digest(self.team)},date_suffix="2025-15",)- assert sent is False+ assert outcome == DigestOutcome.SKIPPED_OPTOUTself.mock_email_class.assert_not_called()def test_sends_anyway_when_org_level_opt_out_but_test_true(self):self.user.partial_notification_settings = {"web_analytics_weekly_digest": False}self.user.save()- sent = _send_digest_for_user(+ outcome = _send_digest_for_user(user=self.user,org=self.organization,membership=self.organization_membership,@@ -91,12 +113,12 @@ class TestSendDigestForUser(_DigestTestBase):date_suffix="2025-15",test=True,)- assert sent is True+ assert outcome == DigestOutcome.SENTkwargs = self.mock_email_class.call_args.kwargsassert "_test_" in kwargs["campaign_key"]- def test_returns_false_when_team_digest_data_is_empty(self):- sent = _send_digest_for_user(+ def test_returns_no_data_when_team_digest_data_is_empty(self):+ outcome = _send_digest_for_user(user=self.user,org=self.organization,membership=self.organization_membership,@@ -104,11 +126,11 @@ class TestSendDigestForUser(_DigestTestBase):date_suffix="2025-15",test=True,)- assert sent is False+ assert outcome == DigestOutcome.SKIPPED_NO_DATAself.mock_email_class.assert_not_called()def test_dry_run_does_not_send(self):- sent = _send_digest_for_user(+ outcome = _send_digest_for_user(user=self.user,org=self.organization,membership=self.organization_membership,@@ -116,16 +138,40 @@ class TestSendDigestForUser(_DigestTestBase):date_suffix="2025-15",dry_run=True,)- assert sent is True+ assert outcome == DigestOutcome.DRY_RUNself.mock_email_class.assert_not_called()+ def test_returns_failed_when_email_send_raises(self):+ self.mock_message.send.side_effect = RuntimeError("smtp blew up")+ outcome = _send_digest_for_user(+ user=self.user,+ org=self.organization,+ membership=self.organization_membership,+ team_digest_data={self.team.id: _make_team_digest(self.team)},+ date_suffix="2025-15",+ )+ assert outcome == DigestOutcome.FAILED++ def test_propagates_send_error_when_test_mode(self):+ self.mock_message.send.side_effect = RuntimeError("smtp blew up")+ with self.assertRaises(RuntimeError) as cm:+ _send_digest_for_user(+ user=self.user,+ org=self.organization,+ membership=self.organization_membership,+ team_digest_data={self.team.id: _make_team_digest(self.team)},+ date_suffix="2025-15",+ test=True,+ )+ assert "smtp blew up" in str(cm.exception)+def test_test_mode_bypasses_per_team_opt_out(self):team_b = Team.objects.create(organization=self.organization, name="Team B")self.user.partial_notification_settings = {"web_analytics_weekly_digest_project_enabled": {str(self.team.id): True},}self.user.save()- sent = _send_digest_for_user(+ outcome = _send_digest_for_user(user=self.user,org=self.organization,membership=self.organization_membership,@@ -136,7 +182,7 @@ class TestSendDigestForUser(_DigestTestBase):date_suffix="2025-15",test=True,)- assert sent is True+ assert outcome == DigestOutcome.SENTsections = self.mock_email_class.call_args.kwargs["template_context"]["project_sections"]assert {s["team"].id for s in sections} == {self.team.id, team_b.id}@@ -146,7 +192,7 @@ class TestSendDigestForUser(_DigestTestBase):"web_analytics_weekly_digest_project_enabled": {str(self.team.id): True},}self.user.save()- sent = _send_digest_for_user(+ outcome = _send_digest_for_user(user=self.user,org=self.organization,membership=self.organization_membership,@@ -156,7 +202,7 @@ class TestSendDigestForUser(_DigestTestBase):},date_suffix="2025-15",)- assert sent is True+ assert outcome == DigestOutcome.SENTctx = self.mock_email_class.call_args.kwargs["template_context"]assert [s["team"].id for s in ctx["project_sections"]] == [self.team.id]assert team_b.name in ctx["disabled_project_names"]@@ -164,7 +210,7 @@ class TestSendDigestForUser(_DigestTestBase):def test_sections_sorted_by_visitors_descending(self):team_b = Team.objects.create(organization=self.organization, name="Team B")team_c = Team.objects.create(organization=self.organization, name="Team C")- sent = _send_digest_for_user(+ outcome = _send_digest_for_user(user=self.user,org=self.organization,membership=self.organization_membership,@@ -176,7 +222,7 @@ class TestSendDigestForUser(_DigestTestBase):date_suffix="2025-15",test=True,)- assert sent is True+ assert outcome == DigestOutcome.SENTsections = self.mock_email_class.call_args.kwargs["template_context"]["project_sections"]assert [s["team"].id for s in sections] == [team_b.id, team_c.id, self.team.id]@@ -280,3 +326,229 @@ class TestSendTestDigestFullUserMode(_DigestTestBase):with self.assertRaises(ValueError):_send_test_digest(email="[email protected]")self.mock_email_class.assert_not_called()+++class TestGetOrgIdBatches(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.flag_patcher = patch(+ "products.web_analytics.backend.temporal.weekly_digest.activities.posthoganalytics.feature_enabled",+ return_value=True,+ )+ self.flag_patcher.start()+ self.kill_switch_patcher = patch(+ "products.web_analytics.backend.temporal.weekly_digest.activities.get_kill_switch_level",+ )+ self.mock_kill_switch = self.kill_switch_patcher.start()+ self.mock_kill_switch.return_value = KillSwitchLevel.OFF+ self.email_available_patcher = patch(+ "products.web_analytics.backend.temporal.weekly_digest.activities.is_email_available",+ return_value=True,+ )+ self.mock_email_available = self.email_available_patcher.start()+ self.close_conn_patcher = patch(+ "products.web_analytics.backend.temporal.weekly_digest.activities.close_old_connections"+ )+ self.close_conn_patcher.start()++ def tearDown(self):+ self.close_conn_patcher.stop()+ self.email_available_patcher.stop()+ self.kill_switch_patcher.stop()+ self.flag_patcher.stop()+ super().tearDown()++ def test_returns_empty_list_when_kill_switch_active(self):+ self.mock_kill_switch.return_value = KillSwitchLevel.LIGHT+ batches = _get_org_id_batches(WAWeeklyDigestInput())+ assert batches == []++ def test_raises_when_email_unavailable(self):+ self.mock_email_available.return_value = False+ with self.assertRaises(ApplicationError) as ctx:+ _get_org_id_batches(WAWeeklyDigestInput())+ assert ctx.exception.type == WA_DIGEST_EMAIL_UNAVAILABLE_TYPE+ assert ctx.exception.non_retryable is True++ def test_kill_switch_short_circuits_before_email_check(self):+ self.mock_kill_switch.return_value = KillSwitchLevel.LIGHT+ self.mock_email_available.return_value = False+ batches = _get_org_id_batches(WAWeeklyDigestInput())+ assert batches == []++ def test_active_since_filter_excludes_orgs_with_only_dormant_members(self):+ self.user.last_login = timezone.now()+ self.user.save()++ dormant_org = Organization.objects.create(name="Dormant org")+ dormant_user = User.objects.create_user(email="[email protected]", password="x", first_name="Dormant")+ dormant_user.last_login = timezone.now() - timedelta(days=200)+ dormant_user.save()+ OrganizationMembership.objects.create(+ organization=dormant_org,+ user=dormant_user,+ level=OrganizationMembership.Level.MEMBER,+ )++ batches = _get_org_id_batches(WAWeeklyDigestInput(active_since_days=30, batch_size=100))+ all_org_ids = {oid for batch in batches for oid in batch}+ assert str(self.organization.id) in all_org_ids+ assert str(dormant_org.id) not in all_org_ids++ def test_admin_org_ids_override_bypasses_filters(self):+ override = ["1111", "2222", "3333"]+ batches = _get_org_id_batches(WAWeeklyDigestInput(org_ids=override, batch_size=2, active_since_days=1))+ flat = [oid for batch in batches for oid in batch]+ assert flat == override+ assert [len(b) for b in batches] == [2, 1]++ def test_admin_org_ids_override_bypasses_rollout(self):+ override = [f"org-{i:04d}" for i in range(20)]+ batches = _get_org_id_batches(WAWeeklyDigestInput(org_ids=override, rollout_percentage=0.1, batch_size=100))+ flat = [oid for batch in batches for oid in batch]+ assert flat == override++ @parameterized.expand(+ [+ ("ten_percent", 0.1),+ ("fifty_percent", 0.5),+ ]+ )+ def test_rollout_filter_is_deterministic(self, _name, percentage):+ all_org_ids = [f"org-{i:04d}" for i in range(100)]+ with patch("products.web_analytics.backend.temporal.weekly_digest.activities.Organization") as mock_org_model:+ mock_org_model.objects.all.return_value.values_list.return_value = all_org_ids+ first = _get_org_id_batches(+ WAWeeklyDigestInput(rollout_percentage=percentage, batch_size=10, active_since_days=None)+ )+ second = _get_org_id_batches(+ WAWeeklyDigestInput(rollout_percentage=percentage, batch_size=10, active_since_days=None)+ )+ first_flat = [oid for batch in first for oid in batch]+ second_flat = [oid for batch in second for oid in batch]+ assert first_flat == second_flat+ assert len(first_flat) == math.ceil(100 * percentage)+++class TestRunWaDigestBatch(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.close_conn_patcher = patch(+ "products.web_analytics.backend.temporal.weekly_digest.activities.close_old_connections"+ )+ self.close_conn_patcher.start()++ def tearDown(self):+ self.close_conn_patcher.stop()+ super().tearDown()++ def test_aggregates_per_org_results(self):+ results_by_org = {+ "1": OrgDigestCounts(+ sent=2,+ skipped_optout=1,+ team_count=3,+ build_duration=0.4,+ send_duration=0.2,+ ),+ "2": OrgDigestCounts(+ skipped_no_data=5,+ failed=1,+ team_count=1,+ build_duration=0.1,+ send_duration=0.05,+ ),+ "3": OrgDigestCounts(skipped_reason="no_teams"),+ }++ with patch(+ "products.web_analytics.backend.temporal.weekly_digest.activities._build_and_send_for_org",+ side_effect=lambda org_id, dry_run: results_by_org[org_id],+ ):+ totals = _run_wa_digest_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.emails_sent == 2+ assert totals.emails_skipped_optout == 1+ assert totals.emails_skipped_no_data == 5+ assert totals.emails_failed == 1++ def test_isolates_per_org_failures(self):+ def fake_build_and_send(org_id, dry_run):+ if org_id == "2":+ raise RuntimeError("clickhouse exploded for org 2")+ return OrgDigestCounts(sent=1, team_count=1)++ with patch(+ "products.web_analytics.backend.temporal.weekly_digest.activities._build_and_send_for_org",+ side_effect=fake_build_and_send,+ ):+ totals = _run_wa_digest_batch(DigestBatchInput(org_ids=["1", "2", "3"]))++ assert totals.orgs_processed == 2+ assert totals.orgs_failed == 1+ assert totals.emails_sent == 2++ def test_failure_rate_excludes_skipped_orgs(self):+ with patch(+ "products.web_analytics.backend.temporal.weekly_digest.activities._build_and_send_for_org",+ side_effect=lambda org_id, dry_run: OrgDigestCounts(skipped_reason="no_teams"),+ ):+ totals = _run_wa_digest_batch(DigestBatchInput(org_ids=["1", "2", "3"]))++ assert totals.orgs_skipped == 3+ assert totals.orgs_failed == 0+ assert totals.failure_rate == 0.0++ @parameterized.expand(+ [+ ("all_skipped", {"batch_size": 100, "orgs_skipped": 100}, 0.0),+ ("all_failed", {"batch_size": 10, "orgs_failed": 10}, 1.0),+ ("mixed_skip_and_fail", {"batch_size": 100, "orgs_skipped": 90, "orgs_failed": 10}, 1.0),+ (+ "mixed_processed_and_failed",+ {"batch_size": 10, "orgs_processed": 8, "orgs_failed": 2},+ 0.2,+ ),+ (+ "skipped_does_not_dilute",+ {"batch_size": 100, "orgs_processed": 1, "orgs_skipped": 98, "orgs_failed": 1},+ 0.5,+ ),+ ("empty", {}, 0.0),+ ]+ )+ def test_failure_rate_denominator_excludes_skipped(self, _name, fields, expected):+ result = DigestBatchResult(**fields)+ assert result.failure_rate == expected++ def test_aggregates_email_attribution_via_real_build_and_send(self):+ opted_out = User.objects.create_user(email="[email protected]", password="x", first_name="Out")+ opted_out.partial_notification_settings = {"web_analytics_weekly_digest": False}+ opted_out.save()+ OrganizationMembership.objects.create(+ organization=self.organization,+ user=opted_out,+ level=OrganizationMembership.Level.MEMBER,+ )++ with (+ patch(+ "products.web_analytics.backend.temporal.weekly_digest.activities.posthoganalytics.feature_enabled",+ return_value=True,+ ),+ patch(+ "products.web_analytics.backend.temporal.weekly_digest.activities.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,+ ):+ mock_email_class.return_value = MagicMock()+ totals = _run_wa_digest_batch(DigestBatchInput(org_ids=[str(self.organization.id)]))++ assert totals.orgs_processed == 1+ assert totals.emails_sent == 1+ assert totals.emails_skipped_optout == 1diff --git a/products/web_analytics/backend/test/test_weekly_digest_workflows.py b/products/web_analytics/backend/test/test_weekly_digest_workflows.pynew file mode 100644index 000000000000..700a89433074--- /dev/null+++ b/products/web_analytics/backend/test/test_weekly_digest_workflows.py@@ -0,0 +1,264 @@+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.weekly_digest.types import (+ WA_DIGEST_THRESHOLD_EXCEEDED_TYPE,+ DigestBatchInput,+ DigestBatchResult,+ WAWeeklyDigestInput,+)+from products.web_analytics.backend.temporal.weekly_digest.workflows import WAWeeklyDigestWorkflow+++def _empty_batch_result(batch_size: int) -> DigestBatchResult:+ return DigestBatchResult(batch_size=batch_size, orgs_processed=batch_size)+++async def test_wa_weekly_digest_returns_early_when_no_batches() -> None:+ @activity.defn(name="wa-digest-get-org-batches")+ async def _get_batches(input: WAWeeklyDigestInput) -> list[list[str]]:+ return []++ @activity.defn(name="wa-digest-run-batch")+ async def _run_batch(input: DigestBatchInput) -> DigestBatchResult:+ raise AssertionError("should not be called when there are no batches")++ @activity.defn(name="wa-digest-push-metrics")+ async def _push_metrics(totals_dict: dict, success: bool) -> None:+ raise AssertionError("should not push metrics when there is no work")++ task_queue = str(uuid.uuid4())+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue=task_queue,+ workflows=[WAWeeklyDigestWorkflow],+ activities=[_get_batches, _run_batch, _push_metrics],+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),+ ):+ result = await env.client.execute_workflow(+ WAWeeklyDigestWorkflow.run,+ WAWeeklyDigestInput(dry_run=True),+ id=str(uuid.uuid4()),+ task_queue=task_queue,+ )++ assert result == {"orgs": 0, "batches": 0}+++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), (500, 25, 8)])+async def test_wa_weekly_digest_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-get-org-batches")+ async def _get_batches(input: WAWeeklyDigestInput) -> list[list[str]]:+ return expected_batches++ @activity.defn(name="wa-digest-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 _empty_batch_result(len(input.org_ids))++ metric_pushes: list[tuple[dict, bool]] = []++ @activity.defn(name="wa-digest-push-metrics")+ async def _push_metrics(totals_dict: dict, success: bool) -> None:+ metric_pushes.append((totals_dict, success))++ task_queue = str(uuid.uuid4())+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue=task_queue,+ workflows=[WAWeeklyDigestWorkflow],+ activities=[_get_batches, _run_batch, _push_metrics],+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),+ max_concurrent_activities=org_count,+ ):+ await env.client.execute_workflow(+ WAWeeklyDigestWorkflow.run,+ WAWeeklyDigestInput(+ 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"+ )+ assert len(metric_pushes) == 1+ assert metric_pushes[0][1] is True+++async def test_wa_weekly_digest_threshold_exceeded_raises_and_pushes_failure_metric() -> None:+ org_ids = [f"org-{i}" for i in range(20)]+ batches = [org_ids]++ @activity.defn(name="wa-digest-get-org-batches")+ async def _get_batches(input: WAWeeklyDigestInput) -> list[list[str]]:+ return batches++ @activity.defn(name="wa-digest-run-batch")+ async def _run_batch(input: DigestBatchInput) -> DigestBatchResult:+ # Half the orgs fail — well above the 0.2 default threshold.+ return DigestBatchResult(+ batch_size=len(input.org_ids),+ orgs_processed=len(input.org_ids) // 2,+ orgs_failed=len(input.org_ids) // 2,+ )++ metric_pushes: list[tuple[dict, bool]] = []++ @activity.defn(name="wa-digest-push-metrics")+ async def _push_metrics(totals_dict: dict, success: bool) -> None:+ metric_pushes.append((totals_dict, success))++ task_queue = str(uuid.uuid4())+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue=task_queue,+ workflows=[WAWeeklyDigestWorkflow],+ activities=[_get_batches, _run_batch, _push_metrics],+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),+ ):+ with pytest.raises(Exception) as exc_info:+ await env.client.execute_workflow(+ WAWeeklyDigestWorkflow.run,+ WAWeeklyDigestInput(dry_run=True),+ id=str(uuid.uuid4()),+ task_queue=task_queue,+ )++ # Workflow raises ApplicationError(type=WADigestThresholdExceeded). Temporal+ # wraps it in WorkflowFailureError; the cause carries the ApplicationError.+ cause = exc_info.value.__cause__+ assert cause is not None and getattr(cause, "type", None) == WA_DIGEST_THRESHOLD_EXCEEDED_TYPE, (+ f"Expected ApplicationError type={WA_DIGEST_THRESHOLD_EXCEEDED_TYPE}, got {type(cause).__name__}: {cause}"+ )+ assert len(metric_pushes) == 1+ assert metric_pushes[0][1] is False, "metrics push should report success=False when threshold is exceeded"+++async def test_wa_weekly_digest_aggregates_totals_across_batches() -> None:+ batches_input = [["org-a", "org-b"], ["org-c"]]++ @activity.defn(name="wa-digest-get-org-batches")+ async def _get_batches(input: WAWeeklyDigestInput) -> list[list[str]]:+ return batches_input++ @activity.defn(name="wa-digest-run-batch")+ async def _run_batch(input: DigestBatchInput) -> DigestBatchResult:+ return DigestBatchResult(+ batch_size=len(input.org_ids),+ orgs_processed=len(input.org_ids),+ emails_sent=len(input.org_ids) * 3,+ emails_skipped_optout=len(input.org_ids),+ build_duration=0.5,+ send_duration=0.25,+ )++ @activity.defn(name="wa-digest-push-metrics")+ async def _push_metrics(totals_dict: dict, success: bool) -> None:+ return None++ task_queue = str(uuid.uuid4())+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue=task_queue,+ workflows=[WAWeeklyDigestWorkflow],+ activities=[_get_batches, _run_batch, _push_metrics],+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),+ ):+ result = await env.client.execute_workflow(+ WAWeeklyDigestWorkflow.run,+ WAWeeklyDigestInput(dry_run=True),+ id=str(uuid.uuid4()),+ task_queue=task_queue,+ )++ assert result["orgs"] == 3+ assert result["batches"] == 2+ assert result["emails_sent"] == 9 # (2 + 1) * 3+ assert result["failed_batches"] == 0+++async def test_wa_weekly_digest_does_not_raise_when_only_skipped() -> None:+ # Regression guard: legitimate pre-processing skips (no targeted members,+ # no teams) must not trip the threshold. Only orgs_failed counts.+ org_ids = [f"org-{i}" for i in range(20)]+ batches = [org_ids]++ @activity.defn(name="wa-digest-get-org-batches")+ async def _get_batches(input: WAWeeklyDigestInput) -> list[list[str]]:+ return batches++ @activity.defn(name="wa-digest-run-batch")+ async def _run_batch(input: DigestBatchInput) -> DigestBatchResult:+ return DigestBatchResult(+ batch_size=len(input.org_ids),+ orgs_skipped=len(input.org_ids),+ )++ metric_pushes: list[tuple[dict, bool]] = []++ @activity.defn(name="wa-digest-push-metrics")+ async def _push_metrics(totals_dict: dict, success: bool) -> None:+ metric_pushes.append((totals_dict, success))++ task_queue = str(uuid.uuid4())+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue=task_queue,+ workflows=[WAWeeklyDigestWorkflow],+ activities=[_get_batches, _run_batch, _push_metrics],+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),+ ):+ result = await env.client.execute_workflow(+ WAWeeklyDigestWorkflow.run,+ WAWeeklyDigestInput(dry_run=True),+ id=str(uuid.uuid4()),+ task_queue=task_queue,+ )++ assert result["orgs"] == 20+ assert metric_pushes[0][1] is True, "all-skipped is not a failure — success metric should be True"