: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
fix(cdp): keep a destination running when its filters stop compiling (#103744)
Meikel Ratz639b0cb49ce9
diff --git a/posthog/management/commands/notify_uncompilable_hog_function_filters.py b/posthog/management/commands/notify_uncompilable_hog_function_filters.pyindex c7bfffd85684..b73ce88c4a58 100644--- a/posthog/management/commands/notify_uncompilable_hog_function_filters.py+++ b/posthog/management/commands/notify_uncompilable_hog_function_filters.py@@ -3,6 +3,7 @@ from argparse import ArgumentParserfrom typing import Anyfrom django.core.management.base import BaseCommand, CommandError+from django.db.models import Qfrom posthog.tasks.email import send_hog_function_filters_uncompilable@@ -13,9 +14,10 @@ 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."+ "Find enabled hog functions that have no filter bytecode because their filters failed to "+ "compile, and tell their project. A function in this state matches nothing and delivers "+ "nothing, because evaluating a null bytecode raises on every event. A function that kept "+ "its last working bytecode carries the same error but still delivers, so it is left alone.")def add_arguments(self, parser: ArgumentParser) -> None:@@ -39,14 +41,18 @@ class Command(BaseCommand):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.+ # The error alone does not identify the dead state, because a save that fails to recompile+ # keeps the last working bytecode beside the error and that function still delivers. Both+ # shapes of "no bytecode" are selected: the key is absent on a function that has never+ # compiled, and JSON null on one whose bytecode was cleared. Matching on the error 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+ queryset = (+ HogFunction.objects.filter(deleted=False, enabled=True, type=HogFunctionType.DESTINATION)+ .exclude(filters__bytecode_error__isnull=True)+ .filter(Q(filters__bytecode__isnull=True) | Q(filters__bytecode=None)))team_id = options["team_id"]if team_id is not None: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.pyindex 08b174ead092..142f1192e951 100644--- a/posthog/management/commands/test/test_notify_uncompilable_hog_function_filters.py+++ b/posthog/management/commands/test/test_notify_uncompilable_hog_function_filters.py@@ -20,12 +20,13 @@ class TestNotifyUncompilableHogFunctionFilters(BaseTest):enabled: bool = True,type: str = HogFunctionType.DESTINATION,team: Team | None = None,+ bytecode: list | 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"}+ filters={"bytecode": bytecode, "bytecode_error": "Cohort membership can't be evaluated"})return hog_function@@ -62,6 +63,21 @@ class TestNotifyUncompilableHogFunctionFilters(BaseTest):hog_function.refresh_from_db()assert hog_function.enabled is False+ def test_leaves_a_destination_that_kept_its_last_working_bytecode_alone(self) -> None:+ # A save whose recompile fails keeps the previous bytecode beside the error, so this+ # destination still delivers. Disabling it would cause the outage the error only warns of,+ # and the email would tell the project that a working destination dropped events.+ hog_function = self._broken(bytecode=["_H", 1, 29])+ out = StringIO()++ with patch(TASK) as task:+ call_command("notify_uncompilable_hog_function_filters", "--apply", "--disable", stdout=out)++ task.delay.assert_not_called()+ hog_function.refresh_from_db()+ assert hog_function.enabled is True+ assert "0 enabled destination(s)" in out.getvalue()+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.diff --git a/posthog/models/test/test_hog_function.py b/posthog/models/test/test_hog_function.pyindex 108485e56f21..0790ee5d5e94 100644--- a/posthog/models/test/test_hog_function.py+++ b/posthog/models/test/test_hog_function.py@@ -130,6 +130,129 @@ class TestHogFunction(TestCase):== f'["_H", {HOGQL_BYTECODE_VERSION}, 32, "$host", 32, "properties", 1, 2, 2, "toString", 1, 32, "^(localhost|127\\\\.0\\\\.0\\\\.1)($|:)", 2, "match", 2, 5, 47, 3, 35, 33, 1]')+ def test_save_keeps_working_bytecode_when_filters_stop_compiling(self):+ cohort = Cohort.objects.create(+ team=self.team,+ name="Internal users",+ filters={+ "properties": {+ "type": "AND",+ "values": [{"type": "person", "key": "email", "operator": "icontains", "value": "@posthog.com"}],+ }+ },+ )+ self.team.test_account_filters = [{"type": "cohort", "key": "id", "value": cohort.id}]+ self.team.save()++ item = HogFunction.objects.create(+ name="Test",+ type=HogFunctionType.DESTINATION,+ team=self.team,+ enabled=True,+ filters={"filter_test_accounts": True},+ )+ working_bytecode = to_dict(item.filters)["bytecode"]+ assert working_bytecode is not None++ cohort.is_static = True+ cohort.save()++ item.name = "Renamed"+ item.save()++ item.refresh_from_db()+ assert item.enabled+ assert to_dict(item.filters)["bytecode"] == working_bytecode+ assert "static cohort" in to_dict(item.filters)["bytecode_error"]++ def test_save_leaves_an_existing_enabled_function_without_bytecode_alone(self):+ cohort = Cohort.objects.create(+ team=self.team,+ name="Internal users",+ filters={+ "properties": {+ "type": "AND",+ "values": [{"type": "person", "key": "email", "operator": "icontains", "value": "@posthog.com"}],+ }+ },+ )+ self.team.test_account_filters = [{"type": "cohort", "key": "id", "value": cohort.id}]+ self.team.save()++ item = HogFunction.objects.create(+ name="Test",+ type=HogFunctionType.DESTINATION,+ team=self.team,+ enabled=True,+ filters={"filter_test_accounts": True},+ )+ cohort.is_static = True+ cohort.save()+ # An enabled function that already lost its bytecode. Written past save() so the row keeps+ # that shape. A bulk re-save of every destination must not switch it off, because the+ # notification command and the recompile task both need it enabled to reach it.+ HogFunction.objects.filter(id=item.id).update(+ filters={"filter_test_accounts": True, "bytecode": None, "bytecode_error": "static cohort"}+ )++ item.name = "Renamed"+ item.save()++ item.refresh_from_db()+ assert item.enabled+ assert to_dict(item.filters)["bytecode"] is None++ def test_save_that_changes_the_filters_does_not_reuse_the_old_bytecode(self):+ cohort = Cohort.objects.create(+ team=self.team,+ name="Internal users",+ filters={+ "properties": {+ "type": "AND",+ "values": [{"type": "person", "key": "email", "operator": "icontains", "value": "@posthog.com"}],+ }+ },+ )+ self.team.test_account_filters = [{"type": "cohort", "key": "id", "value": cohort.id}]+ self.team.save()++ item = HogFunction.objects.create(+ name="Test",+ type=HogFunctionType.DESTINATION,+ team=self.team,+ enabled=True,+ filters={"filter_test_accounts": True},+ )+ assert to_dict(item.filters)["bytecode"] is not None++ cohort.is_static = True+ cohort.save()++ item.filters = {"filter_test_accounts": True, "events": [{"id": "$pageview", "type": "events"}]}+ item.save()++ item.refresh_from_db()+ assert to_dict(item.filters)["bytecode"] is None+ assert "static cohort" in to_dict(item.filters)["bytecode_error"]++ def test_create_with_uncompilable_filters_is_not_enabled(self):+ cohort = Cohort.objects.create(team=self.team, name="Imported users", is_static=True)+ self.team.test_account_filters = [{"type": "cohort", "key": "id", "value": cohort.id}]+ self.team.save()++ item = HogFunction.objects.create(+ name="Test",+ type=HogFunctionType.DESTINATION,+ team=self.team,+ enabled=True,+ filters={"filter_test_accounts": True},+ )++ item.refresh_from_db()+ assert not item.enabled+ assert to_dict(item.filters)["bytecode"] is None+ assert "static cohort" in to_dict(item.filters)["bytecode_error"]+class TestHogFunctionsBackgroundReloading(TestCase, QueryMatchingTest):def setUp(self):diff --git a/posthog/tasks/email.py b/posthog/tasks/email.pyindex 7cab742f3ab2..e0d0de509ff7 100644--- a/posthog/tasks/email.py+++ b/posthog/tasks/email.py@@ -798,10 +798,13 @@ def send_hog_function_filters_uncompilable(team_id: int, hog_function_ids: list[hog_functions = HogFunction.objects.prefetch_related("created_by").filter(team_id=team_id, id__in=hog_function_ids, deleted=False)+ # A recompile that fails on save keeps the last working bytecode beside the error, so the+ # error alone does not mean the destination stopped delivering. Only a destination left+ # without bytecode is what this email is about.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 (filters := hog_function.filters or {}).get("bytecode") is None and (error := filters.get("bytecode_error"))]if not broken:returndiff --git a/posthog/tasks/test/test_email.py b/posthog/tasks/test/test_email.pyindex be42f22be94e..3dcdf890bc42 100644--- a/posthog/tasks/test/test_email.py+++ b/posthog/tasks/test/test_email.py@@ -1167,6 +1167,24 @@ class TestEmail(APIBaseTest, ClickhouseTestMixin):):assert fragment in html+ def test_send_hog_function_filters_uncompilable_skips_a_destination_still_on_its_last_bytecode(+ self, MockEmailMessage: MagicMock+ ) -> None:+ # A save whose recompile fails keeps the previous bytecode beside the error, so this+ # destination still delivers. The email says the listed destinations dropped events, which+ # would be wrong for this one.+ 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="Still delivering", enabled=True)+ HogFunction.objects.filter(id=hog_function.id).update(+ filters={"bytecode": ["_H", 1, 29], "bytecode_error": "Cohort membership can't be evaluated"}+ )++ send_hog_function_filters_uncompilable(self.team.id, [str(hog_function.id)])++ assert mocked_email_messages == []+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.ADMINdiff --git a/products/cdp/backend/api/test/test_hog_function.py b/products/cdp/backend/api/test/test_hog_function.pyindex 5265289cd6f6..17df0c12bc8a 100644--- a/products/cdp/backend/api/test/test_hog_function.py+++ b/products/cdp/backend/api/test/test_hog_function.py@@ -558,7 +558,16 @@ class TestHogFunctionAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):def test_uncompilable_filters_only_block_saves_that_leave_function_enabled(self, _name, initial_enabled, patch, expected):- cohort = Cohort.objects.create(team=self.team, name="Test users", is_static=True)+ cohort = Cohort.objects.create(+ team=self.team,+ name="Test users",+ filters={+ "properties": {+ "type": "AND",+ "values": [{"type": "person", "key": "email", "operator": "icontains", "value": "@example.com"}],+ }+ },+ )self.team.test_account_filters = [{"key": "id", "type": "cohort", "value": cohort.pk}]self.team.save()fn = HogFunction.objects.create(@@ -571,6 +580,9 @@ class TestHogFunctionAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):hog="return event",filters={"filter_test_accounts": True},)+ # Static only after the save: a save leaving the function enabled and uncompilable is refused.+ cohort.is_static = True+ cohort.save()response = self.client.patch(f"/api/projects/{self.team.id}/hog_functions/{fn.id}/",data=patch,@@ -583,7 +595,16 @@ class TestHogFunctionAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):# A client may send the boolean as a JSON string ("false"). The enable-guard reads the raw# value before field coercion, so it must coerce rather than rely on truthiness - otherwise# "false" is truthy and the disable is wrongly rejected with the filter error.- cohort = Cohort.objects.create(team=self.team, name="Test users", is_static=True)+ cohort = Cohort.objects.create(+ team=self.team,+ name="Test users",+ filters={+ "properties": {+ "type": "AND",+ "values": [{"type": "person", "key": "email", "operator": "icontains", "value": "@example.com"}],+ }+ },+ )self.team.test_account_filters = [{"key": "id", "type": "cohort", "value": cohort.pk}]self.team.save()fn = HogFunction.objects.create(@@ -596,6 +617,9 @@ class TestHogFunctionAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):hog="return event",filters={"filter_test_accounts": True},)+ # Static only after the save: a save leaving the function enabled and uncompilable is refused.+ cohort.is_static = True+ cohort.save()response = self.client.patch(f"/api/projects/{self.team.id}/hog_functions/{fn.id}/",data={"enabled": "false"},diff --git a/products/cdp/backend/models/hog_functions/hog_function.py b/products/cdp/backend/models/hog_functions/hog_function.pyindex e387c116d782..2c0da3527445 100644--- a/products/cdp/backend/models/hog_functions/hog_function.py+++ b/products/cdp/backend/models/hog_functions/hog_function.py@@ -96,10 +96,17 @@ TYPES_THAT_CAN_RERUN = (DRAFT_ONLY_UPDATE_FIELDS = frozenset({"draft", "draft_updated_at", "draft_encrypted_inputs"})+DERIVED_FILTER_KEYS = {"bytecode", "bytecode_error"}++def _is_draft_only_save(update_fields: Optional[Iterable[str]]) -> bool:return update_fields is not None and set(update_fields) <= DRAFT_ONLY_UPDATE_FIELDS+def _raw_filters(filters: dict | None) -> dict:+ return {key: value for key, value in (filters or {}).items() if key not in DERIVED_FILTER_KEYS}++class HogFunction(FileSystemSyncMixin, UUIDTModel):class Meta:db_table = "posthog_hogfunction"@@ -281,9 +288,55 @@ class HogFunction(FileSystemSyncMixin, UUIDTModel):def url(self):return absolute_uri(f"/project/{self.team_id}/pipeline/destinations/hog-{str(self.id)}")- def save(self, *args, **kwargs):+ def _compile_filters(self) -> dict:from posthog.cdp.filters import compile_filters_bytecode+ compiled = compile_filters_bytecode(self.filters, self.team)+ if not compiled.get("bytecode_error"):+ return compiled++ # compile_filters_bytecode nulls the bytecode next to the error, so a save that is not about+ # these filters, such as one after a cohort stops being inlinable, would otherwise leave an+ # enabled function that matches nothing. The error stays on the filters for the UI.+ previous = (+ {}+ if self._state.adding+ else (+ HogFunction.objects.filter(pk=self.pk, team_id=self.team_id).values_list("filters", flat=True).first()+ or {}+ )+ )+ previous_bytecode = previous.get("bytecode")++ # The runtime reads raw fields beside the bytecode - `source` picks the consumer, `events`+ # drives the pre-filter - so new raw fields on an old program would apply rules the stored+ # filters no longer describe.+ if previous_bytecode is not None and _raw_filters(compiled) == _raw_filters(previous):+ compiled["bytecode"] = previous_bytecode+ logger.warning(+ "hog_function_filters_kept_previous_bytecode",+ hog_function_id=str(self.pk),+ team_id=self.team_id,+ bytecode_error=compiled["bytecode_error"],+ )+ elif self._state.adding and self.enabled:+ # A new function has no working bytecode to fall back on, so saving it enabled would+ # create a function that is on and matches nothing. An existing function already in+ # that state stays enabled: notify_uncompilable_hog_function_filters is what tells its+ # owner, and refresh_affected_hog_functions starts it delivering again once the cause+ # is fixed. Both need the function to still be on, and a bulk re-save must not take+ # that away silently.+ self.enabled = False+ logger.warning(+ "hog_function_created_disabled_uncompilable_filters",+ hog_function_id=str(self.pk),+ team_id=self.team_id,+ bytecode_error=compiled["bytecode_error"],+ )++ return compiled++ def save(self, *args, **kwargs):if _is_draft_only_save(kwargs.get("update_fields")):# Nothing here writes a live column, so re-splitting live secrets and recompiling filter# bytecode (a DB-hitting compile) would be pure waste.@@ -291,7 +344,7 @@ class HogFunction(FileSystemSyncMixin, UUIDTModel):self.move_secret_inputs()if self.type not in TYPES_WITH_TRANSPILED_FILTERS:- self.filters = compile_filters_bytecode(self.filters, self.team)+ self.filters = self._compile_filters()return super().save(*args, **kwargs)