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.

perf(error-tracking): cut weekly digest clickhouse query load (#70471)

Aleksander Błaszkiewicz35a43af6cf0b
diff --git a/posthog/tasks/email.py b/posthog/tasks/email.py
index d158949cfa7c..e6d25dac07cf 100644
--- a/posthog/tasks/email.py
+++ b/posthog/tasks/email.py
@@ -11,7 +11,7 @@ from django.utils import timezone
import structlog
import posthoganalytics
-from celery import shared_task
+from celery import Task, shared_task
from posthoganalytics import new_context, tag
from prometheus_client import Counter, Histogram
@@ -1947,9 +1947,9 @@ def send_error_tracking_weekly_digest() -> None:
logger.info("Completed Error Tracking weekly digest fan-out")
-@shared_task(**EMAIL_TASK_KWARGS, rate_limit="10/s")
+@shared_task(**{**EMAIL_TASK_KWARGS, "max_retries": 5}, rate_limit="10/s", bind=True)
@skip_team_scope_audit
-def send_error_tracking_weekly_digest_for_org(org_id: str) -> None:
+def send_error_tracking_weekly_digest_for_org(self: Task, org_id: str) -> None:
"""Send one combined weekly error tracking digest per user in an org via the delivery workflow"""
from posthog.models.organization import Organization
@@ -1963,68 +1963,123 @@ def send_error_tracking_weekly_digest_for_org(org_id: str) -> None:
if not all_org_teams:
return
- # Use unfiltered counts only to determine which teams have any exceptions at all
+ # Which teams have any exceptions at all — one ClickHouse query for the whole org.
unfiltered_counts = error_tracking_api.get_exception_counts(list(all_org_teams.keys()))
- team_ids_with_exceptions = {row[0] for row in unfiltered_counts}
+ 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
- # Pre-compute per-team digest data only for teams that have exceptions
- team_digest_data: dict[int, dict] = {}
- for team_id in team_ids_with_exceptions:
- team = all_org_teams.get(team_id)
- if not team:
- continue
-
- 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)
-
- all_memberships = OrganizationMembership.objects.prefetch_related("user").filter(organization_id=org.id)
-
allowed_emails = settings.ERROR_TRACKING_WEEKLY_DIGEST_ALLOWED_EMAILS
if not allowed_emails:
logger.info(f"No allowed emails configured, skipping org {org_id}")
return
+
+ all_memberships = OrganizationMembership.objects.prefetch_related("user").filter(organization_id=org.id)
memberships: list[OrganizationMembership] = (
[m for m in all_memberships if m.user.email in allowed_emails]
if "*" not in allowed_emails
else list(all_memberships)
)
- date_suffix = timezone.now().strftime("%Y-%W")
- sent_count = 0
- failed_count = 0
+ # 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 = _DIGEST_PROJECT_SETTING_KEYS[NotificationSetting.ERROR_TRACKING_WEEKLY_DIGEST.value]
+ autoselect_counts: dict[int, dict] = {}
+ if any(setting_key not in (m.user.partial_notification_settings or {}) for m in memberships):
+ autoselect_counts = {
+ tid: summary
+ for tid in team_ids_with_exceptions
+ if (summary := error_tracking_api.get_exception_summary_for_team(all_org_teams[tid]))
+ and summary["exception_count"] > 0
+ }
+ # 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
- # Auto-select busiest project for first-time users
- if error_tracking_api.auto_select_project_for_user(user, org.id, team_digest_data):
+ if error_tracking_api.auto_select_project_for_user(user, org.id, autoselect_counts):
user.refresh_from_db(fields=["partial_notification_settings"])
- # Build per-user list of enabled teams
- user_team_sections = []
- disabled_team_names = []
- for team_id, data in team_digest_data.items():
- team = data["team"]
+ 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
if should_send_notification(user, NotificationSetting.ERROR_TRACKING_WEEKLY_DIGEST.value, team_id):
- user_team_sections.append(data)
+ enabled_team_ids.append(team_id)
else:
disabled_team_names.append(team.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
+
+ # 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 task re-raises at the end to autoretry.
+ team_digest_data: dict[int, dict] = {}
+ failed_team_ids: list[int] = []
+ for team_id in needed_team_ids:
+ try:
+ data = error_tracking_api.build_team_digest_data(all_org_teams[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 = (getattr(self.request, "retries", 0) or 0) >= (self.max_retries or 0)
+
+ sent_count = 0
+ failed_count = 0
+ deferred_count = 0
+ lacking_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)
@@ -2050,22 +2105,49 @@ def send_error_tracking_weekly_digest_for_org(org_id: str) -> None:
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}")
+ logger.exception("et_weekly_digest.send_failed", user_id=str(user.uuid), org_id=org_id)
failed_count += 1
continue
record.sent_at = timezone.now()
record.save()
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),
+ )
+ # Per-org, per-attempt summary. Counts are per-attempt but don't double-count across retries: each
+ # recipient is sent (and counted) in exactly one attempt, then skipped via the sent_at guard. So
+ # summing a field across an org's attempts gives the true total.
logger.info(
- f"Sent Error Tracking weekly digest to {sent_count} members for org {org_id} "
- 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}")
+ "et_weekly_digest.org_complete",
+ org_id=org_id,
+ retries=(getattr(self.request, "retries", 0) or 0),
+ is_final_attempt=is_final_attempt,
+ sent=sent_count,
+ 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 celery autoretry; already-sent recipients are skipped via MessagingRecord, and
+ # recipients missing a failed team were deferred above so the retry can complete them.
+ raise Exception(
+ f"Error Tracking weekly digest failed for {failed_count} recipients "
+ f"and {len(failed_team_ids)} team builds in org {org_id}"
+ )
def get_integration_display_name(kind: str) -> str:
diff --git a/products/error_tracking/backend/test/test_weekly_digest.py b/products/error_tracking/backend/test/test_weekly_digest.py
index dbcbefa20d2c..7071cc683834 100644
--- a/products/error_tracking/backend/test/test_weekly_digest.py
+++ b/products/error_tracking/backend/test/test_weekly_digest.py
@@ -1,4 +1,5 @@
import json
+import time
from datetime import timedelta
from uuid import uuid4
@@ -12,16 +13,19 @@ from django.utils import timezone
import requests
from parameterized import parameterized
-from posthog.models import Team
+from posthog.models import Team, User
+from posthog.models.messaging import MessagingRecord
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.facade import api as error_tracking_facade
from products.error_tracking.backend.models import (
ErrorTrackingIssue,
ErrorTrackingIssueFingerprintV2,
ErrorTrackingRecommendation,
+ sync_issues_to_clickhouse,
)
from products.error_tracking.backend.weekly_digest import (
auto_select_project_for_user,
@@ -62,6 +66,8 @@ class TestWeeklyDigest(ClickhouseTestMixin, APIBaseTest):
issue=issue,
fingerprint=str(uuid4()),
)
+ # issue_id_v2 resolves via the fingerprint issue state table in ClickHouse
+ sync_issues_to_clickhouse(issue_ids=[issue.id], team_id=self.team.pk)
return issue
def _create_exception_event(
@@ -74,6 +80,13 @@ class TestWeeklyDigest(ClickhouseTestMixin, APIBaseTest):
props: dict = {}
if issue_id:
props["$exception_issue_id"] = str(issue_id)
+ fingerprint = (
+ ErrorTrackingIssueFingerprintV2.objects.filter(issue_id=issue_id)
+ .values_list("fingerprint", flat=True)
+ .first()
+ )
+ if fingerprint:
+ props["$exception_fingerprint"] = fingerprint
if session_id:
props["$session_id"] = session_id
@@ -254,6 +267,11 @@ class TestWeeklyDigest(ClickhouseTestMixin, APIBaseTest):
)
ErrorTrackingIssue.objects.filter(id=old_issue.id).update(created_at=timezone.now() - timedelta(days=14))
ErrorTrackingIssueFingerprintV2.objects.create(team=self.team, issue=old_issue, fingerprint=str(uuid4()))
+ # first_seen is auto_now_add; backdate it so the issue counts as old (newness comes from state-table first_seen)
+ ErrorTrackingIssueFingerprintV2.objects.filter(issue=old_issue).update(
+ first_seen=timezone.now() - timedelta(days=14)
+ )
+ sync_issues_to_clickhouse(issue_ids=[old_issue.id], team_id=self.team.pk)
for _ in range(10):
self._create_exception_event(issue_id=old_issue.id)
flush_persons_and_events()
@@ -268,6 +286,38 @@ class TestWeeklyDigest(ClickhouseTestMixin, APIBaseTest):
result = get_new_issues_for_team(self.team)
assert result == []
+ def test_summary_not_suppressed_by_high_issue_cardinality(self):
+ # 101+ prior-week issues used to fill HogQL's injected LIMIT 100 and truncate away the current week
+ for _ in range(101):
+ self._create_exception_event(issue_id=str(uuid7()), timestamp=_days_ago(10))
+ issue = self._create_issue()
+ self._create_exception_event(issue_id=issue.id)
+ flush_persons_and_events()
+
+ result = get_exception_summary_for_team(self.team)
+
+ assert result["exception_count"] == 1
+ assert result["prev_exception_count"] == 101
+
+ def test_top_issues_follow_issue_merges(self):
+ issue_a = self._create_issue(name="OriginalIssue")
+ self._create_exception_event(issue_id=issue_a.id) # ingested while the fingerprint pointed at A
+ issue_b = ErrorTrackingIssue.objects.create(
+ id=uuid7(), team=self.team, status=ErrorTrackingIssue.Status.ACTIVE, name="MergedIntoIssue"
+ )
+ ErrorTrackingIssueFingerprintV2.objects.filter(issue=issue_a).update(issue=issue_b)
+ # force a later state version so the merge wins argMax
+ with patch("products.error_tracking.backend.models.time") as mock_time:
+ mock_time.time.return_value = time.time() + 10
+ sync_issues_to_clickhouse(issue_ids=[issue_b.id], team_id=self.team.pk)
+ flush_persons_and_events()
+
+ result = get_top_issues_for_team(self.team)
+
+ assert len(result) == 1
+ assert str(result[0]["id"]) == str(issue_b.id)
+ assert result[0]["name"] == "MergedIntoIssue"
+
def test_get_org_ids_with_exceptions(self):
issue = self._create_issue()
self._create_exception_event(issue_id=issue.id)
@@ -583,11 +633,14 @@ class TestWeeklyDigestWorkflowDelivery(ClickhouseTestMixin, APIBaseTest):
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)},
+ properties={"$exception_issue_id": str(issue.id), "$exception_fingerprint": fingerprint},
timestamp=_days_ago(1),
)
flush_persons_and_events()
@@ -626,3 +679,168 @@ class TestWeeklyDigestWorkflowDelivery(ClickhouseTestMixin, APIBaseTest):
# 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
+
+ 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
+
+ @override_settings(ERROR_TRACKING_WEEKLY_DIGEST_ALLOWED_EMAILS=["*"])
+ 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("products.error_tracking.backend.weekly_digest.requests.post"):
+ send_error_tracking_weekly_digest_for_org(str(self.organization.id))
+
+ 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}
+
+ @override_settings(ERROR_TRACKING_WEEKLY_DIGEST_ALLOWED_EMAILS=["*"])
+ 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()
+
+ real_build = error_tracking_facade.build_team_digest_data
+
+ def build_or_fail(team):
+ if team.pk == self.team.pk:
+ raise Exception("ClickHouse query failed")
+ return real_build(team)
+
+ 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,
+ ):
+ with pytest.raises(Exception, match="team builds"):
+ send_error_tracking_weekly_digest_for_org(str(self.organization.id))
+
+ # 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()
+
+ @override_settings(ERROR_TRACKING_WEEKLY_DIGEST_ALLOWED_EMAILS=["*"])
+ 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()
+
+ real_build = error_tracking_facade.build_team_digest_data
+ fail_team_a = {"on": True}
+
+ def build_or_recover(team):
+ if team.pk == self.team.pk and fail_team_a["on"]:
+ raise Exception("ClickHouse query failed")
+ return real_build(team)
+
+ 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,
+ ):
+ # Attempt 1: team A build fails, so the recipient is deferred and the task raises to retry.
+ with pytest.raises(Exception, match="team builds"):
+ send_error_tracking_weekly_digest_for_org(str(self.organization.id))
+ 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 fix.
+ fail_team_a["on"] = False
+ send_error_tracking_weekly_digest_for_org(str(self.organization.id))
+
+ 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}
+
+ @override_settings(ERROR_TRACKING_WEEKLY_DIGEST_ALLOWED_EMAILS=["*"])
+ 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()
+
+ real_build = error_tracking_facade.build_team_digest_data
+
+ def build_or_fail(team):
+ if team.pk == self.team.pk:
+ raise Exception("ClickHouse query failed")
+ return real_build(team)
+
+ 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,
+ ):
+ # 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.
+ send_error_tracking_weekly_digest_for_org.apply(args=[str(self.organization.id)], retries=5, throw=False)
+
+ 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]
+
+ @override_settings(ERROR_TRACKING_WEEKLY_DIGEST_ALLOWED_EMAILS=["*"])
+ 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("products.error_tracking.backend.weekly_digest.requests.post") as mock_post:
+ send_error_tracking_weekly_digest_for_org(str(self.organization.id))
+
+ digest = mock_post.call_args.kwargs["json"]["digest"]
+ assert digest["disabled_project_names"] == [team_b.name]
+ assert digest["excluded_project_count"] == 0
diff --git a/products/error_tracking/backend/weekly_digest.py b/products/error_tracking/backend/weekly_digest.py
index 67ec94c7b1a1..44b4494ae66e 100644
--- a/products/error_tracking/backend/weekly_digest.py
+++ b/products/error_tracking/backend/weekly_digest.py
@@ -33,36 +33,57 @@ def get_org_ids_with_exceptions() -> list[str]:
return org_ids
-def get_exception_summary_for_team(team: Team) -> dict:
- """Get filtered exception counts, ingestion failures, and prev week count for a single team."""
+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
+ instead of mistaking a failure for "no activity".
+ """
from posthog.hogql.query import execute_hogql_query
- tag_queries(product=ProductKey.ERROR_TRACKING, team_id=team.pk, name="weekly_digest:exception_summary")
+ tag_queries(product=ProductKey.ERROR_TRACKING, team_id=team.pk, name="weekly_digest:daily_rows")
- try:
- response = execute_hogql_query(
- query="""
- SELECT
- countIf(timestamp >= toStartOfDay(now()) - INTERVAL 7 DAY) as exception_count,
- countIf(timestamp >= toStartOfDay(now()) - INTERVAL 7 DAY AND issue_id IS NULL) as ingestion_failure_count,
- countIf(timestamp < toStartOfDay(now()) - INTERVAL 7 DAY) as prev_exception_count
- FROM events
- WHERE event = '$exception'
- AND timestamp >= toStartOfDay(now()) - INTERVAL 14 DAY
- AND timestamp < toStartOfDay(now())
- AND {filters}
- """,
- team=team,
- filters=HogQLFilters(filterTestAccounts=True),
- )
- except Exception:
- logger.exception(f"Failed to query exception summary for team {team.pk}")
- return {}
+ response = execute_hogql_query(
+ query="""
+ SELECT
+ toDate(timestamp) AS day,
+ count() AS day_count,
+ countIf(isNull(properties.$exception_issue_id)) AS failure_count
+ FROM events
+ WHERE event = '$exception'
+ AND timestamp >= toStartOfDay(now()) - INTERVAL 14 DAY
+ AND timestamp < toStartOfDay(now())
+ AND {filters}
+ GROUP BY day
+ ORDER BY day ASC
+ LIMIT 14
+ """,
+ team=team,
+ filters=HogQLFilters(filterTestAccounts=True),
+ )
+ return response.results or []
- if not response.results or not response.results[0]:
+
+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)
+ if not daily_rows:
return {}
- exception_count, ingestion_failure_count, prev_exception_count = response.results[0]
+ # ClickHouse returns team-timezone dates, so bucket against the team-local today, not UTC
+ today = timezone.now().astimezone(team.timezone_info).date()
+ exception_count = 0
+ ingestion_failure_count = 0
+ prev_exception_count = 0
+ for day, day_count, failure_count in daily_rows:
+ days_ago = (today - day).days
+ if 1 <= days_ago <= 7:
+ exception_count += day_count
+ ingestion_failure_count += failure_count
+ elif 8 <= days_ago <= 14:
+ prev_exception_count += day_count
+
return {
"exception_count": exception_count,
"ingestion_failure_count": ingestion_failure_count,
@@ -107,7 +128,11 @@ def auto_select_project_for_user(user: Any, org_id: int, team_exception_counts:
def get_exception_counts(team_ids: list[int] | None = None) -> list:
- """Teams with at least one exception in the last 7 days, used for digest routing."""
+ """Per-team exception counts over the last 7 days: ``(team_id, count)`` rows.
+
+ Used both for digest routing (which teams have any exceptions) and to pick a first-time user's
+ busiest project without needing a per-team build.
+ """
from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.workload import Workload
@@ -121,12 +146,13 @@ def get_exception_counts(team_ids: list[int] | None = None) -> list:
# nosemgrep: clickhouse-fstring-param-audit (team_filter is built from trusted code, not user input)
query = f"""
- SELECT DISTINCT team_id
+ SELECT team_id, count() AS exception_count
FROM events
WHERE event = '$exception'
AND timestamp >= toStartOfDay(now()) - INTERVAL 7 DAY
AND timestamp < toStartOfDay(now())
{team_filter}
+ GROUP BY team_id
"""
# Cross-team scan for a weekly batch job — keep it off the online cluster.
@@ -144,26 +170,24 @@ def get_crash_free_sessions(team: Team) -> dict:
tag_queries(product=ProductKey.ERROR_TRACKING, team_id=team.pk, name="weekly_digest:crash_free_sessions")
- try:
- response = execute_hogql_query(
- query="""
- SELECT
- uniqIf($session_id, timestamp >= toStartOfDay(now()) - INTERVAL 7 DAY) as total_sessions,
- uniqIf($session_id, event = '$exception' AND timestamp >= toStartOfDay(now()) - INTERVAL 7 DAY) as crash_sessions,
- uniqIf($session_id, timestamp < toStartOfDay(now()) - INTERVAL 7 DAY) as prev_total_sessions,
- uniqIf($session_id, event = '$exception' AND timestamp < toStartOfDay(now()) - INTERVAL 7 DAY) as prev_crash_sessions
- FROM events
- WHERE timestamp >= toStartOfDay(now()) - INTERVAL 14 DAY
- AND timestamp < toStartOfDay(now())
- AND notEmpty($session_id)
- AND {filters}
- """,
- team=team,
- filters=HogQLFilters(filterTestAccounts=True),
- )
- except Exception:
- logger.exception(f"Failed to query crash free sessions for team {team.pk}")
- return {}
+ # A ClickHouse failure propagates (task fails and retries) rather than being swallowed into an
+ # empty result. A successful query with no sessions still returns {} below.
+ response = execute_hogql_query(
+ query="""
+ SELECT
+ uniqIf($session_id, timestamp >= toStartOfDay(now()) - INTERVAL 7 DAY) as total_sessions,
+ uniqIf($session_id, event = '$exception' AND timestamp >= toStartOfDay(now()) - INTERVAL 7 DAY) as crash_sessions,
+ uniqIf($session_id, timestamp < toStartOfDay(now()) - INTERVAL 7 DAY) as prev_total_sessions,
+ uniqIf($session_id, event = '$exception' AND timestamp < toStartOfDay(now()) - INTERVAL 7 DAY) as prev_crash_sessions
+ FROM events
+ WHERE timestamp >= toStartOfDay(now()) - INTERVAL 14 DAY
+ AND timestamp < toStartOfDay(now())
+ AND notEmpty($session_id)
+ AND {filters}
+ """,
+ team=team,
+ filters=HogQLFilters(filterTestAccounts=True),
+ )
if not response.results or not response.results[0]:
return {}
@@ -194,41 +218,22 @@ def get_crash_free_sessions(team: Team) -> dict:
return result
-def get_daily_exception_counts(team: Team) -> list[dict]:
- """Get exception counts per day for the last 7 days"""
- from posthog.hogql.query import execute_hogql_query
-
- tag_queries(product=ProductKey.ERROR_TRACKING, team_id=team.pk, name="weekly_digest:daily_exception_counts")
-
- try:
- response = execute_hogql_query(
- query="""
- SELECT
- toDate(timestamp) as day,
- count() as day_count
- FROM events
- WHERE event = '$exception'
- AND timestamp >= toStartOfDay(now()) - INTERVAL 7 DAY
- AND timestamp < toStartOfDay(now())
- AND {filters}
- GROUP BY day
- ORDER BY day ASC
- """,
- team=team,
- filters=HogQLFilters(filterTestAccounts=True),
- )
- except Exception:
- logger.exception(f"Failed to query daily exception counts for team {team.pk}")
- return []
+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)
- results = response.results or []
- counts_by_day = {row[0].isoformat(): row[1] for row in results}
+ # ClickHouse returns team-timezone dates, so bucket against the team-local today, not UTC
+ today = timezone.now().astimezone(team.timezone_info).date()
+ counts_by_day: dict[datetime.date, int] = {}
+ for day, day_count, _failure_count in daily_rows:
+ if 1 <= (today - day).days <= 7:
+ counts_by_day[day] = day_count
- today = timezone.now().date()
- daily_counts = []
+ daily_counts: list[dict[str, Any]] = []
for i in range(7, 0, -1):
day = today - datetime.timedelta(days=i)
- count = counts_by_day.get(day.isoformat(), 0)
+ count = counts_by_day.get(day, 0)
daily_counts.append({"day": day.strftime("%a"), "count": count})
max_count = max((d["count"] for d in daily_counts), default=0)
@@ -240,110 +245,77 @@ def get_daily_exception_counts(team: Team) -> list[dict]:
return daily_counts
-def get_top_issues_for_team(team: Team) -> list[dict]:
- """Query top 5 issues by occurrence count for the last 7 days with sparkline data"""
- from posthog.hogql.query import execute_hogql_query
+def _query_issue_rows(team: Team) -> list:
+ """Ranked ``(issue_id, occurrence_count, daily_counts, is_new)`` rows for the last 7 days.
- from products.error_tracking.backend.models import ErrorTrackingIssue
+ ``LIMIT 5 BY is_new`` (≤10 rows) feeds both the top-issues and new-issues sections: the overall
+ top 5 is always a subset of the per-group union. ``issue_id_v2`` and ``issue_first_seen`` come
+ from the fingerprint issue state table, so merged issues are attributed and dated like the error
+ tracking UI. Newness is computed in-query — embedding issue ids would make the rendered SQL grow
+ with issue cardinality (ClickHouse caps query text at 1 MiB).
+ """
+ from posthog.hogql.query import execute_hogql_query
- tag_queries(product=ProductKey.ERROR_TRACKING, team_id=team.pk, name="weekly_digest:top_issues")
+ tag_queries(product=ProductKey.ERROR_TRACKING, team_id=team.pk, name="weekly_digest:issue_rows")
- try:
- response = execute_hogql_query(
- query="""
+ response = execute_hogql_query(
+ query="""
+ SELECT
+ issue_id,
+ sum(day_count) AS occurrence_count,
+ arrayMap(x -> tupleElement(x, 2), arraySort(x -> tupleElement(x, 1), groupArray(tuple(day, day_count)))) AS daily_counts,
+ if(min(first_seen) >= toStartOfDay(now()) - INTERVAL 7 DAY, 1, 0) AS is_new
+ FROM (
SELECT
- issue_id,
- sum(day_count) as occurrence_count,
- groupArray(day_count) as daily_counts
- FROM (
- SELECT issue_id, toDate(timestamp) as day, count(*) as day_count
- FROM events
- WHERE event = '$exception'
- AND timestamp >= toStartOfDay(now()) - INTERVAL 7 DAY
- AND timestamp < toStartOfDay(now())
- AND issue_id IS NOT NULL
- AND {filters}
- GROUP BY issue_id, day
- ORDER BY day ASC
- )
- GROUP BY issue_id
- ORDER BY occurrence_count DESC
- LIMIT 5
- """,
- team=team,
- filters=HogQLFilters(filterTestAccounts=True),
- )
- except Exception:
- logger.exception(f"Failed to query top issues for team {team.pk}")
- return []
-
- if not response.results:
- return []
-
- issue_ids = [row[0] for row in response.results if row[0]]
- issues_by_id = {str(issue.id): issue for issue in ErrorTrackingIssue.objects.filter(team=team, id__in=issue_ids)}
-
- return _build_issues_list(response.results, issues_by_id, team)
-
+ issue_id_v2 AS issue_id,
+ toDate(timestamp) AS day,
+ count() AS day_count,
+ min(issue_first_seen) AS first_seen
+ FROM events
+ WHERE event = '$exception'
+ AND timestamp >= toStartOfDay(now()) - INTERVAL 7 DAY
+ AND timestamp < toStartOfDay(now())
+ AND isNotNull(issue_id_v2)
+ AND {filters}
+ GROUP BY issue_id, day
+ )
+ GROUP BY issue_id
+ ORDER BY occurrence_count DESC
+ LIMIT 5 BY is_new
+ LIMIT 10
+ """,
+ team=team,
+ filters=HogQLFilters(filterTestAccounts=True),
+ )
+ return response.results or []
-def get_new_issues_for_team(team: Team) -> list[dict]:
- """Query top 5 issues first seen in the last 7 days ranked by occurrence count with sparkline data"""
- from posthog.hogql import ast
- from posthog.hogql.query import execute_hogql_query
+def _issues_payload(issue_rows: list, team: Team) -> list[dict]:
+ """Top 5 of the given ranked rows, hydrated with issue names from Postgres."""
from products.error_tracking.backend.models import ErrorTrackingIssue
- tag_queries(product=ProductKey.ERROR_TRACKING, team_id=team.pk, name="weekly_digest:new_issues")
-
- week_ago = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0) - datetime.timedelta(days=7)
- new_issue_objects = list(
- ErrorTrackingIssue.objects.filter(team=team, created_at__gte=week_ago).values_list("id", flat=True)
- )
-
- if not new_issue_objects:
+ ranked = sorted(issue_rows, key=lambda row: row[1], reverse=True)[:5]
+ if not ranked:
return []
- new_issue_ids = [str(i) for i in new_issue_objects]
+ ranked = [(issue_id, occurrence_count, daily_counts) for issue_id, occurrence_count, daily_counts, _ in ranked]
+ issue_ids = [row[0] for row in ranked]
+ issues_by_id = {str(issue.id): issue for issue in ErrorTrackingIssue.objects.filter(team=team, id__in=issue_ids)}
+ return _build_issues_list(ranked, issues_by_id, team)
- try:
- response = execute_hogql_query(
- query="""
- SELECT
- issue_id,
- sum(day_count) as occurrence_count,
- groupArray(day_count) as daily_counts
- FROM (
- SELECT issue_id, toDate(timestamp) as day, count(*) as day_count
- FROM events
- WHERE event = '$exception'
- AND timestamp >= toStartOfDay(now()) - INTERVAL 7 DAY
- AND timestamp < toStartOfDay(now())
- AND issue_id IN {issue_ids}
- AND {filters}
- GROUP BY issue_id, day
- ORDER BY day ASC
- )
- GROUP BY issue_id
- ORDER BY occurrence_count DESC
- LIMIT 5
- """,
- team=team,
- placeholders={"issue_ids": ast.Constant(value=new_issue_ids)},
- filters=HogQLFilters(filterTestAccounts=True),
- )
- except Exception:
- logger.exception(f"Failed to query new issues for team {team.pk}")
- return []
- if not response.results:
- return []
+def get_top_issues_for_team(team: Team, issue_rows: list | None = None) -> list[dict]:
+ """Top 5 issues by occurrence count for the last 7 days with sparkline data."""
+ if issue_rows is None:
+ issue_rows = _query_issue_rows(team)
+ return _issues_payload(issue_rows, team)
- result_issue_ids = [row[0] for row in response.results if row[0]]
- issues_by_id = {
- str(issue.id): issue for issue in ErrorTrackingIssue.objects.filter(team=team, id__in=result_issue_ids)
- }
- return _build_issues_list(response.results, issues_by_id, team)
+def get_new_issues_for_team(team: Team, issue_rows: list | None = None) -> list[dict]:
+ """Top 5 issues first seen in the last 7 days ranked by occurrence count with sparkline data."""
+ if issue_rows is None:
+ issue_rows = _query_issue_rows(team)
+ return _issues_payload([row for row in issue_rows if row[3]], team)
def _build_issues_list(results: list, issues_by_id: dict, team: Team) -> list[dict]:
@@ -422,10 +394,14 @@ def build_team_digest_data(team: Team) -> dict[str, Any] | None:
# 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)
+ # Two bounded ClickHouse passes + crash-free: three queries per team instead of five.
+ 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
+ issue_rows = _query_issue_rows(team)
+
return {
"team": team,
"exception_count": counts["exception_count"],
@@ -433,9 +409,9 @@ def build_team_digest_data(team: Team) -> dict[str, Any] | None:
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),
+ "top_issues": get_top_issues_for_team(team, issue_rows),
+ "new_issues": get_new_issues_for_team(team, issue_rows),
+ "daily_counts": get_daily_exception_counts(team, daily_rows),
"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",