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): unfiltered digest fallback on last two attempts (#78807)

Aleksander Błaszkiewicz90a5405a0e59
diff --git a/products/error_tracking/backend/temporal/weekly_digest/activities.py b/products/error_tracking/backend/temporal/weekly_digest/activities.py
index 1ea5d78c7fe0..ba588d1ef06e 100644
--- a/products/error_tracking/backend/temporal/weekly_digest/activities.py
+++ b/products/error_tracking/backend/temporal/weekly_digest/activities.py
@@ -90,7 +90,9 @@ def _send_org_digest(inputs: SendOrgDigestInputs, attempt: int) -> SendOrgDigest
"""Send one combined weekly error tracking digest per user in an org via the delivery workflow.
``attempt`` is Temporal's 1-based attempt counter; ``attempt >= inputs.max_attempts`` marks
- the final attempt, which sends partial digests instead of deferring recipients.
+ the final attempt, which sends partial digests instead of deferring recipients. On the last
+ two attempts, a team whose filtered build fails is rebuilt without its test account filters,
+ with the section flagged so the email can disclose it.
"""
org_id = inputs.org_id
try:
@@ -123,7 +125,14 @@ def _send_org_digest(inputs: SendOrgDigestInputs, attempt: int) -> SendOrgDigest
daily_rows_by_team: dict[int, list] = {}
if any(setting_key not in (m.user.partial_notification_settings or {}) for m in memberships):
for tid in team_ids_with_exceptions:
- daily_rows_by_team[tid] = weekly_digest.query_daily_rows(all_org_teams[tid])
+ try:
+ daily_rows_by_team[tid] = weekly_digest.query_daily_rows(all_org_teams[tid])
+ except Exception:
+ # A team whose filtered query is permanently broken (bad regex, deleted cohort) must
+ # not sink the whole org here, before the build loop below can defer or fall back.
+ # It just goes unranked, so auto-select can't enroll anyone onto it.
+ logger.exception("et_weekly_digest.autoselect_rank_failed", team_id=tid, org_id=org_id)
+ continue
summary = weekly_digest.get_exception_summary_for_team(all_org_teams[tid], daily_rows_by_team[tid])
if summary and summary["exception_count"] > 0:
autoselect_counts[tid] = summary
@@ -186,13 +195,30 @@ def _send_org_digest(inputs: SendOrgDigestInputs, attempt: int) -> SendOrgDigest
# Temporal retries it.
team_digest_data: dict[int, dict] = {}
failed_team_ids: list[int] = []
+ # A team still failing this deep into the retries is most likely failing because of its test
+ # account filters (broken regex, deleted cohort), which no retry will fix. The last two attempts
+ # trade filtered accuracy for delivery: rebuild without the filters, and flag the section so the
+ # email can disclose it. Keeping it off earlier attempts means a transient ClickHouse error
+ # can't produce an unfiltered digest for a team whose filters work fine.
+ unfiltered_fallback = attempt >= inputs.max_attempts - 1
for team_id in needed_team_ids:
try:
data = weekly_digest.build_team_digest_data(all_org_teams[team_id], daily_rows_by_team.get(team_id))
except Exception:
- logger.exception("et_weekly_digest.team_build_failed", team_id=team_id, org_id=org_id)
- failed_team_ids.append(team_id)
- continue
+ if not unfiltered_fallback:
+ logger.exception("et_weekly_digest.team_build_failed", team_id=team_id, org_id=org_id)
+ failed_team_ids.append(team_id)
+ continue
+ logger.exception("et_weekly_digest.team_build_filtered_failed", team_id=team_id, org_id=org_id)
+ try:
+ # No cached daily_rows: those were queried with the filters applied, and the
+ # rebuilt sections must be consistently unfiltered.
+ data = weekly_digest.build_team_digest_data(all_org_teams[team_id], filter_test_accounts=False)
+ 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
+ logger.warning("et_weekly_digest.team_built_without_test_account_filters", team_id=team_id, org_id=org_id)
if data:
team_digest_data[team_id] = data
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 491dc7031fac..bf101f464f2d 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
@@ -390,7 +390,9 @@ class TestSendOrgDigest(ClickhouseTestMixin, APIBaseTest):
}
self.user.save()
- def build_or_fail(team, daily_rows=None):
+ # Fails with and without test account filters, like a timeout: the unfiltered
+ # fallback on the last attempts must not rescue it.
+ def build_or_fail(team, daily_rows=None, filter_test_accounts=True):
if team.pk == self.team.pk:
raise Exception("ClickHouse query failed")
return build_team_digest_data(team, daily_rows)
@@ -410,6 +412,78 @@ class TestSendOrgDigest(ClickhouseTestMixin, APIBaseTest):
# A raising activity returns no result, so the count only reaches the workflow via details.
assert list(exc_info.value.details) == [1]
+ @parameterized.expand(
+ [
+ ("before_last_two_attempts_no_fallback", 4, 0),
+ ("second_to_last_attempt_falls_back", 5, 1),
+ ("final_attempt_falls_back", 6, 1),
+ ]
+ )
+ def test_broken_test_account_filter_falls_back_to_unfiltered_on_last_two_attempts(
+ self, _name, attempt, expected_sends
+ ):
+ # RE2 rejects negative lookahead, so every filtered digest query for this team raises during
+ # HogQL preparation (the failure shape seen in production). Only the unfiltered rebuild on the
+ # last two attempts can ever deliver this team's digest, and it must disclose itself via
+ # test_account_filters_skipped; falling back any earlier would mean a transient error could
+ # ship an unfiltered digest for a team whose filters work.
+ self.team.test_account_filters = [
+ {"key": "$host", "type": "event", "operator": "regex", "value": "^(?!.*localhost).*$"}
+ ]
+ self.team.save()
+ _create_event(distinct_id="user_a", event="$exception", team=self.team, properties={}, timestamp=_days_ago(1))
+ flush_persons_and_events()
+
+ self.user.partial_notification_settings = {
+ "error_tracking_weekly_digest_project_enabled": {str(self.team.id): True}
+ }
+ self.user.save()
+
+ with patch(_WEBHOOK_POST) as mock_post:
+ if expected_sends:
+ result = self._run(attempt=attempt)
+ assert result == SendOrgDigestResult(sent=1, teams_built=1)
+ else:
+ with pytest.raises(ApplicationError, match="team builds"):
+ self._run(attempt=attempt)
+
+ assert mock_post.call_count == expected_sends
+ if expected_sends:
+ section = mock_post.call_args.kwargs["json"]["digest"]["project_sections"][0]
+ assert section["test_account_filters_skipped"] is True
+ assert section["exception_count"] == "1"
+
+ def test_first_time_user_auto_select_survives_broken_filter_team(self):
+ # The auto-select ranking pass queries every team with exceptions. A broken-filter team
+ # raising there used to fail the whole activity before the build loop could defer or fall
+ # back, so no one in the org got any digest. The healthy team must still rank, enroll, and send.
+ self.team.test_account_filters = [
+ {"key": "$host", "type": "event", "operator": "regex", "value": "^(?!.*localhost).*$"}
+ ]
+ self.team.save()
+ _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.role_at_organization = "engineering"
+ self.user.save()
+
+ with patch(_WEBHOOK_POST) as mock_post:
+ result = self._run(attempt=1)
+
+ # The broken team goes unranked, so enrollment lands on the healthy team and its digest
+ # sends. The broken team isn't enabled for anyone, so nothing needs its build and the
+ # activity completes instead of raising.
+ assert result == SendOrgDigestResult(sent=1, teams_built=1)
+ self.user.refresh_from_db()
+ project_enabled = (self.user.partial_notification_settings or {}).get(
+ "error_tracking_weekly_digest_project_enabled", {}
+ )
+ assert project_enabled == {str(team_b.pk): True}
+ sections = mock_post.call_args.kwargs["json"]["digest"]["project_sections"]
+ assert [s["team_name"] for s in sections] == [team_b.name]
+ assert sections[0]["test_account_filters_skipped"] is False
+
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()
diff --git a/products/error_tracking/backend/weekly_digest.py b/products/error_tracking/backend/weekly_digest.py
index 99fd911ca20d..1676a9e29894 100644
--- a/products/error_tracking/backend/weekly_digest.py
+++ b/products/error_tracking/backend/weekly_digest.py
@@ -39,7 +39,7 @@ def get_org_ids_with_exceptions() -> list[str]:
return org_ids
-def query_daily_rows(team: Team) -> list:
+def query_daily_rows(team: Team, filter_test_accounts: bool = True) -> 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
@@ -69,7 +69,7 @@ def query_daily_rows(team: Team) -> list:
LIMIT 14
""",
team=team,
- filters=HogQLFilters(filterTestAccounts=True),
+ filters=HogQLFilters(filterTestAccounts=filter_test_accounts),
# Weekly batch job: Celery pinned this to the offline cluster process-wide, Temporal does not.
workload=Workload.OFFLINE,
ch_user=ClickHouseUser.ERROR_TRACKING,
@@ -194,7 +194,7 @@ def get_exception_counts(team_ids: list[int] | None = None) -> list:
return results if isinstance(results, list) else []
-def get_crash_free_sessions(team: Team) -> dict:
+def get_crash_free_sessions(team: Team, filter_test_accounts: bool = True) -> dict:
"""Calculate crash free sessions rate for the last 7 days with previous week comparison."""
from posthog.hogql.constants import HogQLGlobalSettings
from posthog.hogql.query import execute_hogql_query
@@ -224,7 +224,7 @@ def get_crash_free_sessions(team: Team) -> dict:
AND {filters}
""",
team=team,
- filters=HogQLFilters(filterTestAccounts=True),
+ filters=HogQLFilters(filterTestAccounts=filter_test_accounts),
# Unfiltered 14-day session scan — the heaviest query here. Must stay off the online cluster.
workload=Workload.OFFLINE,
ch_user=ClickHouseUser.ERROR_TRACKING,
@@ -287,7 +287,7 @@ def get_daily_exception_counts(team: Team, daily_rows: list | None = None) -> li
return daily_counts
-def _query_issue_rows(team: Team) -> list:
+def _query_issue_rows(team: Team, filter_test_accounts: bool = True) -> list:
"""Ranked ``(issue_id, occurrence_count, daily_counts, is_new)`` rows for the last 7 days.
``LIMIT 5 BY is_new`` (≤10 rows) feeds both the top-issues and new-issues sections: the overall
@@ -331,7 +331,7 @@ def _query_issue_rows(team: Team) -> list:
LIMIT 10
""",
team=team,
- filters=HogQLFilters(filterTestAccounts=True),
+ filters=HogQLFilters(filterTestAccounts=filter_test_accounts),
# Weekly batch job: Celery pinned this to the offline cluster process-wide, Temporal does not.
workload=Workload.OFFLINE,
ch_user=ClickHouseUser.ERROR_TRACKING,
@@ -445,11 +445,17 @@ def get_source_maps_recommendation_for_team(team: Team) -> dict | None:
}
-def build_team_digest_data(team: Team, daily_rows: list | None = None) -> dict[str, Any] | None:
+def build_team_digest_data(
+ team: Team, daily_rows: list | None = None, filter_test_accounts: bool = True
+) -> dict[str, Any] | None:
"""Assemble all digest data for one team, or None when it had no exceptions this week.
``daily_rows`` lets a caller that already queried the team's 14-day rows hand them in
instead of paying for the same query twice.
+
+ ``filter_test_accounts=False`` builds from unfiltered queries, for teams whose test account
+ filters make every filtered query fail. The result carries ``test_account_filters_skipped``
+ so the email template can disclose that the filters were not applied.
"""
# 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.
@@ -457,12 +463,12 @@ def build_team_digest_data(team: Team, daily_rows: list | None = None) -> dict[s
# Two bounded ClickHouse passes + crash-free: three queries per team instead of five.
if daily_rows is None:
- daily_rows = query_daily_rows(team)
+ daily_rows = query_daily_rows(team, filter_test_accounts)
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)
+ issue_rows = _query_issue_rows(team, filter_test_accounts)
return {
"team": team,
@@ -474,8 +480,9 @@ def build_team_digest_data(team: Team, daily_rows: list | None = None) -> dict[s
"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),
+ "crash_free": get_crash_free_sessions(team, filter_test_accounts),
"source_maps_recommendation": get_source_maps_recommendation_for_team(team),
+ "test_account_filters_skipped": not filter_test_accounts,
"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),
}