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.

chore(error-tracking): isolate weekly digest delivery (#87396)

posthog[bot]e72d35bdde9d
diff --git a/.github/workflows/container-images-cd.yml b/.github/workflows/container-images-cd.yml
index 071f1e6054de..2a1a0dfd906c 100644
--- a/.github/workflows/container-images-cd.yml
+++ b/.github/workflows/container-images-cd.yml
@@ -544,6 +544,7 @@ jobs:
- 'products/error_tracking/backend/logic/**'
- 'products/error_tracking/backend/models.py'
- 'products/error_tracking/backend/weekly_digest.py'
+ - 'products/error_tracking/backend/weekly_digest_delivery.py'
- 'products/error_tracking/backend/indexed_embedding.py'
- 'posthog/tasks/email.py'
- 'posthog/tasks/email_utils.py'
diff --git a/products/error_tracking/backend/facade/api.py b/products/error_tracking/backend/facade/api.py
index 3295f46891df..dac0e7e09478 100644
--- a/products/error_tracking/backend/facade/api.py
+++ b/products/error_tracking/backend/facade/api.py
@@ -13,7 +13,7 @@ import posthoganalytics
from posthog.event_usage import groups
-from .. import logic, weekly_digest
+from .. import logic, weekly_digest, weekly_digest_delivery
from ..logic import external_references, rules
from ..models import (
ErrorTrackingIssue,
@@ -768,8 +768,8 @@ def build_team_digest_data(team: Any) -> dict[str, Any] | None:
def build_team_section_payload(data: dict[str, Any]) -> dict[str, Any]:
- return weekly_digest.build_team_section_payload(data)
+ return weekly_digest_delivery.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)
+ weekly_digest_delivery.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
index f45317a776b7..850cb5c9f555 100644
--- 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
@@ -20,7 +20,7 @@ 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
+from products.error_tracking.backend import weekly_digest, weekly_digest_delivery
class Command(BaseCommand):
@@ -63,14 +63,14 @@ class Command(BaseCommand):
digest = {
"recipient_email": email,
"org_name": org.name,
- "project_sections": [weekly_digest.build_team_section_payload(d) for d in sections],
+ "project_sections": [weekly_digest_delivery.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)
+ weekly_digest_delivery.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)"
diff --git a/products/error_tracking/backend/temporal/weekly_digest/activities.py b/products/error_tracking/backend/temporal/weekly_digest/activities.py
index 933984c235f4..40a6eea25454 100644
--- a/products/error_tracking/backend/temporal/weekly_digest/activities.py
+++ b/products/error_tracking/backend/temporal/weekly_digest/activities.py
@@ -16,7 +16,7 @@ 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 import weekly_digest, weekly_digest_delivery
from products.error_tracking.backend.facade.contracts import ExceptionSummary
from products.error_tracking.backend.temporal.weekly_digest.types import (
CleanupDigestOrgsInputs,
@@ -264,7 +264,7 @@ def _send_org_digest(inputs: SendOrgDigestInputs, attempt: int) -> SendOrgDigest
digest = {
"recipient_email": user.email,
"org_name": org.name,
- "project_sections": [weekly_digest.build_team_section_payload(d) for d in user_team_sections],
+ "project_sections": [weekly_digest_delivery.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",
@@ -294,7 +294,7 @@ def _send_org_digest(inputs: SendOrgDigestInputs, attempt: int) -> SendOrgDigest
continue
try:
- weekly_digest.send_digest_to_workflow(digest, distinct_id)
+ weekly_digest_delivery.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)
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.py
index f92b17bc8cc3..d80959e872f9 100644
--- 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.py
@@ -54,7 +54,7 @@ from products.error_tracking.backend.weekly_digest import build_team_digest_data
from ee.clickhouse.materialized_columns.columns import materialize
-_WEBHOOK_POST = "products.error_tracking.backend.weekly_digest.requests.post"
+_WEBHOOK_POST = "products.error_tracking.backend.weekly_digest_delivery.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"
_OBJECT_STORAGE = "products.error_tracking.backend.temporal.weekly_digest.activities.object_storage"
diff --git a/products/error_tracking/backend/test/test_weekly_digest_delivery.py b/products/error_tracking/backend/test/test_weekly_digest_delivery.py
index f47cbc16f653..c5c68a4cce68 100644
--- a/products/error_tracking/backend/test/test_weekly_digest_delivery.py
+++ b/products/error_tracking/backend/test/test_weekly_digest_delivery.py
@@ -22,7 +22,7 @@ from products.error_tracking.backend.models import (
ErrorTrackingIssueFingerprintV2,
sync_issues_to_clickhouse,
)
-from products.error_tracking.backend.weekly_digest import send_digest_to_workflow
+from products.error_tracking.backend.weekly_digest_delivery import send_digest_to_workflow
from ee.clickhouse.materialized_columns.columns import materialize
@@ -35,13 +35,13 @@ def _days_ago(n: int) -> str:
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 patch("products.error_tracking.backend.weekly_digest_delivery.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:
+ with patch("products.error_tracking.backend.weekly_digest_delivery.requests.post") as mock_post:
mock_post.return_value.raise_for_status.side_effect = requests.HTTPError(
"500", response=mock_post.return_value
)
@@ -50,7 +50,7 @@ class TestSendDigestToWorkflow(SimpleTestCase):
@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:
+ with patch("products.error_tracking.backend.weekly_digest_delivery.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"}
@@ -84,7 +84,7 @@ class TestWeeklyDigestWorkflowDelivery(ClickhouseTestMixin, APIBaseTest):
}
self.user.save()
- with patch("products.error_tracking.backend.weekly_digest.requests.post") as mock_post:
+ with patch("products.error_tracking.backend.weekly_digest_delivery.requests.post") as mock_post:
send_error_tracking_weekly_digest_for_org(str(self.organization.id))
assert mock_post.call_count == 1
@@ -144,7 +144,7 @@ class TestWeeklyDigestWorkflowDelivery(ClickhouseTestMixin, APIBaseTest):
self.user.role_at_organization = "engineering"
self.user.save()
- with patch("products.error_tracking.backend.weekly_digest.requests.post"):
+ with patch("products.error_tracking.backend.weekly_digest_delivery.requests.post"):
send_error_tracking_weekly_digest_for_org(str(self.organization.id))
self.user.refresh_from_db()
@@ -181,7 +181,7 @@ class TestWeeklyDigestWorkflowDelivery(ClickhouseTestMixin, APIBaseTest):
with (
patch("posthog.tasks.email.error_tracking_api.build_team_digest_data", side_effect=build_or_fail),
- patch("products.error_tracking.backend.weekly_digest.requests.post") as mock_post,
+ patch("products.error_tracking.backend.weekly_digest_delivery.requests.post") as mock_post,
):
with pytest.raises(Exception, match="team builds"):
send_error_tracking_weekly_digest_for_org(str(self.organization.id))
@@ -215,7 +215,7 @@ class TestWeeklyDigestWorkflowDelivery(ClickhouseTestMixin, APIBaseTest):
with (
patch("posthog.tasks.email.error_tracking_api.build_team_digest_data", side_effect=build_or_recover),
- patch("products.error_tracking.backend.weekly_digest.requests.post") as mock_post,
+ patch("products.error_tracking.backend.weekly_digest_delivery.requests.post") as mock_post,
):
# Attempt 1: team A build fails, so the recipient is deferred and the task raises to retry.
with pytest.raises(Exception, match="team builds"):
@@ -251,7 +251,7 @@ class TestWeeklyDigestWorkflowDelivery(ClickhouseTestMixin, APIBaseTest):
with (
patch("posthog.tasks.email.error_tracking_api.build_team_digest_data", side_effect=build_or_fail),
- patch("products.error_tracking.backend.weekly_digest.requests.post") as mock_post,
+ patch("products.error_tracking.backend.weekly_digest_delivery.requests.post") as mock_post,
):
# Retries exhausted (retries == max_retries): fall back to delivering the healthy teams rather
# than starving the recipient of a digest entirely. throw=False keeps the terminal raise eager.
@@ -272,7 +272,7 @@ class TestWeeklyDigestWorkflowDelivery(ClickhouseTestMixin, APIBaseTest):
}
self.user.save()
- with patch("products.error_tracking.backend.weekly_digest.requests.post") as mock_post:
+ with patch("products.error_tracking.backend.weekly_digest_delivery.requests.post") as mock_post:
send_error_tracking_weekly_digest_for_org(str(self.organization.id))
digest = mock_post.call_args.kwargs["json"]["digest"]
diff --git a/products/error_tracking/backend/weekly_digest.py b/products/error_tracking/backend/weekly_digest.py
index e61cc57be24e..63b332f9775b 100644
--- a/products/error_tracking/backend/weekly_digest.py
+++ b/products/error_tracking/backend/weekly_digest.py
@@ -1,27 +1,21 @@
import datetime
-from dataclasses import asdict
from typing import Any
from django.conf import settings
from django.utils import timezone
-import requests
import structlog
from posthog.schema import HogQLFilters
from posthog.clickhouse.query_tagging import tag_queries
-from posthog.cloud_utils import is_cloud
from posthog.models import Team
from posthog.schema_enums import ProductKey
-from posthog.utils import compact_number
from products.error_tracking.backend.facade.contracts import SOURCE_MAPS_DOCS_URL, CrashFreeSummary, ExceptionSummary
logger = structlog.get_logger(__name__)
-DIGEST_WEBHOOK_TIMEOUT_SECONDS = 10
-
# Above HogQL's 60s default: digest scans on high-volume teams (14-day windows, plus a persons
# join when test-account filters include person properties) legitimately run past 60s. Matches
# the error_tracking ClickHouse profile's execution ceiling — keep the two in sync.
@@ -483,64 +477,6 @@ def build_team_digest_data(
}
-def build_team_section_payload(data: dict[str, Any]) -> dict[str, Any]:
- """JSON-safe project section for the digest workflow webhook payload.
-
- Big counts are pre-formatted here because the email template (Liquid) has no
- number formatting filter. ingestion_failure_count must stay numeric — the
- template branches on `> 0` — so it gets a display twin instead. Copies, not
- in-place mutation: the same data dict is reused across recipients.
- """
-
- def serialize_issue(issue: dict[str, Any]) -> dict[str, Any]:
- return {**issue, "id": str(issue["id"]), "occurrence_count": compact_number(issue["occurrence_count"])}
-
- section = {k: v for k, v in data.items() if k != "team"}
- section["team_name"] = data["team"].name
- section["exception_count"] = compact_number(data["exception_count"])
- section["ingestion_failure_count_display"] = compact_number(data["ingestion_failure_count"])
- crash_free = data["crash_free"]
- # The digest webhook payload represents "no crash-free data" as {}, not null
- section["crash_free"] = (
- {**asdict(crash_free), "total_sessions": compact_number(crash_free.total_sessions)} if crash_free else {}
- )
- 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.
- """
- # 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
-
- 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="
diff --git a/products/error_tracking/backend/weekly_digest_delivery.py b/products/error_tracking/backend/weekly_digest_delivery.py
new file mode 100644
index 000000000000..7796c04fc1db
--- /dev/null
+++ b/products/error_tracking/backend/weekly_digest_delivery.py
@@ -0,0 +1,68 @@
+from dataclasses import asdict
+from typing import Any
+
+from django.conf import settings
+
+import requests
+
+from posthog.cloud_utils import is_cloud
+from posthog.utils import compact_number
+
+DIGEST_WEBHOOK_TIMEOUT_SECONDS = 10
+
+# 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 build_team_section_payload(data: dict[str, Any]) -> dict[str, Any]:
+ """JSON-safe project section for the digest workflow webhook payload.
+
+ Big counts are pre-formatted here because the email template (Liquid) has no
+ number formatting filter. ingestion_failure_count must stay numeric — the
+ template branches on `> 0` — so it gets a display twin instead. Copies, not
+ in-place mutation: the same data dict is reused across recipients.
+ """
+
+ def serialize_issue(issue: dict[str, Any]) -> dict[str, Any]:
+ return {**issue, "id": str(issue["id"]), "occurrence_count": compact_number(issue["occurrence_count"])}
+
+ section = {k: v for k, v in data.items() if k != "team"}
+ section["team_name"] = data["team"].name
+ section["exception_count"] = compact_number(data["exception_count"])
+ section["ingestion_failure_count_display"] = compact_number(data["ingestion_failure_count"])
+ crash_free = data["crash_free"]
+ # The digest webhook payload represents "no crash-free data" as {}, not null
+ section["crash_free"] = (
+ {**asdict(crash_free), "total_sessions": compact_number(crash_free.total_sessions)} if crash_free else {}
+ )
+ 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
+
+
+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.
+ """
+ # Single choke point where digest data leaves the instance, so the cloud-only guarantee is
+ # enforced here rather than in each caller.
+ 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
+
+ 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()