: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(hogql): skip JSONDropKeys on an empty JSON column (#116555)
Phil Haack3cf43faa2c9a
diff --git a/posthog/hogql/printer/clickhouse.py b/posthog/hogql/printer/clickhouse.pyindex f3abf07618bd..f03a409b90a6 100644--- a/posthog/hogql/printer/clickhouse.py+++ b/posthog/hogql/printer/clickhouse.py@@ -568,12 +568,10 @@ class ClickHousePrinter(BasePrinter):return self._maybe_apply_json_drop_keys(type, serialized)return self._maybe_apply_json_drop_keys(type, field_sql, mask_feature_flags=True)- def _serialize_events_json_field(self, type: ast.FieldType, field_sql: str) -> str | None:+ def _events_json_document_field(self, type: ast.FieldType) -> StringJSONDatabaseField | None:+ """The field when it is a JSON document column of the native events table, otherwise None."""if not self.context.uses_new_events_schema():return None- if getattr(self, "_json_function_argument_depth", 0) > 0:- return None-resolved_field = type.resolve_database_field(self.context)if not isinstance(resolved_field, StringJSONDatabaseField):return None@@ -581,9 +579,16 @@ class ClickHousePrinter(BasePrinter):return Noneif not isinstance(type.table_type, ast.BaseTableType):return None-if not isinstance(type.table_type.resolve_database_table(self.context), EVENTS_TABLE_TYPES):return None+ return resolved_field++ def _serialize_events_json_field(self, type: ast.FieldType, field_sql: str) -> str | None:+ if getattr(self, "_json_function_argument_depth", 0) > 0:+ return None+ resolved_field = self._events_json_document_field(type)+ if resolved_field is None:+ return Noneif resolved_field.name == "properties":prefix = field_sql.removesuffix(self._print_identifier("properties"))@@ -670,15 +675,14 @@ class ClickHousePrinter(BasePrinter):if not keys_to_drop:return field_sql+ is_events_json_document = self._events_json_document_field(type) is not Nonerestricted_flags = restricted_feature_flag_names(keys_to_drop)mask_stored_feature_flags = (mask_feature_flagsand bool(restricted_flags)and "$feature_flags" not in keys_to_dropand resolved_field.name == "properties"- and self.context.uses_new_events_schema()- and isinstance(type.table_type, ast.BaseTableType)- and isinstance(type.table_type.resolve_database_table(self.context), EVENTS_TABLE_TYPES)+ and is_events_json_document)if mask_stored_feature_flags:keys_to_drop = {key for key in keys_to_drop if not key.startswith(FEATURE_FLAG_PROPERTY_PREFIX)} | {@@ -687,6 +691,12 @@ class ClickHousePrinter(BasePrinter):keys_placeholder = self.context.add_sensitive_value(sorted(keys_to_drop))stripped = f"{JSON_DROP_KEYS_CLICKHOUSE_NAME}({keys_placeholder})({field_sql})"+ if not is_events_json_document:+ # A String JSON column holds '' when its producer omits the value.+ # The v12 json_drop_keys_udf binary fails to parse ''. Cloud and CI call it as JSONDropKeys_v12.+ # ClickHouse short-circuits `if`. The UDF therefore receives only the rows that are not empty.+ # A native events document is a JSON column or a document that concat rebuilds, so it is never ''.+ stripped = f"if(empty({field_sql}), '', {stripped})"if not mask_stored_feature_flags:return strippeddiff --git a/posthog/hogql/printer/test/test_property_access_control.py b/posthog/hogql/printer/test/test_property_access_control.pyindex 22ae2153c5a4..536e0bde2c30 100644--- a/posthog/hogql/printer/test/test_property_access_control.py+++ b/posthog/hogql/printer/test/test_property_access_control.py@@ -1,3 +1,5 @@+import uuid+from posthog.test.base import BaseTest, ClickhouseTestMixin, cleanup_materialized_columns, materializedfrom django.conf import settings@@ -9,9 +11,11 @@ from posthog.schema import HogQLQueryModifiers, PersonsOnEventsModefrom posthog.hogql.context import HogQLContextfrom posthog.hogql.parser import parse_selectfrom posthog.hogql.printer import prepare_and_print_ast+from posthog.hogql.query import execute_hogql_queryfrom posthog.constants import AvailableFeaturefrom posthog.models import PropertyDefinition+from posthog.models.event.util import create_eventfrom products.access_control.backend.models.property_access_control import PropertyAccessControlfrom products.access_control.backend.property_access_control import PropertyAccessLevel@@ -649,3 +653,44 @@ class TestRestrictedPropertyWithMaterializedColumn(ClickhouseTestMixin, BaseTestwith materialized("events", "secret_field", is_nullable=False):sql = self._compile_select("SELECT properties.secret_field FROM events")assert "mat_secret_field" not in sql, f"restricted property leaked via materialized column: {sql}"+++class TestRestrictedPersonPropertiesBlobQuery(ClickhouseTestMixin, BaseTest):+ def test_empty_person_properties_row_does_not_fail_the_masked_query(self):+ self.organization.available_product_features = [+ {"name": AvailableFeature.PROPERTY_ACCESS_CONTROL, "key": AvailableFeature.PROPERTY_ACCESS_CONTROL}+ ]+ self.organization.save()+ person_prop = PropertyDefinition.objects.create(+ team=self.team,+ name="email",+ property_type="String",+ type=PropertyDefinition.Type.PERSON,+ )+ PropertyAccessControl.objects.create(+ team=self.team,+ property_definition=person_prop,+ access_level=PropertyAccessLevel.NONE.value,+ )+ create_event(+ event_uuid=uuid.uuid4(),+ event="$pageview",+ team=self.team,+ distinct_id="with-person-properties",+ person_properties={"email": "[email protected]", "name": "Example"},+ )+ create_event(+ event_uuid=uuid.uuid4(), event="$pageview", team=self.team, distinct_id="without-person-properties"+ )++ response = execute_hogql_query(+ "SELECT distinct_id, person.properties FROM events ORDER BY distinct_id",+ team=self.team,+ user=self.user,+ modifiers=HogQLQueryModifiers(+ personsOnEventsMode=PersonsOnEventsMode.PERSON_ID_NO_OVERRIDE_PROPERTIES_ON_EVENTS,+ useNewEventsSchema=False,+ ),+ )++ assert response.results == [("with-person-properties", '{"name":"Example"}'), ("without-person-properties", "")]diff --git a/posthog/hogql/transforms/test/test_property_types.py b/posthog/hogql/transforms/test/test_property_types.pyindex 64d673ca80e6..34f233f41064 100644--- a/posthog/hogql/transforms/test/test_property_types.py+++ b/posthog/hogql/transforms/test/test_property_types.py@@ -219,7 +219,10 @@ class TestNewEventsSchemaArraySubcolumns(_NewEventsSchemaArraySubcolumnsHelpers,False,{RestrictedProperty(name="$feature/secret", property_type=PropertyDefinition.Type.EVENT)},PropertyGroupsMode.OPTIMIZED,- (f"JSONExtractRaw({JSON_DROP_KEYS_CLICKHOUSE_NAME}(", f"JSONHas({JSON_DROP_KEYS_CLICKHOUSE_NAME}("),+ (+ f"JSONExtractRaw(if(empty(events.properties), '', {JSON_DROP_KEYS_CLICKHOUSE_NAME}(",+ f"JSONHas(if(empty(events.properties), '', {JSON_DROP_KEYS_CLICKHOUSE_NAME}(",+ ),("properties_group_feature_flags", "mapFilter("),),(@@ -285,8 +288,8 @@ class TestNewEventsSchemaArraySubcolumns(_NewEventsSchemaArraySubcolumnsHelpers,True,{RestrictedProperty(name="$feature_flags", property_type=PropertyDefinition.Type.EVENT)},None,- ("JSONExtractKeysAndValuesRaw(",),- ("concat('$feature/', key)", "'\"$active_feature_flags\":'"),+ ("JSONExtractKeysAndValuesRaw(", f"{JSON_DROP_KEYS_CLICKHOUSE_NAME}("),+ ("concat('$feature/', key)", "'\"$active_feature_flags\":'", f"'', {JSON_DROP_KEYS_CLICKHOUSE_NAME}("),),("dynamic_restricted",@@ -294,8 +297,12 @@ class TestNewEventsSchemaArraySubcolumns(_NewEventsSchemaArraySubcolumnsHelpers,True,{RestrictedProperty(name="$feature/secret", property_type=PropertyDefinition.Type.EVENT)},None,- ("mapFilter((key, value) -> not(has(", "'\"$active_feature_flags\":'"),- ("JSONMergePatch(",),+ (+ "mapFilter((key, value) -> not(has(",+ "'\"$active_feature_flags\":'",+ f"{JSON_DROP_KEYS_CLICKHOUSE_NAME}(",+ ),+ ("JSONMergePatch(", f"'', {JSON_DROP_KEYS_CLICKHOUSE_NAME}("),),("stored_document_restricted",@@ -303,8 +310,8 @@ class TestNewEventsSchemaArraySubcolumns(_NewEventsSchemaArraySubcolumnsHelpers,True,{RestrictedProperty(name="$feature/secret", property_type=PropertyDefinition.Type.EVENT)},None,- ("JSONMergePatch(", "mapFilter((key, value) -> not(has("),- ("'\"$active_feature_flags\":'",),+ ("JSONMergePatch(", "mapFilter((key, value) -> not(has(", f"{JSON_DROP_KEYS_CLICKHOUSE_NAME}("),+ ("'\"$active_feature_flags\":'", f"'', {JSON_DROP_KEYS_CLICKHOUSE_NAME}("),),("whole_document_adds_temporary_keys",