Skip to content

: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.

feat(error-tracking): deliver weekly digest via workflow webhook instead of SMTP (#68512)

Aleksander Błaszkiewicz5d18132161c3
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index eb6dca799176..01437d1fc832 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -889,6 +889,9 @@ ERROR_TRACKING_WEEKLY_DIGEST_ORG_IDS = get_list(get_from_env("ERROR_TRACKING_WEE
# "*" for all
ERROR_TRACKING_WEEKLY_DIGEST_ALLOWED_EMAILS = get_list(get_from_env("ERROR_TRACKING_WEEKLY_DIGEST_ALLOWED_EMAILS", ""))
+# webhook secret used initially for ET weekly digest workflow webhook but feel free to adopt it
+WORKFLOWS_WEBHOOK_SECRET = get_from_env("WORKFLOWS_WEBHOOK_SECRET", "")
+
####
# OAuth
diff --git a/posthog/tasks/email.py b/posthog/tasks/email.py
index 82a405bf0e3a..057a4f54ccd4 100644
--- a/posthog/tasks/email.py
+++ b/posthog/tasks/email.py
@@ -5,6 +5,7 @@ from typing import Any, Literal, Optional, cast
from urllib.parse import quote
from django.conf import settings
+from django.db import transaction
from django.db.models import OuterRef, Subquery
from django.utils import timezone
@@ -1873,12 +1874,8 @@ def send_error_tracking_weekly_digest() -> None:
@shared_task(**EMAIL_TASK_KWARGS, rate_limit="10/s")
@skip_team_scope_audit
def send_error_tracking_weekly_digest_for_org(org_id: str) -> None:
- """Send one combined weekly error tracking digest email per user in an org"""
+ """Send one combined weekly error tracking digest per user in an org via the delivery workflow"""
from posthog.models.organization import Organization
- from posthog.tasks.email_utils import compute_week_over_week_change
-
- if not is_email_available(with_absolute_urls=True):
- return
try:
org = Organization.objects.get(id=org_id)
@@ -1903,25 +1900,9 @@ def send_error_tracking_weekly_digest_for_org(org_id: str) -> None:
if not team:
continue
- counts = error_tracking_api.get_exception_summary_for_team(team)
- if not counts or counts["exception_count"] == 0:
- continue
-
- team_digest_data[team_id] = {
- "team": team,
- "exception_count": counts["exception_count"],
- "exception_change": compute_week_over_week_change(
- counts["exception_count"], counts["prev_exception_count"], higher_is_better=False
- ),
- "ingestion_failure_count": counts["ingestion_failure_count"],
- "top_issues": error_tracking_api.get_top_issues_for_team(team),
- "new_issues": error_tracking_api.get_new_issues_for_team(team),
- "daily_counts": error_tracking_api.get_daily_exception_counts(team),
- "crash_free": error_tracking_api.get_crash_free_sessions(team),
- "source_maps_recommendation": error_tracking_api.get_source_maps_recommendation_for_team(team),
- "error_tracking_url": f"{settings.SITE_URL}/project/{team_id}/error_tracking?utm_source=error_tracking_weekly_digest",
- "ingestion_failures_url": error_tracking_api.build_ingestion_failures_url(team_id),
- }
+ data = error_tracking_api.build_team_digest_data(team)
+ if data:
+ team_digest_data[team_id] = data
excluded_project_count = len(all_org_teams) - len(team_digest_data)
@@ -1939,6 +1920,7 @@ def send_error_tracking_weekly_digest_for_org(org_id: str) -> None:
date_suffix = timezone.now().strftime("%Y-%W")
sent_count = 0
+ failed_count = 0
for membership in memberships:
user = membership.user
@@ -1969,30 +1951,46 @@ def send_error_tracking_weekly_digest_for_org(org_id: str) -> None:
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": [error_tracking_api.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}",
+ }
+
campaign_key = f"error_tracking_weekly_digest_{org_id}_{user.uuid}_{date_suffix}"
- message = EmailMessage(
- campaign_key=campaign_key,
- subject=f"Error tracking weekly digest for {org.name}",
- template_name="error_tracking_weekly_digest",
- template_context={
- "organization": org,
- "project_sections": 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",
- "contact_support_url": "https://posthog.com/support",
- "feedback_survey_url": f"https://us.posthog.com/external_surveys/019c7fd6-7cfa-0000-2b03-a8e5d4c03743?distinct_id={user.distinct_id}",
- },
- )
- message.add_user_recipient(user)
- message.send()
- sent_count += 1
+ # Per-recipient transaction + sent_at guard so an autoretry after a mid-batch
+ # failure skips recipients whose digest was already accepted by the workflow.
+ with transaction.atomic():
+ record, _ = MessagingRecord.objects.get_or_create(raw_email=user.email, campaign_key=campaign_key)
+ record = MessagingRecord.objects.select_for_update().get(pk=record.pk)
+ if record.sent_at:
+ continue
+
+ try:
+ error_tracking_api.send_digest_to_workflow(digest, distinct_id)
+ except Exception:
+ logger.exception(f"Failed to send Error Tracking weekly digest for user {user.uuid} in org {org_id}")
+ failed_count += 1
+ continue
+
+ record.sent_at = timezone.now()
+ record.save()
+ sent_count += 1
logger.info(
f"Sent Error Tracking weekly digest to {sent_count} members for org {org_id} "
- f"({len(team_digest_data)} teams with exceptions)"
+ f"({len(team_digest_data)} teams with exceptions, {failed_count} failures)"
)
+ if failed_count:
+ # Trigger celery autoretry; already-sent recipients are skipped via MessagingRecord.
+ raise Exception(f"Error Tracking weekly digest failed for {failed_count} recipients in org {org_id}")
+
def get_integration_display_name(kind: str) -> str:
# Only kinds whose correct casing differs from the title-cased fallback need an override.
diff --git a/posthog/tasks/test/preview_error_tracking_digest.py b/posthog/tasks/test/preview_error_tracking_digest.py
deleted file mode 100644
index 7b3a3853f039..000000000000
--- a/posthog/tasks/test/preview_error_tracking_digest.py
+++ /dev/null
@@ -1,240 +0,0 @@
-"""
-Quick preview of the error tracking weekly digest email template.
-
-Usage:
- python manage.py shell -c "exec(open('posthog/tasks/test/preview_error_tracking_digest.py').read())"
-
- # Preview the EU source maps wizard command (adds --region eu)
- DIGEST_PREVIEW_REGION=eu python manage.py shell -c "exec(open('posthog/tasks/test/preview_error_tracking_digest.py').read())"
-"""
-
-import os
-import sys
-import subprocess
-
-from django.conf import settings
-from django.template.loader import get_template
-
-from posthog.email import inline_css
-
-from products.error_tracking.backend.facade.api import SOURCE_MAPS_DOCS_URL
-
-
-def _wizard_command() -> str:
- # Mirrors sourceMapsFixWizardLogic / _source_maps_wizard_command: --region eu on EU.
- region = (os.environ.get("DIGEST_PREVIEW_REGION") or settings.CLOUD_DEPLOYMENT or "us").lower()
- region_flag = " --region eu" if region == "eu" else ""
- return f"npx -y @posthog/wizard@latest upload-source-maps{region_flag}"
-
-
-_issue_sparkline_up = [
- {"height_percent": 10},
- {"height_percent": 25},
- {"height_percent": 40},
- {"height_percent": 55},
- {"height_percent": 70},
- {"height_percent": 85},
- {"height_percent": 100},
-]
-_issue_sparkline_spike = [
- {"height_percent": 30},
- {"height_percent": 45},
- {"height_percent": 100},
- {"height_percent": 80},
- {"height_percent": 65},
- {"height_percent": 70},
- {"height_percent": 50},
-]
-_issue_sparkline_new = [
- {"height_percent": 0},
- {"height_percent": 0},
- {"height_percent": 0},
- {"height_percent": 30},
- {"height_percent": 60},
- {"height_percent": 100},
- {"height_percent": 85},
-]
-
-project_a = {
- "team": type("Team", (), {"name": "PostHog App", "pk": 2})(),
- "exception_count": 12483,
- "exception_change": {
- "percent": 23,
- "direction": "Down",
- "color": "#2f7d4f",
- "text": "Down 23%",
- "long_text": "Down 23% from previous week",
- },
- "ingestion_failure_count": 347,
- "source_maps_recommendation": {
- "unresolved_percent": 72,
- "lookback_hours": 24,
- "wizard_command": _wizard_command(),
- "docs_url": f"{SOURCE_MAPS_DOCS_URL}?utm_source=error_tracking_weekly_digest",
- },
- "daily_counts": [
- {"day": "Tue", "count": 1200, "height_percent": 60},
- {"day": "Wed", "count": 800, "height_percent": 40},
- {"day": "Thu", "count": 2000, "height_percent": 100},
- {"day": "Fri", "count": 1500, "height_percent": 75},
- {"day": "Sat", "count": 400, "height_percent": 20},
- {"day": "Sun", "count": 300, "height_percent": 15},
- {"day": "Mon", "count": 1800, "height_percent": 90},
- ],
- "top_issues": [
- {
- "id": "abc",
- "name": "Error",
- "description": "Minified React error #418; visit https://reactjs.org/docs/error-decoder.html?invariant=418 for the full message",
- "occurrence_count": 155000,
- "sparkline": _issue_sparkline_spike,
- "url": "https://us.posthog.com/project/2/error_tracking/abc?utm_source=error_tracking_weekly_digest",
- },
- {
- "id": "def",
- "name": "TypeError",
- "description": "NetworkError when attempting to fetch resource.",
- "occurrence_count": 79300,
- "sparkline": _issue_sparkline_up,
- "url": "https://us.posthog.com/project/2/error_tracking/def?utm_source=error_tracking_weekly_digest",
- },
- {
- "id": "ghi",
- "name": "TypeError",
- "description": "Failed to fetch",
- "occurrence_count": 46200,
- "sparkline": _issue_sparkline_spike,
- "url": "https://us.posthog.com/project/2/error_tracking/ghi?utm_source=error_tracking_weekly_digest",
- },
- {
- "id": "jkl",
- "name": "ConcurrencyLimitExceededForRealThisTimeNoJoke",
- "description": "Exceeded maximum concurrency limit: 3 for key: api:query:per-team:133740 and this is a really long description",
- "occurrence_count": 41400,
- "sparkline": _issue_sparkline_up,
- "url": "https://us.posthog.com/project/2/error_tracking/jkl?utm_source=error_tracking_weekly_digest",
- },
- {
- "id": "mno",
- "name": "gaierror",
- "description": "[Errno -3] Temporary failure in name resolution",
- "occurrence_count": 38500,
- "sparkline": _issue_sparkline_spike,
- "url": "https://us.posthog.com/project/2/error_tracking/mno?utm_source=error_tracking_weekly_digest",
- },
- ],
- "new_issues": [
- {
- "id": "new1",
- "name": "RangeError",
- "description": "Maximum call stack size exceeded",
- "occurrence_count": 2340,
- "sparkline": _issue_sparkline_new,
- "url": "https://us.posthog.com/project/2/error_tracking/new1?utm_source=error_tracking_weekly_digest",
- },
- {
- "id": "new2",
- "name": "SyntaxError",
- "description": "Unexpected token '<' in JSON at position 0",
- "occurrence_count": 890,
- "sparkline": _issue_sparkline_new,
- "url": "https://us.posthog.com/project/2/error_tracking/new2?utm_source=error_tracking_weekly_digest",
- },
- ],
- "crash_free": {
- "total_sessions": 284532,
- "crash_free_rate": 98.80,
- "crash_free_rate_change": {
- "percent": 1,
- "direction": "Up",
- "color": "#2f7d4f",
- "text": "Up 1%",
- "long_text": "Up 1% from previous week",
- },
- "total_sessions_change": {
- "percent": 12,
- "direction": "Up",
- "color": "#2f7d4f",
- "text": "Up 12%",
- "long_text": "Up 12% from previous week",
- },
- },
- "error_tracking_url": "https://us.posthog.com/project/2/error_tracking?utm_source=error_tracking_weekly_digest",
- "ingestion_failures_url": "https://us.posthog.com/project/2/activity/explore",
-}
-
-project_b = {
- "team": type("Team", (), {"name": "Marketing Site", "pk": 7})(),
- "exception_count": 892,
- "exception_change": {
- "percent": 45,
- "direction": "Up",
- "color": "#a13232",
- "text": "Up 45%",
- "long_text": "Up 45% from previous week",
- },
- "ingestion_failure_count": 0,
- # No source maps problem here — section is omitted for this project.
- "source_maps_recommendation": None,
- "daily_counts": [
- {"day": "Tue", "count": 80, "height_percent": 40},
- {"day": "Wed", "count": 120, "height_percent": 60},
- {"day": "Thu", "count": 200, "height_percent": 100},
- {"day": "Fri", "count": 150, "height_percent": 75},
- {"day": "Sat", "count": 90, "height_percent": 45},
- {"day": "Sun", "count": 52, "height_percent": 26},
- {"day": "Mon", "count": 200, "height_percent": 100},
- ],
- "top_issues": [
- {
- "id": "xyz",
- "name": "ChunkLoadError",
- "description": "Loading chunk 42 failed",
- "occurrence_count": 412,
- "sparkline": _issue_sparkline_up,
- "url": "https://us.posthog.com/project/7/error_tracking/xyz?utm_source=error_tracking_weekly_digest",
- },
- {
- "id": "uvw",
- "name": "AbortError",
- "description": "The operation was aborted.",
- "occurrence_count": 289,
- "sparkline": _issue_sparkline_spike,
- "url": "https://us.posthog.com/project/7/error_tracking/uvw?utm_source=error_tracking_weekly_digest",
- },
- ],
- "new_issues": [
- {
- "id": "new4",
- "name": "SecurityError",
- "description": "Blocked a frame with origin from accessing a cross-origin frame",
- "occurrence_count": 67,
- "sparkline": _issue_sparkline_new,
- "url": "https://us.posthog.com/project/7/error_tracking/new4?utm_source=error_tracking_weekly_digest",
- },
- ],
- "crash_free": {},
- "error_tracking_url": "https://us.posthog.com/project/7/error_tracking?utm_source=error_tracking_weekly_digest",
- "ingestion_failures_url": "https://us.posthog.com/project/7/activity/explore",
-}
-
-template = get_template("email/error_tracking_weekly_digest.html")
-html = template.render(
- {
- "organization": type("Organization", (), {"name": "PostHog"})(),
- "project_sections": [project_a, project_b],
- "disabled_project_names": ["Staging Environment", "Internal Tools", "Experiments Sandbox"],
- "excluded_project_count": 4,
- "settings_url": "https://us.posthog.com/settings/user-notifications",
- "contact_support_url": "https://posthog.com/support",
- "feedback_survey_url": "https://us.posthog.com/external_surveys/019c7fd6-7cfa-0000-2b03-a8e5d4c03743?distinct_id=test@posthog.com",
- }
-)
-
-path = "/tmp/error_tracking_digest_preview.html"
-with open(path, "w") as f:
- f.write(inline_css(html))
-
-print(f"Saved to {path}") # noqa: T201
-if sys.platform == "darwin":
- subprocess.run(["open", path])
diff --git a/posthog/templates/email/error_tracking_weekly_digest.html b/posthog/templates/email/error_tracking_weekly_digest.html
deleted file mode 100644
index 12574ca0e867..000000000000
--- a/posthog/templates/email/error_tracking_weekly_digest.html
+++ /dev/null
@@ -1,245 +0,0 @@
-{% extends "email/base.html" %}
-{% load posthog_assets %}
-{% load posthog_filters %}
-
-{% block head %}
-<style type="text/css">
- body, .main { background-color: #f3f4f0 !important; }
-</style>
-{% endblock %}
-
-{% block preheader %}Error tracking weekly digest for {{ organization.name }} organization{% endblock %}
-
-{% block main %}
-<p style="font-size: 1.1em; color: #374151; margin: 0 0 24px 0;">Error tracking weekly digest for <strong>{{ organization.name }}</strong> organization</p>
-
-{% for section in project_sections %}
-<!-- Project section: {{ section.team.name }} -->
-<div style="margin-bottom: 40px;">
- <table width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-bottom: 12px;">
- <tr>
- <td style="width: 50%; vertical-align: middle;"><div style="height: 1px; background-color: #d1d5db;"></div></td>
- <td style="white-space: nowrap; padding: 0 16px; vertical-align: middle;">
- <a href="{{ section.error_tracking_url }}" target="_blank" style="font-size: 1.15em; font-weight: 600; color: #111827; text-decoration: none;">{{ section.team.name }}</a>
- </td>
- <td style="width: 50%; vertical-align: middle;"><div style="height: 1px; background-color: #d1d5db;"></div></td>
- </tr>
- </table>
-
- <!-- Total -->
- <div style="background-color: #ffffff; border-radius: 8px; padding: 20px; margin-bottom: 8px;">
- <div style="text-align: center;">
- <div style="font-size: 0.8em; color: #6b7280; margin-bottom: 4px;">Total exceptions</div>
- <p style="margin: 0; font-size: 2.5em; font-weight: bold; line-height: 1.1;">
- {{ section.exception_count|compact_number }}
- </p>
- {% if section.exception_change %}
- <p style="margin: 0 0 12px 0; font-size: 0.85em; color: {{ section.exception_change.color }};">{{ section.exception_change.long_text }}</p>
- {% else %}
- <div style="margin-bottom: 12px;"></div>
- {% endif %}
- {% if section.daily_counts %}
- <table width="100%" cellpadding="0" cellspacing="0" border="0" style="margin: 0 auto;">
- <tr>
- {% for day in section.daily_counts %}
- <td align="center" valign="bottom" style="padding: 0 3px; height: 60px;">
- <div style="width: 100%; min-width: 20px; height: {{ day.height_percent }}%; {% if day.height_percent > 0 %}min-height: 3px;{% endif %} background-color: #9f9fa9; border-radius: 3px 3px 0 0;"></div>
- </td>
- {% endfor %}
- </tr>
- <tr><td colspan="{{ section.daily_counts|length }}" style="height: 1px; background-color: #e1e5e9; padding: 0; font-size: 0; line-height: 0;"></td></tr>
- <tr>
- {% for day in section.daily_counts %}
- <td align="center" style="padding: 4px 3px 0; font-size: 0.75em; color: #9ca3af;">{{ day.day }}</td>
- {% endfor %}
- </tr>
- </table>
- {% endif %}
- </div>
- {% if section.crash_free %}
- <table width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-top: 16px; border-top: 1px solid #f3f4f6; padding-top: 16px;">
- <tr>
- <td align="center" style="text-align: center; padding: 8px;">
- <div style="font-size: 0.8em; color: #6b7280;">Total sessions</div>
- <div style="font-size: 1.5em; font-weight: bold;">{{ section.crash_free.total_sessions|compact_number }}</div>
- {% if section.crash_free.total_sessions_change %}
- <div style="font-size: 0.75em; color: {{ section.crash_free.total_sessions_change.color }};">{{ section.crash_free.total_sessions_change.text }}</div>
- {% endif %}
- </td>
- <td align="center" style="text-align: center; padding: 8px;">
- <div style="font-size: 0.8em; color: #6b7280;">Crash free sessions</div>
- <div style="font-size: 1.5em; font-weight: bold;">{{ section.crash_free.crash_free_rate }}%</div>
- {% if section.crash_free.crash_free_rate_change %}
- <div style="font-size: 0.75em; color: {{ section.crash_free.crash_free_rate_change.color }};">{{ section.crash_free.crash_free_rate_change.text }}</div>
- {% endif %}
- </td>
- </tr>
- </table>
- {% endif %}
- </div>
-
- <!-- Missing source maps: prompt the source maps wizard -->
- {% if section.source_maps_recommendation %}
- <div style="background-color: #fef3cd; border: 1px solid #ffc107; padding: 20px; border-radius: 8px; margin-bottom: 8px;">
- <p style="margin: 0 0 8px 0; font-weight: 700; color: #856404; font-size: 1em;">
- &#9888; {{ section.source_maps_recommendation.unresolved_percent }}% of your stack traces aren't readable
- </p>
- <p style="margin: 0 0 16px 0; color: #664d03; font-size: 0.9em;">
- Upload source maps so stack traces show your real source. Run our wizard from your project root, or <a href="{{ section.source_maps_recommendation.docs_url }}" target="_blank" style="color: #856404; text-decoration: underline; font-weight: 500;">read the docs</a>.
- </p>
- <div style="background-color: #ffffff; border: 1px solid #f0d98c; border-radius: 6px; padding: 10px 14px;">
- <code style="font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace; color: #5c4a03; font-size: 0.7em;">{{ section.source_maps_recommendation.wizard_command }}</code>
- </div>
- </div>
- {% endif %}
-
- <!-- Top issues -->
- {% if section.top_issues %}
- <div style="background-color: #ffffff; border-radius: 8px; padding: 20px; margin-bottom: 8px;">
- <h3 style="margin: 0 0 4px 0; text-align: left;">Top issues</h3>
- <p style="margin: 0 0 12px 0; font-size: 0.85em; color: #6b7280; text-align: left;">Issues sorted by occurrence count this week</p>
- <table width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse: collapse;">
- <thead>
- <tr style="border-bottom: 1px solid #e1e5e9;">
- <th align="left" style="padding: 8px 8px 8px 0; font-size: 0.75em; color: #9ca3af; font-weight: 500; text-transform: uppercase; letter-spacing: 0.05em; text-align: left;">Issue</th>
- <th align="center" style="padding: 8px; font-size: 0.75em; color: #9ca3af; font-weight: 500; text-transform: uppercase; letter-spacing: 0.05em; width: 90px;">Volume</th>
- <th align="right" style="padding: 8px 0 8px 8px; font-size: 0.75em; color: #9ca3af; font-weight: 500; text-transform: uppercase; letter-spacing: 0.05em; width: 90px;">Occurrences</th>
- </tr>
- </thead>
- <tbody>
- {% for issue in section.top_issues %}
- <tr style="border-bottom: 1px solid #f3f4f6;">
- <td align="left" style="padding: 10px 8px 10px 0; vertical-align: top; text-align: left;">
- <a href="{{ issue.url }}" target="_blank" style="text-decoration: underline; color: #111827; font-weight: 600; font-size: 0.9em;">{{ issue.name|truncatechars:40 }}</a>
- {% if issue.description %}
- <div style="color: #6b7280; font-size: 0.8em; margin-top: 2px;">{{ issue.description|truncatechars:45 }}</div>
- {% endif %}
- </td>
- <td align="center" style="padding: 10px 8px; vertical-align: middle; width: 90px;">
- {% if issue.sparkline %}
- <table cellpadding="0" cellspacing="0" border="0" style="margin: 0 auto; height: 24px;">
- <tr>
- {% for bar in issue.sparkline %}
- <td valign="bottom" style="padding: 0 1px; height: 24px;">
- <div style="width: 8px; height: {{ bar.height_percent }}%; {% if bar.height_percent > 0 %}min-height: 2px;{% endif %} background-color: #9f9fa9; border-radius: 1px;"></div>
- </td>
- {% endfor %}
- </tr>
- <tr><td colspan="{{ issue.sparkline|length }}" style="height: 1px; background-color: #e1e5e9; padding: 0; font-size: 0; line-height: 0;"></td></tr>
- </table>
- {% endif %}
- </td>
- <td align="right" style="padding: 10px 0 10px 8px; vertical-align: middle; color: #111827; white-space: nowrap; width: 90px;">
- {{ issue.occurrence_count|compact_number }}
- </td>
- </tr>
- {% endfor %}
- </tbody>
- </table>
- </div>
- {% endif %}
-
- <!-- New issues -->
- {% if section.new_issues %}
- <div style="background-color: #ffffff; border-radius: 8px; padding: 20px; margin-bottom: 8px;">
- <h3 style="margin: 0 0 4px 0; text-align: left;">New issues</h3>
- <p style="margin: 0 0 12px 0; font-size: 0.85em; color: #6b7280; text-align: left;">Issues first seen this week sorted by occurrence count</p>
- <table width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse: collapse;">
- <thead>
- <tr style="border-bottom: 1px solid #e1e5e9;">
- <th align="left" style="padding: 8px 8px 8px 0; font-size: 0.75em; color: #9ca3af; font-weight: 500; text-transform: uppercase; letter-spacing: 0.05em; text-align: left;">Issue</th>
- <th align="center" style="padding: 8px; font-size: 0.75em; color: #9ca3af; font-weight: 500; text-transform: uppercase; letter-spacing: 0.05em; width: 90px;">Volume</th>
- <th align="right" style="padding: 8px 0 8px 8px; font-size: 0.75em; color: #9ca3af; font-weight: 500; text-transform: uppercase; letter-spacing: 0.05em; width: 90px;">Occurrences</th>
- </tr>
- </thead>
- <tbody>
- {% for issue in section.new_issues %}
- <tr style="border-bottom: 1px solid #f3f4f6;">
- <td align="left" style="padding: 10px 8px 10px 0; vertical-align: top; text-align: left;">
- <a href="{{ issue.url }}" target="_blank" style="text-decoration: underline; color: #111827; font-weight: 600; font-size: 0.9em;">{{ issue.name|truncatechars:40 }}</a>
- {% if issue.description %}
- <div style="color: #6b7280; font-size: 0.8em; margin-top: 2px;">{{ issue.description|truncatechars:45 }}</div>
- {% endif %}
- </td>
- <td align="center" style="padding: 10px 8px; vertical-align: middle; width: 90px;">
- {% if issue.sparkline %}
- <table cellpadding="0" cellspacing="0" border="0" style="margin: 0 auto; height: 24px;">
- <tr>
- {% for bar in issue.sparkline %}
- <td valign="bottom" style="padding: 0 1px; height: 24px;">
- <div style="width: 8px; height: {{ bar.height_percent }}%; {% if bar.height_percent > 0 %}min-height: 2px;{% endif %} background-color: #9f9fa9; border-radius: 1px;"></div>
- </td>
- {% endfor %}
- </tr>
- <tr><td colspan="{{ issue.sparkline|length }}" style="height: 1px; background-color: #e1e5e9; padding: 0; font-size: 0; line-height: 0;"></td></tr>
- </table>
- {% endif %}
- </td>
- <td align="right" style="padding: 10px 0 10px 8px; vertical-align: middle; color: #111827; white-space: nowrap; width: 90px;">
- {{ issue.occurrence_count|compact_number }}
- </td>
- </tr>
- {% endfor %}
- </tbody>
- </table>
- </div>
- {% endif %}
-
- <!-- Ingestion failures -->
- {% if section.ingestion_failure_count > 0 %}
- <div style="background-color: #fef3cd; border: 1px solid #ffc107; padding: 20px; border-radius: 8px; margin-bottom: 8px;">
- <p style="margin: 0 0 8px 0; font-weight: 700; color: #856404; font-size: 1em;">
- &#9888; {{ section.ingestion_failure_count|compact_number }} exceptions failed to ingest
- </p>
- <p style="margin: 0 0 16px 0; color: #664d03; font-size: 0.9em;">
- This is usually caused by malformed events being sent. You can inspect each failed exception to see what went wrong by expanding it.
- </p>
- <table cellpadding="0" cellspacing="0" border="0" width="100%">
- <tr>
- <td align="right" style="text-align: right;">
- <a href="{{ section.ingestion_failures_url }}" target="_blank" style="display: inline-block; padding: 8px 16px; background-color: #856404; color: #ffffff; text-decoration: none; border-radius: 6px; font-size: 0.9em; font-weight: 500; margin-right: 8px;">View these exceptions</a>
- <a href="{{ contact_support_url }}" target="_blank" style="display: inline-block; padding: 8px 16px; background-color: transparent; color: #856404; text-decoration: none; border: 1px solid #856404; border-radius: 6px; font-size: 0.9em; font-weight: 500;">Contact support</a>
- </td>
- </tr>
- </table>
- </div>
- {% endif %}
-
-</div>
-{% endfor %}
-
-{% if disabled_project_names or excluded_project_count > 0 %}
-<table width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-bottom: 12px;">
- <tr>
- <td style="width: 50%; vertical-align: middle;"><div style="height: 1px; background-color: #d1d5db;"></div></td>
- <td style="white-space: nowrap; padding: 0 16px; vertical-align: middle;">
- <span style="font-size: 0.9em; font-weight: 600; color: #6b7280;">Note</span>
- </td>
- <td style="width: 50%; vertical-align: middle;"><div style="height: 1px; background-color: #d1d5db;"></div></td>
- </tr>
-</table>
-<div style="background-color: #ffffff; border-radius: 8px; padding: 20px; margin-bottom: 16px;">
- {% if disabled_project_names %}
- <p style="margin: 0 0 8px 0; font-size: 0.9em; color: #6b7280;">This report did not include the following projects because they are disabled in your settings:</p>
- <ul style="margin: 0 0 {% if excluded_project_count > 0 %}16px{% else %}0{% endif %} 0; padding-left: 20px; color: #6b7280; font-size: 0.9em;">
- {% for name in disabled_project_names %}
- <li>{{ name }}</li>
- {% endfor %}
- </ul>
- {% endif %}
- {% if excluded_project_count > 0 %}
- <p style="margin: 0; font-size: 0.9em; color: #6b7280;">{{ excluded_project_count }} other project{{ excluded_project_count|pluralize }} in your organization had no exceptions this week and {{ excluded_project_count|pluralize:"was,were" }} not included in this digest.</p>
- {% endif %}
-</div>
-{% endif %}
-
-<div style="margin-bottom: 16px; text-align: center;">
- <a href="{{ settings_url }}" style="color: #6b7280; font-size: 0.85em; text-decoration: underline;">Change notification settings</a>
-</div>
-
-<div style="margin-bottom: 16px; text-align: center;">
- <a href="{{ feedback_survey_url }}" target="_blank" style="color: #6b7280; font-size: 0.85em; text-decoration: underline;">Share feedback on this digest</a>
-</div>
-{% endblock %}
-
-{% block footer %}{% endblock %}
diff --git a/products/error_tracking/backend/facade/api.py b/products/error_tracking/backend/facade/api.py
index c044cdc0249c..63a60a7bf611 100644
--- a/products/error_tracking/backend/facade/api.py
+++ b/products/error_tracking/backend/facade/api.py
@@ -636,3 +636,15 @@ def build_ingestion_failures_url(team_id: int) -> str:
def has_resolved_issues(team_id: int) -> bool:
return ErrorTrackingIssue.objects.filter(team_id=team_id, status=ErrorTrackingIssue.Status.RESOLVED).exists()
+
+
+def build_team_digest_data(team: Any) -> dict[str, Any] | None:
+ return weekly_digest.build_team_digest_data(team)
+
+
+def build_team_section_payload(data: dict[str, Any]) -> dict[str, Any]:
+ return weekly_digest.build_team_section_payload(data)
+
+
+def send_digest_to_workflow(digest: dict[str, Any], distinct_id: str) -> None:
+ weekly_digest.send_digest_to_workflow(digest, distinct_id)
diff --git a/products/error_tracking/backend/management/commands/send_error_tracking_weekly_digest.py b/products/error_tracking/backend/management/commands/send_error_tracking_weekly_digest.py
new file mode 100644
index 000000000000..f45317a776b7
--- /dev/null
+++ b/products/error_tracking/backend/management/commands/send_error_tracking_weekly_digest.py
@@ -0,0 +1,96 @@
+"""Send an error tracking weekly digest email to an arbitrary recipient, for testing.
+
+Builds the full digest for an organization (every project with exceptions this week,
+no per-user notification filtering) and delivers it through the digest workflow webhook.
+
+Usage:
+ # Recipient is a PostHog user in exactly one org
+ python manage.py send_error_tracking_weekly_digest --email [email protected]
+
+ # Explicit org (required when the recipient isn't a user or belongs to multiple orgs)
+ python manage.py send_error_tracking_weekly_digest --email [email protected] --org-id <uuid>
+"""
+
+from typing import Any
+
+from django.conf import settings
+from django.core.management.base import BaseCommand, CommandError
+
+from posthog.models import Team
+from posthog.models.organization import Organization
+from posthog.models.user import User
+
+from products.error_tracking.backend import weekly_digest
+
+
+class Command(BaseCommand):
+ help = "Send an error tracking weekly digest email to any address via the digest workflow (testing tool)."
+
+ def add_arguments(self, parser: Any) -> None:
+ parser.add_argument("--email", type=str, required=True, help="Recipient email address.")
+ parser.add_argument(
+ "--org-id",
+ type=str,
+ default=None,
+ help="Organization (UUID) to build the digest for. Defaults to the recipient's org when they are a user.",
+ )
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ email: str = options["email"]
+
+ user = User.objects.filter(email=email).first()
+ org = self._resolve_org(options["org_id"], user, email)
+
+ teams = list(Team.objects.filter(organization_id=org.id))
+ if not teams:
+ raise CommandError(f"Organization {org.id} has no projects")
+
+ team_ids_with_exceptions = {row[0] for row in weekly_digest.get_exception_counts([t.id for t in teams])}
+ sections = []
+ for team in teams:
+ if team.id not in team_ids_with_exceptions:
+ continue
+ data = weekly_digest.build_team_digest_data(team)
+ if data:
+ sections.append(data)
+
+ if not sections:
+ raise CommandError(f"No exceptions in the last 7 days for organization {org.id}, nothing to send")
+
+ sections.sort(key=lambda d: d["exception_count"], reverse=True)
+
+ distinct_id = (user.distinct_id if user else None) or email
+ digest = {
+ "recipient_email": email,
+ "org_name": org.name,
+ "project_sections": [weekly_digest.build_team_section_payload(d) for d in sections],
+ "disabled_project_names": [],
+ "excluded_project_count": len(teams) - len(sections),
+ "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}",
+ }
+
+ weekly_digest.send_digest_to_workflow(digest, distinct_id)
+ self.stdout.write(
+ self.style.SUCCESS(
+ f"Sent weekly digest for org '{org.name}' ({org.id}) to {email} ({len(sections)} project sections)"
+ )
+ )
+
+ def _resolve_org(self, org_id: str | None, user: User | None, email: str) -> Organization:
+ if org_id:
+ try:
+ return Organization.objects.get(id=org_id)
+ except Organization.DoesNotExist:
+ raise CommandError(f"Organization {org_id} not found")
+
+ if not user:
+ raise CommandError(f"No user with email {email} - pass --org-id to pick the digest organization")
+
+ orgs = list(user.organizations.all())
+ if not orgs:
+ raise CommandError(f"User {email} belongs to no organizations - pass --org-id")
+ if len(orgs) > 1:
+ org_list = ", ".join(f"{o.name} ({o.id})" for o in orgs)
+ raise CommandError(f"User {email} belongs to multiple organizations, pass --org-id. Options: {org_list}")
+ return orgs[0]
diff --git a/products/error_tracking/backend/test/test_weekly_digest.py b/products/error_tracking/backend/test/test_weekly_digest.py
index 51ec9580985c..3c828b2bb37b 100644
--- a/products/error_tracking/backend/test/test_weekly_digest.py
+++ b/products/error_tracking/backend/test/test_weekly_digest.py
@@ -1,16 +1,21 @@
+import json
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 override_settings
+from django.test import SimpleTestCase, override_settings
from django.utils import timezone
+import requests
from parameterized import parameterized
from posthog.models import Team
from posthog.models.organization import Organization
from posthog.models.utils import uuid7
+from posthog.tasks.email import send_error_tracking_weekly_digest_for_org
from posthog.tasks.email_utils import compute_week_over_week_change
from products.error_tracking.backend.models import (
@@ -28,6 +33,7 @@ from products.error_tracking.backend.weekly_digest import (
get_org_ids_with_exceptions,
get_source_maps_recommendation_for_team,
get_top_issues_for_team,
+ send_digest_to_workflow,
)
from ee.clickhouse.materialized_columns.columns import materialize
@@ -548,3 +554,70 @@ class TestSourceMapsRecommendationForDigest(APIBaseTest):
other_team = Team.objects.create(organization=self.organization, name="Other")
self._create_recommendation(meta=_ACTIVE_META)
assert get_source_maps_recommendation_for_team(other_team) is None
+
+
+class TestSendDigestToWorkflow(SimpleTestCase):
+ 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(
+ "500", response=mock_post.return_value
+ )
+ with pytest.raises(requests.HTTPError):
+ send_digest_to_workflow({"recipient_email": "[email protected]"}, "distinct-1")
+
+ @override_settings(WORKFLOWS_WEBHOOK_SECRET="Bearer test-token")
+ def test_sends_secret_as_authorization_header(self):
+ with patch("products.error_tracking.backend.weekly_digest.requests.post") as mock_post:
+ send_digest_to_workflow({"recipient_email": "[email protected]"}, "distinct-1")
+ assert mock_post.call_args.kwargs["headers"] == {"Authorization": "Bearer test-token"}
+
+
+class TestWeeklyDigestWorkflowDelivery(ClickhouseTestMixin, APIBaseTest):
+ @classmethod
+ def setUpTestData(cls):
+ super().setUpTestData()
+ materialize("events", "$exception_issue_id", is_nullable=True)
+
+ @override_settings(ERROR_TRACKING_WEEKLY_DIGEST_ALLOWED_EMAILS=["*"])
+ def test_task_posts_json_safe_digest_and_dedupes_on_retry(self):
+ issue = ErrorTrackingIssue.objects.create(
+ id=uuid7(), team=self.team, status=ErrorTrackingIssue.Status.ACTIVE, name="TestError"
+ )
+ _create_event(
+ distinct_id="user_1",
+ event="$exception",
+ team=self.team,
+ properties={"$exception_issue_id": str(issue.id)},
+ 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("products.error_tracking.backend.weekly_digest.requests.post") as mock_post:
+ send_error_tracking_weekly_digest_for_org(str(self.organization.id))
+
+ 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 "team" not in section
+
+ # Retry of the org task must not send the same campaign twice (MessagingRecord dedupe)
+ send_error_tracking_weekly_digest_for_org(str(self.organization.id))
+ assert mock_post.call_count == 1
diff --git a/products/error_tracking/backend/weekly_digest.py b/products/error_tracking/backend/weekly_digest.py
index 392f0846e58d..8313a08136ed 100644
--- a/products/error_tracking/backend/weekly_digest.py
+++ b/products/error_tracking/backend/weekly_digest.py
@@ -4,6 +4,7 @@ from typing import Any
from django.conf import settings
from django.utils import timezone
+import requests
import structlog
from posthog.schema import HogQLFilters
@@ -14,6 +15,8 @@ from posthog.schema_enums import ProductKey
logger = structlog.get_logger(__name__)
+DIGEST_WEBHOOK_TIMEOUT_SECONDS = 10
+
# Keep in sync with SOURCE_MAPS_DOCS_URL in sourceMapsFixWizardLogic.ts
SOURCE_MAPS_DOCS_URL = "https://posthog.com/docs/error-tracking/upload-source-maps"
@@ -412,6 +415,73 @@ 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."""
+ # 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
+
+ counts = get_exception_summary_for_team(team)
+ if not counts or counts["exception_count"] == 0:
+ return None
+
+ return {
+ "team": team,
+ "exception_count": counts["exception_count"],
+ "exception_change": compute_week_over_week_change(
+ counts["exception_count"], counts["prev_exception_count"], higher_is_better=False
+ ),
+ "ingestion_failure_count": counts["ingestion_failure_count"],
+ "top_issues": get_top_issues_for_team(team),
+ "new_issues": get_new_issues_for_team(team),
+ "daily_counts": get_daily_exception_counts(team),
+ "crash_free": get_crash_free_sessions(team),
+ "source_maps_recommendation": get_source_maps_recommendation_for_team(team),
+ "error_tracking_url": f"{settings.SITE_URL}/project/{team.pk}/error_tracking?utm_source=error_tracking_weekly_digest",
+ "ingestion_failures_url": build_ingestion_failures_url(team.pk),
+ }
+
+
+def build_team_section_payload(data: dict[str, Any]) -> dict[str, Any]:
+ """JSON-safe project section for the digest workflow webhook payload."""
+
+ def serialize_issue(issue: dict[str, Any]) -> dict[str, Any]:
+ return {**issue, "id": str(issue["id"])}
+
+ section = {k: v for k, v in data.items() if k != "team"}
+ section["team_name"] = data["team"].name
+ section["top_issues"] = [serialize_issue(i) for i in data["top_issues"]]
+ section["new_issues"] = [serialize_issue(i) for i in data["new_issues"]]
+ return section
+
+
+# Webhook trigger of the "[Error tracking] Weekly digest email" workflow in the internal
+# PostHog project. Protected by WORKFLOWS_WEBHOOK_SECRET, so the URL is not a secret.
+DIGEST_WORKFLOW_WEBHOOK_URL = "https://webhooks.us.posthog.com/public/webhooks/019f2754-aeff-0000-6a0d-5d3933a94b08"
+
+
+def send_digest_to_workflow(digest: dict[str, Any], distinct_id: str) -> None:
+ """POST one recipient's digest to the delivery workflow's webhook trigger.
+
+ Raises on failure so callers (celery autoretry) can retry.
+ """
+ headers = {}
+ if settings.WORKFLOWS_WEBHOOK_SECRET:
+ headers["Authorization"] = settings.WORKFLOWS_WEBHOOK_SECRET
+
+ response = requests.post(
+ DIGEST_WORKFLOW_WEBHOOK_URL,
+ json={
+ "event": "error_tracking_weekly_digest",
+ "distinct_id": distinct_id,
+ "digest": digest,
+ },
+ headers=headers,
+ timeout=DIGEST_WEBHOOK_TIMEOUT_SECONDS,
+ )
+ response.raise_for_status()
+
+
def build_ingestion_failures_url(team_id: int) -> str:
return (
f"{settings.SITE_URL}/project/{team_id}/activity/explore#q="