:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(cdp): notify projects whose destination filters cannot compile (#102960)
Meikel Ratz04593901de90
diff --git a/posthog/management/commands/notify_uncompilable_hog_function_filters.py b/posthog/management/commands/notify_uncompilable_hog_function_filters.pynew file mode 100644index 000000000000..c7bfffd85684--- /dev/null+++ b/posthog/management/commands/notify_uncompilable_hog_function_filters.py@@ -0,0 +1,109 @@+import logging+from argparse import ArgumentParser+from typing import Any++from django.core.management.base import BaseCommand, CommandError++from posthog.tasks.email import send_hog_function_filters_uncompilable++from products.cdp.backend.models.hog_functions.hog_function import HogFunction, HogFunctionType++logger = logging.getLogger(__name__)+++class Command(BaseCommand):+ help = (+ "Find enabled hog functions whose filters failed to compile, and tell their project. "+ "A function in this state matches nothing and delivers nothing, because the filter "+ "bytecode is null and evaluating it raises on every event."+ )++ def add_arguments(self, parser: ArgumentParser) -> None:+ parser.add_argument(+ "--apply",+ action="store_true",+ help="Send the emails. Without this the command only prints what it would do.",+ )+ parser.add_argument(+ "--disable",+ action="store_true",+ help=(+ "Also set enabled=false on each function. Off by default: the function already "+ "delivers nothing, and disabling means the owner has to re-enable it after fixing."+ ),+ )+ parser.add_argument("--team-id", type=int, help="Limit to one team.")+ parser.add_argument("--limit", type=int, help="Stop after this many functions.")++ def handle(self, *args: Any, **options: Any) -> None:+ apply: bool = options["apply"]+ disable: bool = options["disable"]++ # `bytecode` is set to null alongside every bytecode_error, so the error alone identifies+ # the state. Matching on the message would miss the compile failures that are not about+ # cohorts.+ # Destinations only. Transformations, source webhooks and internal destinations compile+ # bytecode too and can carry the same error, but the email names a destination and links to+ # the destinations page, and an internal destination is ours rather than the customer's.+ queryset = HogFunction.objects.filter(deleted=False, enabled=True, type=HogFunctionType.DESTINATION).exclude(+ filters__bytecode_error__isnull=True+ )+ team_id = options["team_id"]+ if team_id is not None:+ # `if team_id:` would read a mistyped 0 as "every team" and hand the whole fleet to+ # --apply. No team has id 0, so the filter reports nothing instead.+ queryset = queryset.filter(team_id=team_id)+ queryset = queryset.select_related("team", "created_by").order_by("team_id", "id")+ limit = options["limit"]+ if limit is not None:+ # `if limit:` would read 0 as "no limit" and hand the whole fleet to --apply, and a+ # negative value raises inside the slice.+ if limit < 1:+ raise CommandError("--limit must be 1 or more")+ queryset = queryset[:limit]++ # Collected first so nothing is written while the queryset is still being walked.+ by_team: dict[int, list[HogFunction]] = {}+ for hog_function in queryset:+ by_team.setdefault(hog_function.team_id, []).append(hog_function)+ error = (hog_function.filters or {}).get("bytecode_error", "")+ self.stdout.write(+ f"team={hog_function.team_id} id={hog_function.id} type={hog_function.type} "+ f"name={hog_function.name!r} error={error!r}"+ )++ count = sum(len(functions) for functions in by_team.values())+ self.stdout.write("")++ # One team at a time, and the email for a team goes out right after that team's writes.+ # A broker or database failure part way through therefore leaves later teams untouched,+ # and the line printed per team says how far the run got.+ #+ # The gap this does not close: a send that fails after the disable leaves that team's+ # destinations off and unnotified, and a plain re-run will not find them because the scope+ # is enabled destinations. Re-enable them and re-run with --team-id.+ for team_id, functions in sorted(by_team.items()):+ if apply and disable:+ for hog_function in functions:+ hog_function.enabled = False+ # save() rather than a queryset update: the post_save receiver is what tells+ # the workers to reload, and without it the destination stays live in their+ # cache. The cost is that save() recompiles the filters, which fails again and+ # rewrites the same bytecode_error. That is wasted work, not a wrong result.+ hog_function.save(update_fields=["enabled"])++ if apply:+ # One email per project. A shared mistake breaks many destinations at once, so a+ # task per destination would mail the same admins the same root cause repeatedly.+ send_hog_function_filters_uncompilable.delay(team_id, [str(f.id) for f in functions])++ self.stdout.write(f"team={team_id}: {len(functions)} destination(s)" + (" queued" if apply else ""))++ self.stdout.write("")+ self.stdout.write(f"{count} enabled destination(s) with uncompilable filters across {len(by_team)} team(s)")+ if not apply:+ self.stdout.write("Dry run. Re-run with --apply to send the emails.")+ elif disable:+ self.stdout.write("Disabled each destination and emailed each project's admins and creators.")+ else:+ self.stdout.write("Emailed each project's admins and creators.")diff --git a/posthog/management/commands/test/test_notify_uncompilable_hog_function_filters.py b/posthog/management/commands/test/test_notify_uncompilable_hog_function_filters.pynew file mode 100644index 000000000000..08b174ead092--- /dev/null+++ b/posthog/management/commands/test/test_notify_uncompilable_hog_function_filters.py@@ -0,0 +1,130 @@+from io import StringIO++from posthog.test.base import BaseTest+from unittest.mock import patch++from django.core.management import call_command+from django.core.management.base import CommandError++from posthog.models.team.team import Team++from products.cdp.backend.models.hog_functions.hog_function import HogFunction, HogFunctionType++TASK = "posthog.management.commands.notify_uncompilable_hog_function_filters.send_hog_function_filters_uncompilable"+++class TestNotifyUncompilableHogFunctionFilters(BaseTest):+ def _broken(+ self,+ name: str = "Broken",+ enabled: bool = True,+ type: str = HogFunctionType.DESTINATION,+ team: Team | None = None,+ ) -> HogFunction:+ hog_function = HogFunction.objects.create(team=team or self.team, name=name, enabled=enabled, type=type)+ # Past save(), which recompiles the filters and clears the error. This is the shape the row+ # has in the database.+ HogFunction.objects.filter(id=hog_function.id).update(+ filters={"bytecode": None, "bytecode_error": "Cohort membership can't be evaluated"}+ )+ return hog_function++ def test_dry_run_reports_without_emailing_or_disabling(self) -> None:+ hog_function = self._broken()+ out = StringIO()++ with patch(TASK) as task:+ call_command("notify_uncompilable_hog_function_filters", stdout=out)++ task.delay.assert_not_called()+ hog_function.refresh_from_db()+ assert hog_function.enabled is True+ assert str(hog_function.id) in out.getvalue()+ assert "Dry run" in out.getvalue()++ def test_apply_emails_each_function_and_leaves_it_enabled(self) -> None:+ hog_function = self._broken()++ with patch(TASK) as task:+ call_command("notify_uncompilable_hog_function_filters", "--apply", stdout=StringIO())++ task.delay.assert_called_once_with(self.team.id, [str(hog_function.id)])+ hog_function.refresh_from_db()+ assert hog_function.enabled is True++ def test_disable_turns_the_function_off(self) -> None:+ hog_function = self._broken()++ with patch(TASK) as task:+ call_command("notify_uncompilable_hog_function_filters", "--apply", "--disable", stdout=StringIO())++ task.delay.assert_called_once_with(self.team.id, [str(hog_function.id)])+ hog_function.refresh_from_db()+ assert hog_function.enabled is False++ def test_leaves_every_type_other_than_a_destination_alone(self) -> None:+ # Transformations, source webhooks and internal destinations compile bytecode too and carry+ # the same error, but the email names a destination and links to the destinations page.+ for hog_type in (+ HogFunctionType.TRANSFORMATION,+ HogFunctionType.SOURCE_WEBHOOK,+ HogFunctionType.INTERNAL_DESTINATION,+ ):+ self._broken(name=f"Broken {hog_type}", type=hog_type)+ out = StringIO()++ with patch(TASK) as task:+ call_command("notify_uncompilable_hog_function_filters", "--apply", stdout=out)++ task.delay.assert_not_called()+ assert "0 enabled destination(s)" in out.getvalue()++ def test_scopes_to_one_team_and_selects_nothing_for_a_zero(self) -> None:+ other_team = Team.objects.create(organization=self.organization, name="Other project")+ mine = self._broken()+ self._broken(team=other_team)+ out = StringIO()++ with patch(TASK) as scoped:+ call_command("notify_uncompilable_hog_function_filters", "--apply", "--team-id", self.team.id, stdout=out)+ # `if team_id:` read a mistyped 0 as "every team" and would hand the whole fleet to --apply.+ with patch(TASK) as zero:+ call_command("notify_uncompilable_hog_function_filters", "--apply", "--team-id", 0, stdout=out)++ scoped.delay.assert_called_once_with(self.team.id, [str(mine.id)])+ zero.delay.assert_not_called()++ def test_a_failed_send_leaves_later_teams_untouched(self) -> None:+ # The email for a team goes out right after that team's writes, so a broker failure part+ # way through cannot disable a project it never told.+ other_team = Team.objects.create(organization=self.organization, name="Other")+ self._broken(name="Mine")+ theirs = self._broken(name="Theirs", team=other_team)++ with patch(TASK) as task:+ task.delay.side_effect = RuntimeError("broker down")+ with self.assertRaises(RuntimeError):+ call_command("notify_uncompilable_hog_function_filters", "--apply", "--disable", stdout=StringIO())++ theirs.refresh_from_db()+ assert theirs.enabled is True++ def test_rejects_a_limit_below_one(self) -> None:+ # `if limit:` read 0 as "no limit" and would hand the whole fleet to --apply.+ self._broken()++ with patch(TASK) as task, self.assertRaises(CommandError):+ call_command("notify_uncompilable_hog_function_filters", "--apply", "--limit", "0", stdout=StringIO())++ task.delay.assert_not_called()++ def test_skips_functions_that_compile_and_functions_already_off(self) -> None:+ HogFunction.objects.create(team=self.team, name="Healthy", enabled=True)+ self._broken(name="Already off", enabled=False)+ out = StringIO()++ with patch(TASK) as task:+ call_command("notify_uncompilable_hog_function_filters", "--apply", stdout=out)++ task.delay.assert_not_called()+ assert "0 enabled destination(s)" in out.getvalue()diff --git a/posthog/tasks/email.py b/posthog/tasks/email.pyindex 97ece3115b69..7cab742f3ab2 100644--- a/posthog/tasks/email.py+++ b/posthog/tasks/email.py@@ -1,4 +1,5 @@import uuid+import hashlibimport datetimefrom enum import Enumfrom typing import Any, Literal, Optional, cast@@ -17,6 +18,7 @@ from prometheus_client import Counter, Histogramfrom posthog.caching.login_device_cache import check_and_cache_login_devicefrom posthog.cloud_utils import is_cloudfrom posthog.constants import AUTH_BACKEND_DISPLAY_NAMES, INVITE_DAYS_VALIDITY+from posthog.dataclasses import frozenfrom posthog.email import (EMAIL_TASK_KWARGS,EmailMessage,@@ -760,6 +762,101 @@ def send_hog_function_disabled(hog_function_id: str) -> None:message.send()+@frozen+class UncompilableDestination:+ """One destination the email lists, with the reason its filters would not compile."""++ hog_function: HogFunction+ bytecode_error: str+++@shared_task(**EMAIL_TASK_KWARGS)+@with_team_scope()+def send_hog_function_filters_uncompilable(team_id: int, hog_function_ids: list[str]) -> None:+ """+ Tell a project which of its destinations have filters that cannot be compiled.++ One email per project rather than per destination. A single mistake breaks many at once: a+ team's test-account filters are shared, so adding a cohort to them breaks every destination+ that filters test accounts. A message per destination would mail the same admins the same root+ cause repeatedly, and the campaign key could not collapse them because it named the function.++ Deliberately not gated by the pipeline-error notification settings, matching+ send_email_sending_suspended: the destinations send nothing until someone edits them, and a+ muted notification would leave that indefinitely. Recipients are the project admins, who can+ act on it, plus the creators of the destinations listed.+ """+ if not is_email_available(with_absolute_urls=True):+ return+ team = Team.objects.filter(id=team_id).first()+ if team is None:+ return++ # Archived between the command's enqueue and the worker picking the task up: the email would+ # link to a page the owner just archived. A row that has gone entirely is dropped the same way,+ # rather than letting the retry policy try again for work that cannot succeed.+ hog_functions = HogFunction.objects.prefetch_related("created_by").filter(+ team_id=team_id, id__in=hog_function_ids, deleted=False+ )+ broken = [+ UncompilableDestination(hog_function=hog_function, bytecode_error=error)+ for hog_function in hog_functions+ if (error := (hog_function.filters or {}).get("bytecode_error"))+ ]+ if not broken:+ return+ # The id breaks ties: two destinations can share a name, and the query has no ORDER BY, so+ # without it the same breakage can fingerprint differently between runs and email twice.+ broken.sort(key=lambda entry: (entry.hog_function.name or "", entry.hog_function.id))++ recipients = {membership.user for membership in _get_project_admins_to_notify_of_email_sending_suspension(team)}+ # A creator may have left the organization, or kept organization membership while losing access+ # to this project. The email names the project, the destinations and the filter errors, so a+ # creator is included by effective access to this team, not by organization membership.+ for entry in broken:+ creator = entry.hog_function.created_by+ if not creator or creator in recipients:+ continue+ creator_membership = OrganizationMembership.objects.filter(+ organization_id=team.organization_id, user=creator+ ).first()+ if not creator_membership:+ continue+ effective_level = (+ UserPermissions(creator)+ .team(team)+ .effective_membership_level_for_parent_membership(creator_membership.organization, creator_membership)+ )+ if effective_level is not None:+ recipients.add(creator)+ if not recipients:+ return++ # Keyed on the destinations, their errors and whether each is still on. A re-run over the same+ # breakage must not email the same people twice, while a new breakage must. The enabled state+ # is in the key because an operator who notifies first and escalates to --disable later has to+ # be able to tell the recipients the destinations are now off. sha256 rather than hash(), which+ # is seeded per process and would give the same set a new key after a worker restart.+ fingerprint = ";".join(+ f"{entry.hog_function.id}:{entry.bytecode_error}:{int(entry.hog_function.enabled)}" for entry in broken+ )+ digest = hashlib.sha256(fingerprint.encode("utf-8")).hexdigest()[:16]+ # No urgency prefix in the subject: a bracketed one got the suspension emails filtered to junk+ # in production. single_line because a CR or LF in a name raises BadHeaderError, which the send+ # path swallows, so every recipient would silently lose the email.+ count = len(broken)+ noun = "destination" if count == 1 else "destinations"+ message = EmailMessage(+ campaign_key=f"hog_function_filters_uncompilable_{team_id}_{digest}",+ subject=f"{count} {noun} in project '{single_line(str(team))}' are not delivering events",+ template_name="hog_function_filters_uncompilable",+ template_context={"team": team, "broken": broken},+ )+ for user in recipients:+ message.add_user_recipient(user)+ message.send()++def _get_project_admins_to_notify_of_email_sending_suspension(team: Team) -> list[OrganizationMembership]:# Admin+ only: they're the ones who can act on the issue (contact support, clean up lists).# Everyone else with project access still sees the persistent in-app banner. Nodiff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambrindex 1e3b45e2aa4a..9e79f9194712 100644--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr@@ -48,6 +48,7 @@'posthog.tasks.email.send_fatal_plugin_error','posthog.tasks.email.send_feature_flags_secure_api_key_exposed','posthog.tasks.email.send_hog_function_disabled',+ 'posthog.tasks.email.send_hog_function_filters_uncompilable','posthog.tasks.email.send_hog_functions_daily_digest','posthog.tasks.email.send_hog_functions_digest_email','posthog.tasks.email.send_integration_access_request',diff --git a/posthog/tasks/test/test_email.py b/posthog/tasks/test/test_email.pyindex ce061c83be7a..be42f22be94e 100644--- a/posthog/tasks/test/test_email.py+++ b/posthog/tasks/test/test_email.py@@ -1,4 +1,5 @@import uuid+import hashlibimport datetime as dtfrom typing import castfrom uuid import uuid4@@ -15,6 +16,7 @@ from django.utils import timezonefrom parameterized import parameterizedfrom posthog.api.authentication import password_reset_token_generator+from posthog.constants import AvailableFeaturefrom posthog.models import Comment, Organization, Team, Userfrom posthog.models.app_metrics2.sql import TRUNCATE_APP_METRICS2_TABLE_SQLfrom posthog.models.instance_setting import set_instance_setting@@ -36,6 +38,7 @@ from posthog.tasks.email import (send_external_data_failure_digest,send_fatal_plugin_error,send_hog_function_disabled,+ send_hog_function_filters_uncompilable,send_hog_functions_daily_digest,send_hog_functions_digest_email,send_invite,@@ -56,6 +59,7 @@ from posthog.tasks.email import (from posthog.tasks.test.utils_email_tests import mock_email_messagesfrom posthog.test.api_keys import create_project_secret_api_key+from products.access_control.backend.models.access_control import AccessControlfrom products.batch_exports.backend.models.batch_export import (BatchExport,BatchExportDestination,@@ -1106,6 +1110,228 @@ class TestEmail(APIBaseTest, ClickhouseTestMixin):{"recipient": "[email protected]", "raw_email": "[email protected]", "distinct_id": str(user2.distinct_id)}]+ def test_send_hog_function_filters_uncompilable_reaches_admins_and_the_creator(+ self, MockEmailMessage: MagicMock+ ) -> None:+ mocked_email_messages = mock_email_messages(MockEmailMessage)+ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save()+ # A plain member who happens to have created the destination. The admins get it because+ # they can act on it; the creator gets it because they know what it was for.+ creator = self._create_user("[email protected]")+ creator_membership = OrganizationMembership.objects.get(user=creator, organization=self.organization)+ creator_membership.level = OrganizationMembership.Level.MEMBER+ creator_membership.save()+ hog_function = HogFunction.objects.create(+ team=self.team, name="Broken destination", enabled=True, created_by=creator+ )+ # Written past save(), which recompiles the filters and would clear the error again. This is+ # also the shape the row has in the database: a null bytecode beside the reason.+ HogFunction.objects.filter(id=hog_function.id).update(+ filters={"bytecode": None, "bytecode_error": "Cohort membership can't be evaluated"}+ )++ send_hog_function_filters_uncompilable(self.team.id, [str(hog_function.id)])++ recipients = {entry["recipient"] for entry in mocked_email_messages[0].to}+ assert "[email protected]" in recipients+ assert self.user.email in recipients++ def test_send_hog_function_filters_uncompilable_lists_every_destination_in_one_email(+ self, MockEmailMessage: MagicMock+ ) -> None:+ # A shared mistake breaks several destinations at once, so the project gets one message+ # naming each of them beside its own error rather than one message each.+ mocked_email_messages = mock_email_messages(MockEmailMessage)+ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save()+ ids = []+ for name, error in (+ ("Send pageviews to Slack", "Cohort membership can't be evaluated in real-time filters"),+ ("Forward signups to a webhook", "Select queries are not allowed in filters"),+ ):+ hog_function = HogFunction.objects.create(team=self.team, name=name, enabled=True)+ HogFunction.objects.filter(id=hog_function.id).update(filters={"bytecode": None, "bytecode_error": error})+ ids.append(str(hog_function.id))++ send_hog_function_filters_uncompilable(self.team.id, ids)++ assert len(mocked_email_messages) == 1+ html = mocked_email_messages[0].html_body+ # Apostrophe-free slices: how Django escapes a quote is framework behavior, not this email's.+ for fragment in (+ "Send pageviews to Slack",+ "Forward signups to a webhook",+ "evaluated in real-time filters",+ "Select queries are not allowed in filters",+ ):+ assert fragment in html++ def test_send_hog_function_filters_uncompilable_skips_a_creator_who_left(self, MockEmailMessage: MagicMock) -> None:+ mocked_email_messages = mock_email_messages(MockEmailMessage)+ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save()+ creator = self._create_user("[email protected]")+ hog_function = HogFunction.objects.create(+ team=self.team, name="Broken destination", enabled=True, created_by=creator+ )+ HogFunction.objects.filter(id=hog_function.id).update(+ filters={"bytecode": None, "bytecode_error": "Cohort membership can't be evaluated"}+ )+ # The email names the project and quotes the error, so it must not follow a stale created_by.+ OrganizationMembership.objects.filter(user=creator, organization=self.organization).delete()++ send_hog_function_filters_uncompilable(self.team.id, [str(hog_function.id)])++ recipients = {entry["recipient"] for entry in mocked_email_messages[0].to}+ assert "[email protected]" not in recipients+ assert self.user.email in recipients++ def test_send_hog_function_filters_uncompilable_skips_a_creator_denied_project_access(+ self, MockEmailMessage: MagicMock+ ) -> None:+ mocked_email_messages = mock_email_messages(MockEmailMessage)+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}+ ]+ self.organization.save()+ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save()+ creator = self._create_user("[email protected]")+ creator_membership = OrganizationMembership.objects.get(user=creator, organization=self.organization)+ creator_membership.level = OrganizationMembership.Level.MEMBER+ creator_membership.save()+ # The project is private, so organization membership alone no longer grants access to it.+ AccessControl.objects.create(+ team=self.team, resource="project", resource_id=str(self.team.id), access_level="none"+ )+ hog_function = HogFunction.objects.create(+ team=self.team, name="Broken destination", enabled=True, created_by=creator+ )+ HogFunction.objects.filter(id=hog_function.id).update(+ filters={"bytecode": None, "bytecode_error": "Cohort membership can't be evaluated"}+ )++ send_hog_function_filters_uncompilable(self.team.id, [str(hog_function.id)])++ recipients = {entry["recipient"] for entry in mocked_email_messages[0].to}+ assert "[email protected]" not in recipients+ assert self.user.email in recipients++ def test_send_hog_function_filters_uncompilable_tells_a_switched_off_destination_to_switch_back_on(+ self, MockEmailMessage: MagicMock+ ) -> None:+ mocked_email_messages = mock_email_messages(MockEmailMessage)+ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save()+ hog_function = HogFunction.objects.create(team=self.team, name="Broken destination", enabled=True)+ HogFunction.objects.filter(id=hog_function.id).update(+ filters={"bytecode": None, "bytecode_error": "Cohort membership can't be evaluated"}+ )++ send_hog_function_filters_uncompilable(self.team.id, [str(hog_function.id)])+ HogFunction.objects.filter(id=hog_function.id).update(enabled=False)+ send_hog_function_filters_uncompilable(self.team.id, [str(hog_function.id)])++ assert "switch it back on" not in mocked_email_messages[0].html_body+ assert "switch it back on" in mocked_email_messages[1].html_body+ # Fixing the filters leaves the destination off, so the second email must reach the+ # recipients rather than being deduped away by the first.+ assert mocked_email_messages[0].campaign_key != mocked_email_messages[1].campaign_key++ def test_send_hog_function_filters_uncompilable_keys_the_campaign_on_a_stable_digest(+ self, MockEmailMessage: MagicMock+ ) -> None:+ mocked_email_messages = mock_email_messages(MockEmailMessage)+ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save()+ bytecode_error = "Cohort membership can't be evaluated"+ hog_function = HogFunction.objects.create(team=self.team, name="Broken destination", enabled=True)+ HogFunction.objects.filter(id=hog_function.id).update(+ filters={"bytecode": None, "bytecode_error": bytecode_error}+ )++ send_hog_function_filters_uncompilable(self.team.id, [str(hog_function.id)])++ # The key decides whether a re-run emails the same people again, so it has to survive a+ # worker restart. hash() is salted per interpreter and would not. It covers the whole set,+ # because one email now lists every broken destination in the project.+ fingerprint = f"{hog_function.id}:{bytecode_error}:1"+ digest = hashlib.sha256(fingerprint.encode("utf-8")).hexdigest()[:16]+ assert mocked_email_messages[0].campaign_key == f"hog_function_filters_uncompilable_{self.team.id}_{digest}"++ def test_send_hog_function_filters_uncompilable_orders_same_named_destinations_by_id(+ self, MockEmailMessage: MagicMock+ ) -> None:+ mocked_email_messages = mock_email_messages(MockEmailMessage)+ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save()+ bytecode_error = "Cohort membership can't be evaluated"+ # Two destinations can share a name, and the query that reads them has no ORDER BY. The+ # higher id is written first, so the rows come back in the reverse of the order the key+ # has to use, and a key built on names alone would flip between runs and mail twice.+ earlier = uuid.UUID("00000000-0000-0000-0000-0000000000a0")+ later = uuid.UUID("00000000-0000-0000-0000-0000000000b0")+ for hog_function_id in (later, earlier):+ HogFunction.objects.create(id=hog_function_id, team=self.team, name="Shared name", enabled=True)+ HogFunction.objects.filter(id=hog_function_id).update(+ filters={"bytecode": None, "bytecode_error": bytecode_error}+ )++ send_hog_function_filters_uncompilable(self.team.id, [str(later), str(earlier)])++ fingerprint = ";".join(f"{hog_function_id}:{bytecode_error}:1" for hog_function_id in (earlier, later))+ digest = hashlib.sha256(fingerprint.encode("utf-8")).hexdigest()[:16]+ assert mocked_email_messages[0].campaign_key == f"hog_function_filters_uncompilable_{self.team.id}_{digest}"++ def test_send_hog_function_filters_uncompilable_subject_survives_a_newline_in_a_name(+ self, MockEmailMessage: MagicMock+ ) -> None:+ # A CR or LF in either name would make Django reject the whole email as a multiline+ # header. The send path swallows that error, so every recipient would lose this notice.+ mock_email_messages(MockEmailMessage)+ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save()+ self.team.name = "Production\nBcc: [email protected]"+ self.team.save()+ hog_function = HogFunction.objects.create(+ team=self.team, name="Broken destination\nBcc: [email protected]", enabled=True+ )+ HogFunction.objects.filter(id=hog_function.id).update(+ filters={"bytecode": None, "bytecode_error": "Cohort membership can't be evaluated"}+ )++ send_hog_function_filters_uncompilable(self.team.id, [str(hog_function.id)])++ subject = MockEmailMessage.call_args.kwargs["subject"]+ assert "\n" not in subject+ assert "\r" not in subject+ assert "Production" in subject++ @parameterized.expand(+ [+ ("filters that compile", {"bytecode": ["_H", 1]}, False),+ (+ "an archived destination",+ {"bytecode": None, "bytecode_error": "Cohort membership can't be evaluated"},+ True,+ ),+ ]+ )+ def test_send_hog_function_filters_uncompilable_sends_nothing_for(+ self, MockEmailMessage: MagicMock, _name: str, filters: dict, deleted: bool+ ) -> None:+ mocked_email_messages = mock_email_messages(MockEmailMessage)+ # An admin, so an email would have a recipient and the assertion is about the skip.+ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save()+ hog_function = HogFunction.objects.create(team=self.team, name="A destination", enabled=True)+ HogFunction.objects.filter(id=hog_function.id).update(filters=filters, deleted=deleted)++ send_hog_function_filters_uncompilable(self.team.id, [str(hog_function.id)])++ assert mocked_email_messages == []+def test_send_batch_export_run_failure_per_pipeline_opt_out(self, MockEmailMessage: MagicMock) -> None:mocked_email_messages = mock_email_messages(MockEmailMessage)batch_export_destination = BatchExportDestination.objects.create(diff --git a/posthog/templates/email/hog_function_filters_uncompilable.html b/posthog/templates/email/hog_function_filters_uncompilable.htmlnew file mode 100644index 000000000000..0fedbfadf71a--- /dev/null+++ b/posthog/templates/email/hog_function_filters_uncompilable.html@@ -0,0 +1,35 @@+{% extends "email/base.html" %}+{% block heading %}Some destinations aren't delivering anything{% endblock %}+{% block section %}+ <!-- prettier-ignore -->+ <p>+ These destinations in project <b>{{ team }}</b> have filters that PostHog can't evaluate, so they haven't been sending events:+ </p>+ {% for entry in broken %}+ <p>+ <a href="{{ entry.hog_function.url }}"><b>{{ entry.hog_function.name }}</b></a>+ <br />+ <i>{{ entry.bytecode_error }}</i>+ {% if not entry.hog_function.enabled %}+ <br />+ This one is also switched off. Fix the filters, then switch it back on.+ {% endif %}+ </p>+ {% endfor %}+ <p>+ If an error above is about a cohort, replace the cohort with the person properties it's based on. Cohort+ membership can't be checked while an event is being processed, so a filter that refers to one can't run.+ For any other error, edit the filter to remove the expression the error names.+ </p>+ <p>+ One change can break several destinations at once. Filters that apply to your whole project, such as filtering+ out internal users, are shared by every destination that uses them.+ </p>+ <p>Events sent while the filters were broken weren't delivered and can't be recovered.</p>+{% endblock %}+{% block footer %}+ Need help?+ <a href="https://posthog.com/questions?{{ utm_tags }}" target="_blank"><b>Visit support</b></a>+ or+ <a href="https://posthog.com/docs?{{ utm_tags }}" target="_blank"><b>read our documentation</b></a>.+{% endblock %}