:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(error-tracking): add temporal weekly digest workflow (#72738)
Aleksander Błaszkiewiczd34aecdd13af
diff --git a/.github/workflows/container-images-cd.yml b/.github/workflows/container-images-cd.ymlindex 105bfa94ec38..fb1b291b36b2 100644--- a/.github/workflows/container-images-cd.yml+++ b/.github/workflows/container-images-cd.yml@@ -510,8 +510,12 @@ jobs:filters: |changed:- 'products/error_tracking/backend/temporal/**'- - 'products/error_tracking/backend/recommendations/**'+ - 'products/error_tracking/backend/logic/**'- 'products/error_tracking/backend/models.py'+ - 'products/error_tracking/backend/weekly_digest.py'+ - 'products/error_tracking/backend/indexed_embedding.py'+ - 'posthog/tasks/email.py'+ - 'posthog/tasks/email_utils.py'- 'posthog/temporal/common/**'- 'posthog/temporal/schedule.py'- 'posthog/settings/temporal.py'diff --git a/posthog/management/commands/execute_temporal_workflow.py b/posthog/management/commands/execute_temporal_workflow.pyindex 3cf9c69cc652..d8a6afc2e37c 100644--- a/posthog/management/commands/execute_temporal_workflow.py+++ b/posthog/management/commands/execute_temporal_workflow.py@@ -30,6 +30,7 @@ from posthog.temporal.usage_report import WORKFLOWS as USAGE_REPORTS_WORKFLOWSfrom posthog.temporal.weekly_digest import WORKFLOWS as WEEKLY_DIGEST_WORKFLOWSfrom products.batch_exports.backend.temporal import WORKFLOWS as BATCH_EXPORT_WORKFLOWS+from products.error_tracking.backend.facade.temporal import WORKFLOWS as ERROR_TRACKING_WORKFLOWSfrom products.logs.backend.temporal.retention_entitlements import WORKFLOWS as LOGS_RETENTION_ENTITLEMENTS_WORKFLOWSfrom products.warehouse_sources.backend.facade.temporal import WORKFLOWS as DATA_IMPORT_WORKFLOWSfrom products.web_analytics.backend.temporal import WORKFLOWS as WA_DIGEST_WORKFLOWS@@ -157,6 +158,7 @@ class Command(BaseCommand):+ RASTERIZE_RECORDING_WORKFLOWS+ SUMMARIZATION_SWEEP_WORKFLOWS+ WA_DIGEST_WORKFLOWS+ + ERROR_TRACKING_WORKFLOWS+ SURFACING_SCORING_SWEEP_WORKFLOWS+ BACKFILL_GROUP_TYPE_CREATED_AT_WORKFLOWS)diff --git a/posthog/management/commands/start_temporal_workflow.py b/posthog/management/commands/start_temporal_workflow.pyindex 27cd41f99f45..2c7ed8206495 100644--- a/posthog/management/commands/start_temporal_workflow.py+++ b/posthog/management/commands/start_temporal_workflow.py@@ -30,6 +30,7 @@ from posthog.temporal.usage_report import WORKFLOWS as USAGE_REPORTS_WORKFLOWSfrom posthog.temporal.weekly_digest import WORKFLOWS as WEEKLY_DIGEST_WORKFLOWSfrom products.batch_exports.backend.temporal import WORKFLOWS as BATCH_EXPORT_WORKFLOWS+from products.error_tracking.backend.facade.temporal import WORKFLOWS as ERROR_TRACKING_WORKFLOWSfrom products.logs.backend.temporal.retention_entitlements import WORKFLOWS as LOGS_RETENTION_ENTITLEMENTS_WORKFLOWSfrom products.warehouse_sources.backend.facade.temporal import WORKFLOWS as DATA_IMPORT_WORKFLOWSfrom products.web_analytics.backend.temporal import WORKFLOWS as WA_DIGEST_WORKFLOWS@@ -159,6 +160,7 @@ class Command(BaseCommand):+ HEALTH_CHECK_WORKFLOWS+ LOGS_RETENTION_ENTITLEMENTS_WORKFLOWS+ WA_DIGEST_WORKFLOWS+ + ERROR_TRACKING_WORKFLOWS+ SURFACING_SCORING_SWEEP_WORKFLOWS)try:diff --git a/posthog/tasks/email.py b/posthog/tasks/email.pyindex 6f41bd8a2123..a0c1ea4a3a01 100644--- a/posthog/tasks/email.py+++ b/posthog/tasks/email.py@@ -2058,21 +2058,33 @@ def send_error_tracking_weekly_digest_for_org(self: Task, org_id: str) -> None:if not should_send_notification(user, NotificationSetting.ERROR_TRACKING_WEEKLY_DIGEST.value):continue- if error_tracking_api.auto_select_project_for_user(user, org.id, autoselect_counts):+ # One instance per user: its membership and access-control prefetches are cached on the+ # instance, so rebuilding it per team would re-query them for every team in the org.+ user_permissions = UserPermissions(user)+ accessible_team_ids = {+ team_id+ for team_id in team_ids_with_exceptions+ if user_permissions.team(all_org_teams[team_id]).effective_membership_level_for_parent_membership(+ org, membership+ )+ is not None+ }++ # Rank only projects this member can open. Auto-select is one-shot and persisted, so enrolling+ # someone onto a project they can't reach leaves every other project disabled-by-omission and+ # silences their digest for good.+ if error_tracking_api.auto_select_project_for_user(+ user, org.id, {tid: counts for tid, counts in autoselect_counts.items() if tid in accessible_team_ids}+ ):user.refresh_from_db(fields=["partial_notification_settings"])enabled_team_ids: list[int] = []disabled_team_names: list[str] = []- for team_id in team_ids_with_exceptions:- team = all_org_teams[team_id]- user_permissions = UserPermissions(user).team(team)- if user_permissions.effective_membership_level_for_parent_membership(org, membership) is None:- continue-+ for team_id in accessible_team_ids:if should_send_notification(user, NotificationSetting.ERROR_TRACKING_WEEKLY_DIGEST.value, team_id):enabled_team_ids.append(team_id)else:- disabled_team_names.append(team.name)+ disabled_team_names.append(all_org_teams[team_id].name)if enabled_team_ids:recipients.append((membership, enabled_team_ids, disabled_team_names))diff --git a/posthog/tasks/email_utils.py b/posthog/tasks/email_utils.pyindex 0bcb327ee3e5..ac37e5954610 100644--- a/posthog/tasks/email_utils.py+++ b/posthog/tasks/email_utils.py@@ -7,10 +7,13 @@ def auto_select_digest_project(team_data: dict[int, dict],setting_key: str,sort_key: Callable[[dict], float],+ persist: bool = True,) -> bool:"""Auto-select the busiest project for first-time digest users.- Returns True if settings were updated (caller should refresh_from_db).+ Returns True if settings were written to the database (caller should refresh_from_db).+ ``persist=False`` applies the selection to the in-memory user only, so a simulated run does+ not consume the one-shot enrollment."""from posthog.models.user import User@@ -23,6 +26,10 @@ def auto_select_digest_project(busiest_team_id = max(team_data, key=lambda tid: sort_key(team_data[tid]))current_settings[setting_key] = {str(busiest_team_id): True}+ if not persist:+ user.partial_notification_settings = current_settings+ return False+User.objects.filter(pk=user.pk).update(partial_notification_settings=current_settings)return Truediff --git a/products/error_tracking/backend/facade/temporal.py b/products/error_tracking/backend/facade/temporal.pyindex 9b2d2ef1e1e0..e85d51521654 100644--- a/products/error_tracking/backend/facade/temporal.py+++ b/products/error_tracking/backend/facade/temporal.py@@ -14,6 +14,7 @@ from products.error_tracking.backend.temporal.spike_event_cleanup.schedule imporfrom products.error_tracking.backend.temporal.symbol_set_cleanup.schedule import (create_error_tracking_symbol_set_cleanup_schedule,)+from products.error_tracking.backend.temporal.weekly_digest.schedule import create_error_tracking_weekly_digest_schedule__all__ = ["ACTIVITIES",@@ -23,4 +24,5 @@ __all__ = ["RecommendationsRefreshInputs","create_error_tracking_spike_event_cleanup_schedule","create_error_tracking_symbol_set_cleanup_schedule",+ "create_error_tracking_weekly_digest_schedule",]diff --git a/products/error_tracking/backend/temporal/__init__.py b/products/error_tracking/backend/temporal/__init__.pyindex b66e81083713..ab620da4d16a 100644--- a/products/error_tracking/backend/temporal/__init__.py+++ b/products/error_tracking/backend/temporal/__init__.py@@ -30,18 +30,27 @@ from products.error_tracking.backend.temporal.symbol_set_cleanup import (ErrorTrackingSymbolSetCleanupWorkflow,cleanup_symbol_sets_activity,)+from products.error_tracking.backend.temporal.weekly_digest import (+ ACTIVITIES as WEEKLY_DIGEST_ACTIVITIES,+ WORKFLOWS as WEEKLY_DIGEST_WORKFLOWS,+ ErrorTrackingWeeklyDigestWorkflow,+ get_digest_orgs_activity,+ send_org_digest_activity,+)WORKFLOWS = (SYMBOL_SET_WORKFLOWS+ SPIKE_EVENT_WORKFLOWS+ RECOMMENDATIONS_REFRESH_WORKFLOWS+ FINGERPRINT_EMBEDDING_RESULT_WORKFLOWS+ + WEEKLY_DIGEST_WORKFLOWS)ACTIVITIES = (SYMBOL_SET_ACTIVITIES+ SPIKE_EVENT_ACTIVITIES+ RECOMMENDATIONS_REFRESH_ACTIVITIES+ FINGERPRINT_EMBEDDING_RESULT_ACTIVITIES+ + WEEKLY_DIGEST_ACTIVITIES)__all__ = [@@ -56,9 +65,12 @@ __all__ = ["ErrorTrackingRecommendationsRefreshWorkflow","ErrorTrackingSpikeEventCleanupWorkflow","ErrorTrackingSymbolSetCleanupWorkflow",+ "ErrorTrackingWeeklyDigestWorkflow","cleanup_spike_events_activity","cleanup_symbol_sets_activity",+ "get_digest_orgs_activity","get_team_batches_activity","merge_similar_fingerprints_activity","refresh_recommendations_batch_activity",+ "send_org_digest_activity",]diff --git a/products/error_tracking/backend/temporal/weekly_digest/__init__.py b/products/error_tracking/backend/temporal/weekly_digest/__init__.pynew file mode 100644index 000000000000..f90679245eb5--- /dev/null+++ b/products/error_tracking/backend/temporal/weekly_digest/__init__.py@@ -0,0 +1,16 @@+from products.error_tracking.backend.temporal.weekly_digest.activities import (+ get_digest_orgs_activity,+ send_org_digest_activity,+)+from products.error_tracking.backend.temporal.weekly_digest.workflow import ErrorTrackingWeeklyDigestWorkflow++WORKFLOWS = [ErrorTrackingWeeklyDigestWorkflow]+ACTIVITIES = [get_digest_orgs_activity, send_org_digest_activity]++__all__ = [+ "ACTIVITIES",+ "WORKFLOWS",+ "ErrorTrackingWeeklyDigestWorkflow",+ "get_digest_orgs_activity",+ "send_org_digest_activity",+]diff --git a/products/error_tracking/backend/temporal/weekly_digest/activities.py b/products/error_tracking/backend/temporal/weekly_digest/activities.pynew file mode 100644index 000000000000..342c535fef3c--- /dev/null+++ b/products/error_tracking/backend/temporal/weekly_digest/activities.py@@ -0,0 +1,299 @@+from django.conf import settings+from django.db import close_old_connections+from django.utils import timezone++import structlog+from temporalio import activity+from temporalio.exceptions import ApplicationError++from posthog.cloud_utils import is_cloud+from posthog.models import Organization, OrganizationMembership, Team+from posthog.models.messaging import MessagingRecord+from posthog.tasks.email import NotificationSetting, should_send_notification+from posthog.temporal.common.heartbeat_sync import HeartbeaterSync+from posthog.user_permissions import UserPermissions++from products.error_tracking.backend import weekly_digest+from products.error_tracking.backend.temporal.weekly_digest.types import (+ GetDigestOrgsInputs,+ SendOrgDigestInputs,+ SendOrgDigestResult,+)++logger = structlog.get_logger(__name__)+++def _get_digest_orgs(inputs: GetDigestOrgsInputs) -> list[str]:+ """Resolve one keyset page of org ids for this run.++ An explicit ``org_ids`` (manual targeted runs) bypasses discovery; scheduled runs+ discover every org with exceptions.++ The candidate set is sorted and sliced to (``after``, ``after`` + ``limit``] so the+ workflow can page with only a cursor. Recomputing candidates each page is safe: an+ org shifting in or out between pages is either <= cursor (already processed) or+ > cursor (still pending), never both.+ """+ # Checked before org_ids so a targeted manual run can't route around the cloud gate. Returning+ # no orgs is what keeps the send activity from being scheduled at all.+ if not is_cloud():+ logger.info("Skipping Error Tracking weekly digest outside PostHog Cloud")+ return []++ if inputs.org_ids is not None:+ candidates = sorted(str(org_id) for org_id in inputs.org_ids)+ else:+ candidates = sorted(str(org_id) for org_id in weekly_digest.get_org_ids_with_exceptions())++ if inputs.after is not None:+ candidates = [org_id for org_id in candidates if org_id > inputs.after]+ return candidates[: inputs.limit]+++def get_digest_orgs_activity(inputs: GetDigestOrgsInputs) -> list[str]:+ close_old_connections()+ return _get_digest_orgs(inputs)+++def _send_org_digest(inputs: SendOrgDigestInputs, attempt: int) -> SendOrgDigestResult:+ """Send one combined weekly error tracking digest per user in an org via the delivery workflow.++ ``attempt`` is Temporal's 1-based attempt counter; ``attempt >= inputs.max_attempts`` marks+ the final attempt, which sends partial digests instead of deferring recipients.+ """+ org_id = inputs.org_id+ try:+ org = Organization.objects.get(id=org_id)+ except Organization.DoesNotExist:+ logger.warning(f"Organization {org_id} not found for Error Tracking weekly digest")+ return SendOrgDigestResult()++ all_org_teams = {t.id: t for t in Team.objects.filter(organization_id=org.id)}+ if not all_org_teams:+ return SendOrgDigestResult()++ # Which teams have any exceptions at all — one ClickHouse query for the whole org.+ unfiltered_counts = weekly_digest.get_exception_counts(list(all_org_teams.keys()))+ team_ids_with_exceptions = {row[0] for row in unfiltered_counts if row[0] in all_org_teams}+ if not team_ids_with_exceptions:+ return SendOrgDigestResult()++ memberships: list[OrganizationMembership] = list(+ OrganizationMembership.objects.prefetch_related("user").filter(organization_id=org.id)+ )++ # First-time users are auto-enrolled onto their busiest project. Ranking must use test-account-filtered+ # counts: unfiltered counts can permanently enroll a user onto a project whose digest builds empty+ # (auto-select is a one-shot decision). Only computed when the org actually has a first-time user.+ setting_key = weekly_digest.DIGEST_PROJECT_SETTING_KEY+ autoselect_counts: dict[int, dict] = {}+ # Kept for Pass 2: the 14-day row query is the most expensive thing this activity does, so a team+ # ranked here shouldn't pay for it again when its digest is built.+ daily_rows_by_team: dict[int, list] = {}+ if any(setting_key not in (m.user.partial_notification_settings or {}) for m in memberships):+ for tid in team_ids_with_exceptions:+ daily_rows_by_team[tid] = weekly_digest.query_daily_rows(all_org_teams[tid])+ summary = weekly_digest.get_exception_summary_for_team(all_org_teams[tid], daily_rows_by_team[tid])+ if summary and summary["exception_count"] > 0:+ autoselect_counts[tid] = summary++ # Pass 1 — resolve each recipient's enabled teams from notification settings + project access only (no+ # ClickHouse). This yields the set of teams at least one recipient will actually receive, so Pass 2 builds+ # heavy digest data for those alone instead of for every team in the org that happens to have exceptions.+ recipients: list[tuple[OrganizationMembership, list[int], list[str]]] = []+ needed_team_ids: set[int] = set()+ for membership in memberships:+ user = membership.user++ if not should_send_notification(user, NotificationSetting.ERROR_TRACKING_WEEKLY_DIGEST.value):+ continue++ # One instance per user: its membership and access-control prefetches are cached on the+ # instance, so rebuilding it per team would re-query them for every team in the org.+ user_permissions = UserPermissions(user)+ accessible_team_ids = {+ team_id+ for team_id in team_ids_with_exceptions+ if user_permissions.team(all_org_teams[team_id]).effective_membership_level_for_parent_membership(+ org, membership+ )+ is not None+ }++ # Rank only projects this member can open. Auto-select is one-shot and persisted, so enrolling+ # someone onto a project they can't reach leaves every other project disabled-by-omission and+ # silences their digest for good. A dry run only simulates it, so it can't consume the enrollment.+ if weekly_digest.auto_select_project_for_user(+ user,+ org.id,+ {tid: counts for tid, counts in autoselect_counts.items() if tid in accessible_team_ids},+ persist=not inputs.dry_run,+ ):+ user.refresh_from_db(fields=["partial_notification_settings"])++ enabled_team_ids: list[int] = []+ disabled_team_names: list[str] = []+ for team_id in accessible_team_ids:+ if should_send_notification(user, NotificationSetting.ERROR_TRACKING_WEEKLY_DIGEST.value, team_id):+ enabled_team_ids.append(team_id)+ else:+ disabled_team_names.append(all_org_teams[team_id].name)++ if enabled_team_ids:+ recipients.append((membership, enabled_team_ids, disabled_team_names))+ needed_team_ids.update(enabled_team_ids)++ date_suffix = timezone.now().strftime("%Y-%W")++ if not needed_team_ids:+ logger.info(f"Sent Error Tracking weekly digest to 0 members for org {org_id} (no subscribed recipients)")+ return SendOrgDigestResult()++ # Pass 2 — build digest data only for teams a recipient has enabled. A team whose build fails is+ # recorded in failed_team_ids; recipients not subscribed to it are unaffected, while those who are+ # get held back for the retry (see is_final_attempt below). The activity re-raises at the end so+ # Temporal retries it.+ team_digest_data: dict[int, dict] = {}+ failed_team_ids: list[int] = []+ for team_id in needed_team_ids:+ try:+ data = weekly_digest.build_team_digest_data(all_org_teams[team_id], daily_rows_by_team.get(team_id))+ except Exception:+ logger.exception("et_weekly_digest.team_build_failed", team_id=team_id, org_id=org_id)+ failed_team_ids.append(team_id)+ continue+ if data:+ team_digest_data[team_id] = data++ # Org projects not represented as a section this week: no exceptions, no data after test-account+ # filtering, or a failed build. Teams a recipient disabled are named in their disabled list instead,+ # so they must not be counted here.+ excluded_project_count = (+ len(all_org_teams) - len(team_ids_with_exceptions) + (len(needed_team_ids) - len(team_digest_data))+ )++ # On non-final attempts, hold back a recipient whose digest is missing a team that failed to build+ # this run. The retry re-runs the build, so a transient failure still delivers their full digest.+ # Only once retries are exhausted do we fall back to sending the partial, so a permanently-broken+ # team can't starve a recipient of their healthy teams. Recipients not subscribed to a failed team+ # are unaffected and send immediately.+ failed_team_id_set = set(failed_team_ids)+ is_final_attempt = attempt >= inputs.max_attempts++ sent_count = 0+ failed_count = 0+ deferred_count = 0+ lacking_sent_count = 0+ already_sent_count = 0++ for membership, enabled_team_ids, disabled_team_names in recipients:+ user = membership.user++ user_team_sections = [team_digest_data[team_id] for team_id in enabled_team_ids if team_id in team_digest_data]+ if not user_team_sections:+ continue++ # Teams the recipient subscribes to that failed to build this run: a non-empty list means their+ # digest is "lacking" those sections. Defer them off the final attempt; on it, send the partial.+ missing_failed_team_ids = [team_id for team_id in enabled_team_ids if team_id in failed_team_id_set]+ if not is_final_attempt and missing_failed_team_ids:+ deferred_count += 1+ continue++ user_team_sections.sort(key=lambda d: d["exception_count"], reverse=True)++ distinct_id = user.distinct_id or str(user.uuid)+ digest = {+ "recipient_email": user.email,+ "org_name": org.name,+ "project_sections": [weekly_digest.build_team_section_payload(d) for d in user_team_sections],+ "disabled_project_names": disabled_team_names,+ "excluded_project_count": excluded_project_count,+ "settings_url": f"{settings.SITE_URL}/settings/user-notifications?highlight=et-weekly-digest",+ "feedback_survey_url": f"https://us.posthog.com/external_surveys/019c7fd6-7cfa-0000-2b03-a8e5d4c03743?distinct_id={distinct_id}",+ }++ if inputs.dry_run:+ logger.info(+ "et_weekly_digest.dry_run_send",+ org_id=org_id,+ user_id=str(user.uuid),+ teams=len(user_team_sections),+ )+ sent_count += 1+ continue++ campaign_key = f"error_tracking_weekly_digest_{org_id}_{user.uuid}_{date_suffix}"+ # Claim the recipient before handing the digest to the workflow, not after. The send is an+ # irreversible external call, so writing sent_at afterwards leaves a window where a failed+ # commit rolls the marker back and the retry sends the same digest twice. Claiming first+ # inverts that: releasing the claim on a failed send keeps the retry working, and a crash+ # between the two costs one missed digest rather than a duplicate.+ record, _ = MessagingRecord.objects.get_or_create(raw_email=user.email, campaign_key=campaign_key)+ claimed = MessagingRecord.objects.filter(pk=record.pk, sent_at__isnull=True).update(sent_at=timezone.now())+ if not claimed:+ already_sent_count += 1+ continue++ try:+ weekly_digest.send_digest_to_workflow(digest, distinct_id)+ except Exception:+ logger.exception("et_weekly_digest.send_failed", user_id=str(user.uuid), org_id=org_id)+ MessagingRecord.objects.filter(pk=record.pk).update(sent_at=None)+ failed_count += 1+ continue++ sent_count += 1+ if missing_failed_team_ids:+ # A lacking digest actually went out (final-attempt fallback): the recipient is missing+ # these teams because their builds kept failing. Grep this event to audit lacking sends.+ lacking_sent_count += 1+ logger.warning(+ "et_weekly_digest.lacking_digest_sent",+ org_id=org_id,+ user_id=str(user.uuid),+ missing_team_ids=missing_failed_team_ids,+ teams_sent=len(user_team_sections),+ )++ # Temporal only hands the workflow the final attempt's return value, so sent_count alone would lose+ # everything earlier attempts sent, down to zero for an org whose retry sends nothing new.+ sent_total = sent_count + already_sent_count++ # Every field except sent_total describes this attempt alone.+ logger.info(+ "et_weekly_digest.org_complete",+ org_id=org_id,+ attempt=attempt,+ is_final_attempt=is_final_attempt,+ dry_run=inputs.dry_run,+ sent=sent_count,+ already_sent=already_sent_count,+ sent_total=sent_total,+ lacking_sent=lacking_sent_count,+ teams_built=len(team_digest_data),+ team_builds_failed=len(failed_team_ids),+ failed_team_ids=failed_team_ids,+ send_failures=failed_count,+ deferred=deferred_count,+ )++ if failed_count or failed_team_ids:+ # Trigger a Temporal retry; already-sent recipients are skipped via MessagingRecord, and+ # recipients missing a failed team were deferred above so the retry can complete them.+ # sent_total rides in the details because a raising activity returns no result.+ raise ApplicationError(+ f"Error Tracking weekly digest failed for {failed_count} recipients "+ f"and {len(failed_team_ids)} team builds in org {org_id}",+ sent_total,+ )++ return SendOrgDigestResult(sent=sent_total, teams_built=len(team_digest_data))+++def send_org_digest_activity(inputs: SendOrgDigestInputs) -> SendOrgDigestResult:+ close_old_connections()+ with HeartbeaterSync(logger=logger):+ return _send_org_digest(inputs, attempt=activity.info().attempt)diff --git a/products/error_tracking/backend/temporal/weekly_digest/schedule.py b/products/error_tracking/backend/temporal/weekly_digest/schedule.pynew file mode 100644index 000000000000..2a89af6fb265--- /dev/null+++ b/products/error_tracking/backend/temporal/weekly_digest/schedule.py@@ -0,0 +1,56 @@+from datetime import timedelta++from django.conf import settings++from temporalio import common+from temporalio.client import (+ Client,+ Schedule,+ ScheduleActionStartWorkflow,+ ScheduleCalendarSpec,+ ScheduleOverlapPolicy,+ SchedulePolicy,+ ScheduleRange,+ ScheduleSpec,+)++from posthog.temporal.common.schedule import a_create_schedule, a_schedule_exists, a_update_schedule++from products.error_tracking.backend.temporal.weekly_digest.types import WeeklyDigestInputs+from products.error_tracking.backend.temporal.weekly_digest.workflow import WORKFLOW_NAME++SCHEDULE_ID = "error-tracking-weekly-digest-schedule"+# Fire late if Temporal was down over the Monday-morning slot, but never roll a+# missed week into the next: digest queries anchor on now(), so a day-late run+# would report a shifted window.+SCHEDULE_CATCHUP_WINDOW = timedelta(hours=6)+++async def create_error_tracking_weekly_digest_schedule(client: Client) -> None:+ weekly_digest_schedule = Schedule(+ action=ScheduleActionStartWorkflow(+ WORKFLOW_NAME,+ # dry_run defaults to True as a manual-run fail-safe; the schedule is the+ # one caller that must send for real.+ WeeklyDigestInputs(dry_run=False),+ id=SCHEDULE_ID,+ task_queue=settings.ERROR_TRACKING_TASK_QUEUE,+ retry_policy=common.RetryPolicy(maximum_attempts=1),+ ),+ spec=ScheduleSpec(+ calendars=[+ ScheduleCalendarSpec(+ comment="Mondays at 08:30 UTC",+ day_of_week=[ScheduleRange(start=1, end=1)],+ hour=[ScheduleRange(start=8, end=8)],+ minute=[ScheduleRange(start=30, end=30)],+ )+ ]+ ),+ policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP, catchup_window=SCHEDULE_CATCHUP_WINDOW),+ )++ if await a_schedule_exists(client, SCHEDULE_ID):+ await a_update_schedule(client, SCHEDULE_ID, weekly_digest_schedule)+ else:+ await a_create_schedule(client, SCHEDULE_ID, weekly_digest_schedule, trigger_immediately=False)diff --git a/products/error_tracking/backend/temporal/weekly_digest/test/test_weekly_digest_schedule.py b/products/error_tracking/backend/temporal/weekly_digest/test/test_weekly_digest_schedule.pynew file mode 100644index 000000000000..019be9630b7b--- /dev/null+++ b/products/error_tracking/backend/temporal/weekly_digest/test/test_weekly_digest_schedule.py@@ -0,0 +1,91 @@+import pytest+from unittest.mock import AsyncMock, patch++from django.conf import settings++from temporalio.client import ScheduleActionStartWorkflow, ScheduleCalendarSpec, ScheduleOverlapPolicy, ScheduleRange++from products.error_tracking.backend.temporal.weekly_digest.schedule import (+ SCHEDULE_CATCHUP_WINDOW,+ SCHEDULE_ID,+ create_error_tracking_weekly_digest_schedule,+)+from products.error_tracking.backend.temporal.weekly_digest.types import WeeklyDigestInputs+from products.error_tracking.backend.temporal.weekly_digest.workflow import WORKFLOW_NAME+++def schedule_helpers():+ with (+ patch(+ "products.error_tracking.backend.temporal.weekly_digest.schedule.a_create_schedule",+ new_callable=AsyncMock,+ ) as create,+ patch(+ "products.error_tracking.backend.temporal.weekly_digest.schedule.a_update_schedule",+ new_callable=AsyncMock,+ ) as update,+ patch(+ "products.error_tracking.backend.temporal.weekly_digest.schedule.a_schedule_exists",+ new_callable=AsyncMock,+ ) as exists,+ ):+ yield {"create": create, "update": update, "exists": exists}+++def mock_client():+ return object()+++def assert_weekly_digest_schedule(schedule) -> None:+ assert isinstance(schedule.action, ScheduleActionStartWorkflow)+ assert schedule.action.workflow == WORKFLOW_NAME+ # The scheduled run is the one caller that must send for real: dry_run defaults to+ # True everywhere else as a manual-run fail-safe.+ assert schedule.action.args == [WeeklyDigestInputs(dry_run=False)]+ assert schedule.action.id == SCHEDULE_ID+ assert schedule.action.task_queue == settings.ERROR_TRACKING_TASK_QUEUE+ assert schedule.action.retry_policy is not None+ assert schedule.action.retry_policy.maximum_attempts == 1+ assert schedule.policy is not None+ assert schedule.policy.overlap == ScheduleOverlapPolicy.SKIP+ assert schedule.policy.catchup_window == SCHEDULE_CATCHUP_WINDOW+ assert schedule.spec.calendars == [+ ScheduleCalendarSpec(+ comment="Mondays at 08:30 UTC",+ day_of_week=[ScheduleRange(start=1, end=1)],+ hour=[ScheduleRange(start=8, end=8)],+ minute=[ScheduleRange(start=30, end=30)],+ )+ ]+++class TestCreateErrorTrackingWeeklyDigestSchedule:+ @pytest.mark.asyncio+ async def test_creates_weekly_schedule_when_missing(self, mock_client, schedule_helpers) -> None:+ schedule_helpers["exists"].return_value = False++ await create_error_tracking_weekly_digest_schedule(mock_client)++ schedule_helpers["create"].assert_awaited_once()+ schedule_helpers["update"].assert_not_called()+ client, schedule_id, schedule = schedule_helpers["create"].call_args.args+ assert client is mock_client+ assert schedule_id == SCHEDULE_ID+ assert schedule_helpers["create"].call_args.kwargs["trigger_immediately"] is False++ assert_weekly_digest_schedule(schedule)++ @pytest.mark.asyncio+ async def test_updates_existing_schedule(self, mock_client, schedule_helpers) -> None:+ schedule_helpers["exists"].return_value = True++ await create_error_tracking_weekly_digest_schedule(mock_client)++ schedule_helpers["create"].assert_not_called()+ schedule_helpers["update"].assert_awaited_once()+ client, schedule_id, schedule = schedule_helpers["update"].call_args.args+ assert client is mock_client+ assert schedule_id == SCHEDULE_ID+ assert_weekly_digest_schedule(schedule)diff --git a/products/error_tracking/backend/temporal/weekly_digest/test/test_weekly_digest_temporal.py b/products/error_tracking/backend/temporal/weekly_digest/test/test_weekly_digest_temporal.pynew file mode 100644index 000000000000..d4ce19075d4e--- /dev/null+++ b/products/error_tracking/backend/temporal/weekly_digest/test/test_weekly_digest_temporal.py@@ -0,0 +1,550 @@+import json+import uuid+import asyncio+import dataclasses+from collections import Counter+from datetime import timedelta+from uuid import uuid4++import pytest+from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person, flush_persons_and_events+from unittest.mock import patch++from django.test import SimpleTestCase, override_settings+from django.utils import timezone++from parameterized import parameterized+from temporalio import activity+from temporalio.exceptions import ApplicationError+from temporalio.testing import WorkflowEnvironment+from temporalio.worker import UnsandboxedWorkflowRunner, Worker++from posthog.constants import AvailableFeature+from posthog.models import OrganizationMembership, Team, User+from posthog.models.messaging import MessagingRecord+from posthog.models.utils import uuid7++from products.error_tracking.backend.models import (+ ErrorTrackingIssue,+ ErrorTrackingIssueFingerprintV2,+ sync_issues_to_clickhouse,+)+from products.error_tracking.backend.temporal.weekly_digest.activities import _get_digest_orgs, _send_org_digest+from products.error_tracking.backend.temporal.weekly_digest.types import (+ GetDigestOrgsInputs,+ SendOrgDigestInputs,+ SendOrgDigestResult,+ WeeklyDigestInputs,+ WeeklyDigestResult,+)+from products.error_tracking.backend.temporal.weekly_digest.workflow import (+ FAILED_ORGS_ERROR_TYPE,+ ErrorTrackingWeeklyDigestWorkflow,+)+from products.error_tracking.backend.weekly_digest import build_team_digest_data++from ee.clickhouse.materialized_columns.columns import materialize+from ee.models.rbac.access_control import AccessControl++_WEBHOOK_POST = "products.error_tracking.backend.weekly_digest.requests.post"+_BUILD_TEAM_DIGEST_DATA = "products.error_tracking.backend.weekly_digest.build_team_digest_data"+_IS_CLOUD = "products.error_tracking.backend.temporal.weekly_digest.activities.is_cloud"+++def _days_ago(n: int) -> str:+ return (timezone.now() - timedelta(days=n)).isoformat()+++@override_settings(CLOUD_DEPLOYMENT="US")+class TestGetDigestOrgs(SimpleTestCase):+ def test_explicit_org_ids_bypass_discovery(self):+ with patch("products.error_tracking.backend.weekly_digest.get_org_ids_with_exceptions") as mock_discover:+ assert _get_digest_orgs(GetDigestOrgsInputs(org_ids=["org-x"])) == ["org-x"]+ mock_discover.assert_not_called()++ def test_cloud_scheduled_run_returns_all_orgs_with_exceptions(self):+ with patch(+ "products.error_tracking.backend.weekly_digest.get_org_ids_with_exceptions",+ return_value=["org-a", "org-b"],+ ):+ assert _get_digest_orgs(GetDigestOrgsInputs()) == ["org-a", "org-b"]++ @parameterized.expand(+ [+ ("first_page", None, 2, ["org-a", "org-b"]),+ ("cursor_is_exclusive", "org-b", 2, ["org-c"]),+ ("cursor_between_ids_skips_nothing", "org-aa", 2, ["org-b", "org-c"]),+ ("past_the_end", "org-z", 2, []),+ ]+ )+ def test_keyset_page_bounds(self, _name, after, limit, expected):+ # Unsorted input: paging correctness depends on the activity sorting before slicing.+ inputs = GetDigestOrgsInputs(org_ids=["org-c", "org-a", "org-b"], after=after, limit=limit)+ assert _get_digest_orgs(inputs) == expected++ @parameterized.expand([("scheduled", None), ("targeted_manual_run", ["org-x"])])+ def test_self_hosted_run_is_a_noop(self, _name, org_ids):+ # Explicit org ids are the manual-run path and must not route around the cloud gate.+ with (+ patch(_IS_CLOUD, return_value=False),+ patch("products.error_tracking.backend.weekly_digest.get_org_ids_with_exceptions") as mock_discover,+ ):+ assert _get_digest_orgs(GetDigestOrgsInputs(org_ids=org_ids)) == []+ mock_discover.assert_not_called()+++# send_digest_to_workflow refuses to send outside Cloud, so the send path needs cloud mode.+@override_settings(CLOUD_DEPLOYMENT="US")+class TestSendOrgDigest(ClickhouseTestMixin, APIBaseTest):+ @classmethod+ def setUpTestData(cls):+ super().setUpTestData()+ materialize("events", "$exception_issue_id", is_nullable=True)++ def _run(self, attempt: int = 1, dry_run: bool = False) -> SendOrgDigestResult:+ return _send_org_digest(SendOrgDigestInputs(org_id=str(self.organization.id), dry_run=dry_run), attempt=attempt)++ def test_activity_posts_json_safe_digest_and_dedupes_on_retry(self):+ issue = ErrorTrackingIssue.objects.create(+ id=uuid7(), team=self.team, status=ErrorTrackingIssue.Status.ACTIVE, name="TestError"+ )+ fingerprint = str(uuid4())+ ErrorTrackingIssueFingerprintV2.objects.create(team=self.team, issue=issue, fingerprint=fingerprint)+ sync_issues_to_clickhouse(issue_ids=[issue.id], team_id=self.team.pk)+ _create_event(+ distinct_id="user_1",+ event="$exception",+ team=self.team,+ properties={"$exception_issue_id": str(issue.id), "$exception_fingerprint": fingerprint},+ timestamp=_days_ago(1),+ )+ flush_persons_and_events()++ self.user.partial_notification_settings = {+ "error_tracking_weekly_digest_project_enabled": {str(self.team.id): True}+ }+ self.user.save()++ with patch(_WEBHOOK_POST) as mock_post:+ result = self._run()++ assert mock_post.call_count == 1+ url = mock_post.call_args.args[0] if mock_post.call_args.args else mock_post.call_args.kwargs["url"]+ assert url == "https://webhooks.us.posthog.com/public/webhooks/019f2754-aeff-0000-6a0d-5d3933a94b08"++ payload = mock_post.call_args.kwargs["json"]+ json.dumps(payload) # the workflow webhook only accepts JSON-serializable payloads+ assert payload["event"] == "error_tracking_weekly_digest"+ assert payload["distinct_id"] == self.user.distinct_id++ digest = payload["digest"]+ assert digest["recipient_email"] == self.user.email+ assert digest["org_name"] == self.organization.name+ section = digest["project_sections"][0]+ assert section["team_name"] == self.team.name+ assert section["exception_count"] == "1"+ assert section["top_issues"][0]["id"] == str(issue.id)+ assert section["top_issues"][0]["occurrence_count"] == "1"+ # The email template branches on `ingestion_failure_count > 0`, so it+ # must stay numeric; the formatted value ships as the display twin.+ assert section["ingestion_failure_count"] == 0+ assert section["ingestion_failure_count_display"] == "0"+ assert "team" not in section+ assert result == SendOrgDigestResult(sent=1, teams_built=1)++ # Retry of the org activity must not send the same campaign twice (MessagingRecord dedupe),+ # but it still reports what attempt 1 sent, since only the last attempt's result is surfaced.+ retry_result = self._run(attempt=2)+ assert mock_post.call_count == 1+ assert retry_result == SendOrgDigestResult(sent=1, teams_built=1)++ def _create_second_team_with_exception(self, name: str = "Team B") -> Team:+ team_b = Team.objects.create(organization=self.organization, name=name)+ _create_event(+ distinct_id="user_b",+ event="$exception",+ team=team_b,+ properties={},+ timestamp=_days_ago(1),+ )+ return team_b++ def test_dry_run_builds_but_sends_nothing(self):+ _create_event(distinct_id="user_a", event="$exception", team=self.team, properties={}, timestamp=_days_ago(1))+ flush_persons_and_events()++ self.user.partial_notification_settings = {+ "error_tracking_weekly_digest_project_enabled": {str(self.team.id): True}+ }+ self.user.save()++ with patch(_WEBHOOK_POST) as mock_post:+ result = self._run(dry_run=True)++ assert mock_post.call_count == 0+ assert result == SendOrgDigestResult(sent=1, teams_built=1)+ assert not MessagingRecord.objects.filter(sent_at__isnull=False).exists()++ @parameterized.expand([("eligible_role", "engineering", 1), ("ineligible_role", "marketing", 0)])+ def test_dry_run_simulates_auto_select_without_enrolling(self, _name, role, expected_sent):+ # Auto-select is one-shot, so a dry run that wrote it would change what the next real run sends.+ _create_event(distinct_id="user_a", event="$exception", team=self.team, properties={}, timestamp=_days_ago(1))+ flush_persons_and_events()++ self.user.role_at_organization = role+ self.user.save()++ with patch(_WEBHOOK_POST) as mock_post:+ result = self._run(dry_run=True)++ assert mock_post.call_count == 0+ assert result.sent == expected_sent++ self.user.refresh_from_db()+ assert "error_tracking_weekly_digest_project_enabled" not in (self.user.partial_notification_settings or {})++ def test_auto_select_uses_filtered_counts(self):+ # Team A has more raw exceptions, but all from internal users; team B has one real exception.+ # A first-time user must be enrolled onto B, not onto A whose digest builds empty.+ self.team.test_account_filters = [+ {"key": "email", "type": "person", "operator": "not_icontains", "value": "@internal.com"}+ ]+ self.team.save()+ _create_person(distinct_ids=["internal_user"], properties={"email": "[email protected]"}, team=self.team)+ for _ in range(5):+ _create_event(+ distinct_id="internal_user", event="$exception", team=self.team, properties={}, timestamp=_days_ago(1)+ )+ team_b = self._create_second_team_with_exception()+ flush_persons_and_events()++ self.user.role_at_organization = "engineering"+ self.user.save()++ with patch(_WEBHOOK_POST):+ self._run()++ self.user.refresh_from_db()+ project_enabled = (self.user.partial_notification_settings or {}).get(+ "error_tracking_weekly_digest_project_enabled", {}+ )+ assert project_enabled == {str(team_b.pk): True}++ def test_auto_select_skips_the_busiest_project_the_user_cannot_access(self):+ # self.team is the busiest but private to a plain member. Enrolling them onto it would leave every+ # other project disabled-by-omission, and auto-select is one-shot, so their digest would stop for good.+ for _ in range(5):+ _create_event(+ distinct_id="user_a", event="$exception", team=self.team, properties={}, timestamp=_days_ago(1)+ )+ team_b = self._create_second_team_with_exception()+ flush_persons_and_events()++ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}+ ]+ self.organization.save()+ self.organization_membership.level = OrganizationMembership.Level.MEMBER+ self.organization_membership.save()+ AccessControl.objects.create(+ team=self.team, resource="project", resource_id=str(self.team.id), access_level="none"+ )++ self.user.role_at_organization = "engineering"+ self.user.save()++ with patch(_WEBHOOK_POST) as mock_post:+ self._run()++ self.user.refresh_from_db()+ project_enabled = (self.user.partial_notification_settings or {}).get(+ "error_tracking_weekly_digest_project_enabled", {}+ )+ assert project_enabled == {str(team_b.pk): True}+ sections = mock_post.call_args.kwargs["json"]["digest"]["project_sections"]+ assert [s["team_name"] for s in sections] == [team_b.name]++ def test_recipient_missing_a_failed_team_is_deferred_while_others_send(self):+ # self.team's build fails this run; team_b's succeeds.+ _create_event(distinct_id="user_a", event="$exception", team=self.team, properties={}, timestamp=_days_ago(1))+ team_b = self._create_second_team_with_exception()+ flush_persons_and_events()++ # Subscribed to both teams: their digest is incomplete this run, so it must be held for the retry+ # rather than shipped as a partial that gets stamped and never completed.+ self.user.partial_notification_settings = {+ "error_tracking_weekly_digest_project_enabled": {str(self.team.pk): True, str(team_b.pk): True}+ }+ self.user.save()++ # Subscribed to the healthy team only: unaffected by the unrelated failure, sends immediately.+ other = User.objects.create_and_join(self.organization, "[email protected]", None)+ other.partial_notification_settings = {"error_tracking_weekly_digest_project_enabled": {str(team_b.pk): True}}+ other.save()++ def build_or_fail(team, daily_rows=None):+ if team.pk == self.team.pk:+ raise Exception("ClickHouse query failed")+ return build_team_digest_data(team, daily_rows)++ with (+ patch(_BUILD_TEAM_DIGEST_DATA, side_effect=build_or_fail),+ patch(_WEBHOOK_POST) as mock_post,+ ):+ with pytest.raises(Exception, match="team builds"):+ self._run()++ # Only the healthy-team-only recipient was sent; the incomplete recipient was deferred, not sent a partial.+ recipients = [c.kwargs["json"]["digest"]["recipient_email"] for c in mock_post.call_args_list]+ assert recipients == [other.email]+ # The deferred recipient must not be stamped, so the retry can still deliver their complete digest.+ assert not MessagingRecord.objects.filter(+ campaign_key__contains=str(self.user.uuid), sent_at__isnull=False+ ).exists()++ def test_deferred_recipient_gets_full_digest_when_build_recovers_on_retry(self):+ _create_event(distinct_id="user_a", event="$exception", team=self.team, properties={}, timestamp=_days_ago(1))+ team_b = self._create_second_team_with_exception()+ flush_persons_and_events()++ self.user.partial_notification_settings = {+ "error_tracking_weekly_digest_project_enabled": {str(self.team.pk): True, str(team_b.pk): True}+ }+ self.user.save()++ fail_team_a = {"on": True}++ def build_or_recover(team, daily_rows=None):+ if team.pk == self.team.pk and fail_team_a["on"]:+ raise Exception("ClickHouse query failed")+ return build_team_digest_data(team, daily_rows)++ with (+ patch(_BUILD_TEAM_DIGEST_DATA, side_effect=build_or_recover),+ patch(_WEBHOOK_POST) as mock_post,+ ):+ # Attempt 1: team A build fails, so the recipient is deferred and the activity raises to retry.+ with pytest.raises(Exception, match="team builds"):+ self._run(attempt=1)+ assert mock_post.call_count == 0++ # Attempt 2 (retry): team A now builds. Because attempt 1 never stamped the recipient, they+ # are not deduped away and receive their complete digest — the whole point of the deferral.+ fail_team_a["on"] = False+ self._run(attempt=2)++ assert mock_post.call_count == 1+ sections = mock_post.call_args.kwargs["json"]["digest"]["project_sections"]+ assert {s["team_name"] for s in sections} == {self.team.name, team_b.name}++ def test_final_attempt_sends_partial_to_recipient_with_permanently_failing_team(self):+ _create_event(distinct_id="user_a", event="$exception", team=self.team, properties={}, timestamp=_days_ago(1))+ team_b = self._create_second_team_with_exception()+ flush_persons_and_events()++ self.user.partial_notification_settings = {+ "error_tracking_weekly_digest_project_enabled": {str(self.team.pk): True, str(team_b.pk): True}+ }+ self.user.save()++ def build_or_fail(team, daily_rows=None):+ if team.pk == self.team.pk:+ raise Exception("ClickHouse query failed")+ return build_team_digest_data(team, daily_rows)++ with (+ patch(_BUILD_TEAM_DIGEST_DATA, side_effect=build_or_fail),+ patch(_WEBHOOK_POST) as mock_post,+ ):+ # Final attempt (attempt == max_attempts): fall back to delivering the healthy teams rather+ # than starving the recipient of a digest entirely. The activity still raises for visibility.+ with pytest.raises(ApplicationError, match="team builds") as exc_info:+ self._run(attempt=6)++ assert mock_post.call_count == 1+ sections = mock_post.call_args.kwargs["json"]["digest"]["project_sections"]+ assert [s["team_name"] for s in sections] == [team_b.name]+ # A raising activity returns no result, so the count only reaches the workflow via details.+ assert list(exc_info.value.details) == [1]++ def test_disabled_team_not_counted_as_excluded(self):+ _create_event(distinct_id="user_a", event="$exception", team=self.team, properties={}, timestamp=_days_ago(1))+ team_b = self._create_second_team_with_exception()+ flush_persons_and_events()++ self.user.partial_notification_settings = {+ "error_tracking_weekly_digest_project_enabled": {str(self.team.pk): True, str(team_b.pk): False}+ }+ self.user.save()++ with patch(_WEBHOOK_POST) as mock_post:+ self._run()++ digest = mock_post.call_args.kwargs["json"]["digest"]+ assert digest["disabled_project_names"] == [team_b.name]+ assert digest["excluded_project_count"] == 0+++class _FanOutTracker:+ in_flight: int = 0+ max_in_flight: int = 0+ inputs_seen: list[SendOrgDigestInputs] = dataclasses.field(default_factory=list)+++class TestErrorTrackingWeeklyDigestWorkflow:+ async def _execute(self, workflow_inputs, activities, max_concurrent_activities: int = 16):+ task_queue = str(uuid.uuid4())+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue=task_queue,+ workflows=[ErrorTrackingWeeklyDigestWorkflow],+ activities=activities,+ workflow_runner=UnsandboxedWorkflowRunner(),+ max_concurrent_activities=max_concurrent_activities,+ ):+ return await env.client.execute_workflow(+ ErrorTrackingWeeklyDigestWorkflow.run,+ workflow_inputs,+ id=str(uuid.uuid4()),+ task_queue=task_queue,+ )++ @pytest.mark.asyncio+ async def test_completes_without_fanout_when_no_orgs(self):+ @activity.defn(name="get_digest_orgs_activity")+ async def _get_orgs(inputs: GetDigestOrgsInputs) -> list[str]:+ return []++ @activity.defn(name="send_org_digest_activity")+ async def _send(inputs: SendOrgDigestInputs) -> SendOrgDigestResult:+ raise AssertionError("should not fan out when there are no orgs")++ result = await self._execute(WeeklyDigestInputs(), [_get_orgs, _send])+ assert result == WeeklyDigestResult(orgs=0, orgs_failed=0, sent=0)++ @pytest.mark.asyncio+ async def test_fans_out_with_concurrency_cap_and_plumbs_inputs(self):+ org_ids = [f"org-{i}" for i in range(10)]+ tracker = _FanOutTracker()+ state_lock = asyncio.Lock()++ @activity.defn(name="get_digest_orgs_activity")+ async def _get_orgs(inputs: GetDigestOrgsInputs) -> list[str]:+ return org_ids++ @activity.defn(name="send_org_digest_activity")+ async def _send(inputs: SendOrgDigestInputs) -> SendOrgDigestResult:+ async with state_lock:+ tracker.in_flight += 1+ tracker.max_in_flight = max(tracker.max_in_flight, tracker.in_flight)+ tracker.inputs_seen.append(inputs)+ try:+ await asyncio.sleep(0.01)+ finally:+ async with state_lock:+ tracker.in_flight -= 1+ return SendOrgDigestResult(sent=2, teams_built=1)++ result = await self._execute(+ WeeklyDigestInputs(dry_run=True, max_concurrent=3, max_attempts=4),+ [_get_orgs, _send],+ max_concurrent_activities=len(org_ids),+ )++ assert {i.org_id for i in tracker.inputs_seen} == set(org_ids)+ assert all(i.dry_run and i.max_attempts == 4 for i in tracker.inputs_seen)+ assert tracker.max_in_flight <= 3, (+ f"workflow scheduled {tracker.max_in_flight} org activities concurrently "+ f"but max_concurrent=3 — semaphore fan-out guard is missing"+ )+ assert result == WeeklyDigestResult(orgs=10, orgs_failed=0, sent=20)++ @pytest.mark.asyncio+ async def test_raises_after_processing_all_orgs_when_one_fails(self):+ org_ids = ["org-a", "org-b", "org-c"]+ sent_orgs: set[str] = set()+ inputs_seen: list[SendOrgDigestInputs] = []++ @activity.defn(name="get_digest_orgs_activity")+ async def _get_orgs(inputs: GetDigestOrgsInputs) -> list[str]:+ return org_ids++ @activity.defn(name="send_org_digest_activity")+ async def _send(inputs: SendOrgDigestInputs) -> SendOrgDigestResult:+ inputs_seen.append(inputs)+ if inputs.org_id == "org-b":+ raise ApplicationError("org exhausted retries", 3, non_retryable=True)+ sent_orgs.add(inputs.org_id)+ return SendOrgDigestResult(sent=1, teams_built=1)++ # No input at all — the shape of a manual Temporal UI run. It must fall back to+ # defaults, and those defaults must be a dry run.+ with pytest.raises(Exception) as exc_info:+ await self._execute(None, [_get_orgs, _send])++ # Workflow raises ApplicationError(type=FAILED_ORGS_ERROR_TYPE). 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) == FAILED_ORGS_ERROR_TYPE+ # org-a and org-c sent 1 each, org-b sent 3 before exhausting its retries. Dropping the+ # failed org's count would report 2.+ assert "5 digests sent" in str(cause)+ # The failed org must not prevent the other orgs from being processed.+ assert sent_orgs == {"org-a", "org-c"}+ # An input-less run can never send for real; only the schedule passes dry_run=False.+ assert all(i.dry_run for i in inputs_seen)++ @pytest.mark.asyncio+ async def test_pages_through_all_orgs_via_continue_as_new(self):+ org_ids = sorted(f"org-{i}" for i in range(25))+ cursors_seen: list[str | None] = []+ seen: list[str] = []++ @activity.defn(name="get_digest_orgs_activity")+ async def _get_orgs(inputs: GetDigestOrgsInputs) -> list[str]:+ cursors_seen.append(inputs.after)+ candidates = org_ids if inputs.after is None else [o for o in org_ids if o > inputs.after]+ return candidates[: inputs.limit]++ @activity.defn(name="send_org_digest_activity")+ async def _send(inputs: SendOrgDigestInputs) -> SendOrgDigestResult:+ seen.append(inputs.org_id)+ return SendOrgDigestResult(sent=1, teams_built=1)++ result = await self._execute(WeeklyDigestInputs(page_size=10), [_get_orgs, _send])++ # One discovery call per page, each carrying the previous page's last org id as+ # the cursor; every org is processed exactly once across the continued executions.+ assert cursors_seen == [None, org_ids[9], org_ids[19]]+ assert Counter(seen) == Counter(org_ids)+ assert result == WeeklyDigestResult(orgs=25, orgs_failed=0, sent=25)++ @pytest.mark.asyncio+ async def test_failure_in_early_page_is_carried_to_the_final_execution(self):+ # Exact multiple of page_size: the chain must end via the empty trailing page+ # without dropping carried failures or totals.+ org_ids = sorted(f"org-{i}" for i in range(20))+ seen: list[str] = []++ @activity.defn(name="get_digest_orgs_activity")+ async def _get_orgs(inputs: GetDigestOrgsInputs) -> list[str]:+ candidates = org_ids if inputs.after is None else [o for o in org_ids if o > inputs.after]+ return candidates[: inputs.limit]++ @activity.defn(name="send_org_digest_activity")+ async def _send(inputs: SendOrgDigestInputs) -> SendOrgDigestResult:+ seen.append(inputs.org_id)+ if inputs.org_id == "org-3":+ raise ApplicationError("org exhausted retries", non_retryable=True)+ return SendOrgDigestResult(sent=1, teams_built=1)++ with pytest.raises(Exception) as exc_info:+ await self._execute(WeeklyDigestInputs(page_size=10), [_get_orgs, _send])++ cause = exc_info.value.__cause__+ assert cause is not None and getattr(cause, "type", None) == FAILED_ORGS_ERROR_TYPE+ # A failure in page 1 must not stop later pages: the chain drains fully and+ # only the final execution reports the carried failure.+ assert Counter(seen) == Counter(org_ids)diff --git a/products/error_tracking/backend/temporal/weekly_digest/types.py b/products/error_tracking/backend/temporal/weekly_digest/types.pynew file mode 100644index 000000000000..1ee900177900--- /dev/null+++ b/products/error_tracking/backend/temporal/weekly_digest/types.py@@ -0,0 +1,64 @@+import dataclasses++[email protected](frozen=True)+class WeeklyDigestInputs:+ # dry_run builds digests without POSTing to the delivery workflow or stamping+ # MessagingRecords. It defaults to True so an input-less manual run (e.g. from the+ # Temporal UI) can never send real digests — only the registered schedule and+ # deliberate manual runs pass dry_run=False. org_ids bypasses discovery for+ # targeted manual runs.+ dry_run: bool = True+ org_ids: list[str] | None = None+ # How many per-org activities run at once (bounds ClickHouse load and webhook rate).+ max_concurrent: int = 10+ # Total executions per org activity: initial run + 5 retries. The final attempt sends+ # partial digests instead of deferring recipients whose teams failed to build.+ max_attempts: int = 6+ # Orgs handled per workflow execution. Each page runs in its own execution (chained via+ # continue_as_new) so history stays bounded no matter how many orgs are discovered.+ page_size: int = 1000+ # Continue-as-new carried state — never set by callers. cursor is the last org id of+ # the previous page (keyset paging: only this ~40-byte cursor rides between executions,+ # never the org list, so org count can't approach the 2 MiB payload cap); the carried_*+ # counters accumulate across the chain so the final execution can report and fail on+ # the whole run.+ cursor: str | None = None+ carried_orgs: int = 0+ carried_orgs_failed: int = 0+ carried_sent: int = 0++[email protected](frozen=True)+class GetDigestOrgsInputs:+ org_ids: list[str] | None = None+ # Keyset page bounds: return at most ``limit`` org ids, sorted, strictly greater+ # than ``after``. The candidate set is recomputed each call; sorting makes paging+ # stable so an org can never be returned in two pages.+ after: str | None = None+ limit: int = 1000++[email protected](frozen=True)+class SendOrgDigestInputs:+ org_id: str+ # Fail-safe default, matching WeeklyDigestInputs: the workflow always passes it explicitly.+ dry_run: bool = True+ # Must equal the activity's RetryPolicy.maximum_attempts — an activity cannot read its own+ # retry policy, and final-attempt detection (attempt >= max_attempts) depends on it.+ max_attempts: int = 6++[email protected](frozen=True)+class SendOrgDigestResult:+ # Across every attempt, not just the one that returned this result: Temporal surfaces only the+ # final attempt's return value.+ sent: int = 0+ teams_built: int = 0++[email protected](frozen=True)+class WeeklyDigestResult:+ orgs: int+ orgs_failed: int+ sent: intdiff --git a/products/error_tracking/backend/temporal/weekly_digest/workflow.py b/products/error_tracking/backend/temporal/weekly_digest/workflow.pynew file mode 100644index 000000000000..fbb4623f3f83--- /dev/null+++ b/products/error_tracking/backend/temporal/weekly_digest/workflow.py@@ -0,0 +1,138 @@+import asyncio+import dataclasses+from datetime import timedelta++from temporalio import common, workflow+from temporalio.exceptions import ApplicationError++from posthog.temporal.common.base import PostHogWorkflow++with workflow.unsafe.imports_passed_through():+ from products.error_tracking.backend.temporal.weekly_digest.activities import (+ get_digest_orgs_activity,+ send_org_digest_activity,+ )+ from products.error_tracking.backend.temporal.weekly_digest.types import (+ GetDigestOrgsInputs,+ SendOrgDigestInputs,+ SendOrgDigestResult,+ WeeklyDigestInputs,+ WeeklyDigestResult,+ )++WORKFLOW_NAME = "error-tracking-weekly-digest"++FAILED_ORGS_ERROR_TYPE = "ErrorTrackingWeeklyDigestOrgsFailed"++GET_ORGS_RETRY_POLICY = common.RetryPolicy(maximum_attempts=3, initial_interval=timedelta(seconds=30))+GET_ORGS_TIMEOUT = timedelta(minutes=5)++SEND_ORG_START_TO_CLOSE_TIMEOUT = timedelta(minutes=30)+SEND_ORG_HEARTBEAT_TIMEOUT = timedelta(minutes=5)+SEND_ORG_INITIAL_RETRY_INTERVAL = timedelta(seconds=30)+SEND_ORG_MAXIMUM_RETRY_INTERVAL = timedelta(minutes=5)+++def _sent_from_error(error: BaseException) -> int:+ """Digests a failed org still sent, as carried in the activity's ApplicationError details.++ Returns 0 for failures that carry no count, such as a timeout or a crash outside the activity's+ own error path.+ """+ details = getattr(getattr(error, "cause", None), "details", None) or ()+ return details[0] if details and isinstance(details[0], int) else 0++[email protected](name=WORKFLOW_NAME)+class ErrorTrackingWeeklyDigestWorkflow(PostHogWorkflow):+ inputs_cls = WeeklyDigestInputs+ inputs_optional = True++ @workflow.run+ async def run(self, inputs: WeeklyDigestInputs | None = None) -> WeeklyDigestResult:+ if inputs is None:+ inputs = WeeklyDigestInputs()++ # One keyset page per execution: only the ~40-byte cursor rides through+ # continue_as_new, so neither history nor payload size grows with org count.+ page = await workflow.execute_activity(+ get_digest_orgs_activity,+ GetDigestOrgsInputs(org_ids=inputs.org_ids, after=inputs.cursor, limit=inputs.page_size),+ start_to_close_timeout=GET_ORGS_TIMEOUT,+ retry_policy=GET_ORGS_RETRY_POLICY,+ )++ # Keep up to max_concurrent per-org activities in flight at all times: the semaphore+ # releases the moment one finishes, so the next org starts immediately rather than+ # waiting for a whole wave to drain.+ semaphore = asyncio.Semaphore(inputs.max_concurrent)++ async def send_org(org_id: str) -> SendOrgDigestResult:+ async with semaphore:+ return await workflow.execute_activity(+ send_org_digest_activity,+ SendOrgDigestInputs(org_id=org_id, dry_run=inputs.dry_run, max_attempts=inputs.max_attempts),+ start_to_close_timeout=SEND_ORG_START_TO_CLOSE_TIMEOUT,+ heartbeat_timeout=SEND_ORG_HEARTBEAT_TIMEOUT,+ retry_policy=common.RetryPolicy(+ # Must match SendOrgDigestInputs.max_attempts — final-attempt detection+ # inside the activity depends on the two agreeing.+ maximum_attempts=inputs.max_attempts,+ initial_interval=SEND_ORG_INITIAL_RETRY_INTERVAL,+ backoff_coefficient=2.0,+ maximum_interval=SEND_ORG_MAXIMUM_RETRY_INTERVAL,+ ),+ )++ results = await asyncio.gather(*(send_org(org_id) for org_id in page), return_exceptions=True)++ sent = inputs.carried_sent+ orgs_failed = inputs.carried_orgs_failed+ for org_id, result in zip(page, results):+ if isinstance(result, BaseException):+ orgs_failed += 1+ sent += _sent_from_error(result)+ workflow.logger.error(+ "Error Tracking weekly digest org failed after retries",+ extra={"org_id": org_id, "error": str(result)},+ )+ continue+ sent += result.sent++ orgs = inputs.carried_orgs + len(page)++ # A full page may hide more orgs behind it; only a short page proves the set is+ # drained. An exact-multiple total costs one extra execution that gets an empty+ # page and finishes with the carried totals.+ if page and len(page) == inputs.page_size:+ workflow.logger.info(+ "Error Tracking weekly digest page complete, continuing as new",+ extra={"orgs_so_far": orgs, "cursor": page[-1], "orgs_failed": orgs_failed, "sent": sent},+ )+ workflow.continue_as_new(+ dataclasses.replace(+ inputs,+ cursor=page[-1],+ carried_orgs=orgs,+ carried_orgs_failed=orgs_failed,+ carried_sent=sent,+ )+ )++ if not orgs:+ workflow.logger.info("No orgs for Error Tracking weekly digest")++ workflow.logger.info(+ "Error Tracking weekly digest run complete",+ extra={"orgs": orgs, "orgs_failed": orgs_failed, "sent": sent, "dry_run": inputs.dry_run},+ )++ if orgs_failed:+ raise ApplicationError(+ f"Error Tracking weekly digest failed for {orgs_failed}/{orgs} orgs "+ f"({sent} digests sent, including partial sends from the failed orgs)",+ type=FAILED_ORGS_ERROR_TYPE,+ non_retryable=True,+ )++ return WeeklyDigestResult(orgs=orgs, orgs_failed=orgs_failed, sent=sent)diff --git a/products/error_tracking/backend/test/test_weekly_digest.py b/products/error_tracking/backend/test/test_weekly_digest.pyindex e79af7e25fce..ab2cdeba7105 100644--- a/products/error_tracking/backend/test/test_weekly_digest.py+++ b/products/error_tracking/backend/test/test_weekly_digest.py@@ -599,7 +599,15 @@ class TestSourceMapsRecommendationForDigest(APIBaseTest):assert get_source_maps_recommendation_for_team(other_team) is None+@override_settings(CLOUD_DEPLOYMENT="US")class TestSendDigestToWorkflow(SimpleTestCase):+ @override_settings(CLOUD_DEPLOYMENT=None)+ def test_refuses_to_send_from_a_self_hosted_deployment(self):+ with patch("products.error_tracking.backend.weekly_digest.requests.post") as mock_post:+ with pytest.raises(RuntimeError, match="self-hosted"):+ send_digest_to_workflow({"recipient_email": "[email protected]"}, "distinct-1")+ assert mock_post.call_count == 0+def test_raises_on_non_2xx_so_failures_are_not_marked_sent(self):with patch("products.error_tracking.backend.weekly_digest.requests.post") as mock_post:mock_post.return_value.raise_for_status.side_effect = requests.HTTPError(@@ -615,6 +623,7 @@ class TestSendDigestToWorkflow(SimpleTestCase):assert mock_post.call_args.kwargs["headers"] == {"Authorization": "Bearer test-token"}+@override_settings(CLOUD_DEPLOYMENT="US")class TestWeeklyDigestWorkflowDelivery(ClickhouseTestMixin, APIBaseTest):@classmethoddef setUpTestData(cls):diff --git a/products/error_tracking/backend/weekly_digest.py b/products/error_tracking/backend/weekly_digest.pyindex c28e7596bec0..5692c59bd085 100644--- a/products/error_tracking/backend/weekly_digest.py+++ b/products/error_tracking/backend/weekly_digest.py@@ -10,6 +10,7 @@ import structlogfrom posthog.schema import HogQLFiltersfrom posthog.clickhouse.query_tagging import tag_queries+from posthog.cloud_utils import is_cloudfrom posthog.models import Teamfrom posthog.schema_enums import ProductKeyfrom posthog.utils import compact_number@@ -33,7 +34,7 @@ def get_org_ids_with_exceptions() -> list[str]:return org_ids-def _query_daily_rows(team: Team) -> list:+def query_daily_rows(team: Team) -> list:"""Per-day counts over 14 days. Explicit LIMIT: HogQL appends LIMIT 100 to unlimited selects.Missing ``$exception_issue_id`` = ingestion failure. Query errors propagate so the task retries@@ -41,6 +42,8 @@ def _query_daily_rows(team: Team) -> list:"""from posthog.hogql.query import execute_hogql_query+ from posthog.clickhouse.workload import Workload+tag_queries(product=ProductKey.ERROR_TRACKING, team_id=team.pk, name="weekly_digest:daily_rows")response = execute_hogql_query(@@ -60,6 +63,8 @@ def _query_daily_rows(team: Team) -> list:""",team=team,filters=HogQLFilters(filterTestAccounts=True),+ # Weekly batch job: Celery pinned this to the offline cluster process-wide, Temporal does not.+ workload=Workload.OFFLINE,)return response.results or []@@ -67,7 +72,7 @@ def _query_daily_rows(team: Team) -> list:def get_exception_summary_for_team(team: Team, daily_rows: list | None = None) -> dict:"""Exception counts, ingestion failures, and previous-week count. This week = 1-7 days ago, previous = 8-14."""if daily_rows is None:- daily_rows = _query_daily_rows(team)+ daily_rows = query_daily_rows(team)if not daily_rows:return {}@@ -93,19 +98,28 @@ def get_exception_summary_for_team(team: Team, daily_rows: list | None = None) -ELIGIBLE_ROLES_FOR_AUTO_DIGEST = {"engineering", "data", "founder"}+# Per-project opt-in map inside User.partial_notification_settings. Mirrors the entry for this+# notification type in posthog.tasks.email._DIGEST_PROJECT_SETTING_KEYS, which is module-private.+DIGEST_PROJECT_SETTING_KEY = "error_tracking_weekly_digest_project_enabled"+-def auto_select_project_for_user(user: Any, org_id: int, team_exception_counts: dict[int, dict]) -> bool:+def auto_select_project_for_user(+ user: Any, org_id: int, team_exception_counts: dict[int, dict], persist: bool = True+) -> bool:"""For first-time users who have no ET digest project settings, auto-select the project with the most exceptionsand persist the selection to their notification settings.Only auto-enrolls users with engineering, data, or founder roles. Users with other roles(marketing, sales, leadership, product, other, None) are marked as "processed" with an emptyproject map so auto-selection doesn't run again - they can still opt in manually via settings.++ ``persist=False`` keeps the decision in memory so a dry run routes recipients the same way+ without enrolling anyone. Returns True only when settings were written to the database."""from posthog.models.user import Userfrom posthog.tasks.email_utils import auto_select_digest_project- setting_key = "error_tracking_weekly_digest_project_enabled"+ setting_key = DIGEST_PROJECT_SETTING_KEYcurrent_settings = user.partial_notification_settings or {}if setting_key in current_settings:return False@@ -116,6 +130,9 @@ def auto_select_project_for_user(user: Any, org_id: int, team_exception_counts:role = (user.role_at_organization or "").lower()if role not in ELIGIBLE_ROLES_FOR_AUTO_DIGEST:current_settings[setting_key] = {}+ if not persist:+ user.partial_notification_settings = current_settings+ return FalseUser.objects.filter(pk=user.pk).update(partial_notification_settings=current_settings)return True@@ -124,6 +141,7 @@ def auto_select_project_for_user(user: Any, org_id: int, team_exception_counts:team_data=team_exception_counts,setting_key=setting_key,sort_key=lambda d: d["exception_count"],+ persist=persist,)@@ -164,6 +182,8 @@ def get_crash_free_sessions(team: Team) -> dict:"""Calculate crash free sessions rate for the last 7 days with previous week comparison."""from posthog.hogql.query import execute_hogql_query+ from posthog.clickhouse.workload import Workload+# posthog.tasks.__init__ eagerly imports every task module (celery autoimport);# import the helper at call time so this module doesn't pull the task graph.from posthog.tasks.email_utils import compute_week_over_week_change # noqa: PLC0415@@ -187,6 +207,8 @@ def get_crash_free_sessions(team: Team) -> dict:""",team=team,filters=HogQLFilters(filterTestAccounts=True),+ # Unfiltered 14-day session scan — the heaviest query here. Must stay off the online cluster.+ workload=Workload.OFFLINE,)if not response.results or not response.results[0]:@@ -221,7 +243,7 @@ def get_crash_free_sessions(team: Team) -> dict:def get_daily_exception_counts(team: Team, daily_rows: list | None = None) -> list[dict]:"""Exception counts per day for the last 7 days, as sparkline-ready bars."""if daily_rows is None:- daily_rows = _query_daily_rows(team)+ daily_rows = query_daily_rows(team)# ClickHouse returns team-timezone dates, so bucket against the team-local today, not UTCtoday = timezone.now().astimezone(team.timezone_info).date()@@ -256,6 +278,8 @@ def _query_issue_rows(team: Team) -> list:"""from posthog.hogql.query import execute_hogql_query+ from posthog.clickhouse.workload import Workload+tag_queries(product=ProductKey.ERROR_TRACKING, team_id=team.pk, name="weekly_digest:issue_rows")response = execute_hogql_query(@@ -286,6 +310,8 @@ def _query_issue_rows(team: Team) -> list:""",team=team,filters=HogQLFilters(filterTestAccounts=True),+ # Weekly batch job: Celery pinned this to the offline cluster process-wide, Temporal does not.+ workload=Workload.OFFLINE,)return response.results or []@@ -395,14 +421,19 @@ def get_source_maps_recommendation_for_team(team: Team) -> dict | None:}-def build_team_digest_data(team: Team) -> dict[str, Any] | None:- """Assemble all digest data for one team, or None when it had no exceptions this week."""+def build_team_digest_data(team: Team, daily_rows: list | None = None) -> dict[str, Any] | None:+ """Assemble all digest data for one team, or None when it had no exceptions this week.++ ``daily_rows`` lets a caller that already queried the team's 14-day rows hand them in+ instead of paying for the same query twice.+ """# posthog.tasks.__init__ eagerly imports every task module (celery autoimport);# import the helper at call time so this module doesn't pull the task graph.from posthog.tasks.email_utils import compute_week_over_week_change # noqa: PLC0415# Two bounded ClickHouse passes + crash-free: three queries per team instead of five.- daily_rows = _query_daily_rows(team)+ if daily_rows is None:+ daily_rows = query_daily_rows(team)counts = get_exception_summary_for_team(team, daily_rows)if not counts or counts["exception_count"] == 0:return None@@ -462,6 +493,11 @@ def send_digest_to_workflow(digest: dict[str, Any], distinct_id: str) -> None:Raises on failure so callers (celery autoretry) can retry."""+ # Single choke point where digest data leaves the instance, so the cloud-only guarantee is+ # enforced here rather than in each of the three callers.+ if not is_cloud():+ raise RuntimeError("Error Tracking weekly digest cannot send from a self-hosted deployment")+headers = {}if settings.WORKFLOWS_WEBHOOK_SECRET:headers["Authorization"] = settings.WORKFLOWS_WEBHOOK_SECRET