: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): keep four query shapes working on the native events table (#108943)
Sandy Spicer1df2cc7e6137
diff --git a/posthog/clickhouse/events_json.py b/posthog/clickhouse/events_json.pyindex 2cfc77026d87..10137ac29da9 100644--- a/posthog/clickhouse/events_json.py+++ b/posthog/clickhouse/events_json.py@@ -16,7 +16,7 @@ UNPARSEABLE_PROPERTIES_KEY = "$unparseable_properties"TEMPORARY_PROPERTIES_COLUMN = "temporary_properties"# Mirrors isTemporaryProperty in clickhouse-udfs/util/cmd/json_clean_posthog_event_properties_udf/main.go, so update both.-_TEMPORARY_EVENT_PROPERTY_ROOTS = frozenset(+TEMPORARY_EVENT_PROPERTY_ROOTS = frozenset({"$set","$set_once",@@ -35,7 +35,7 @@ _TEMPORARY_EVENT_PROPERTY_ROOTS = frozenset("$lib_custom_api_host",})-_TEMPORARY_EVENT_PROPERTY_ROOT_PREFIX = "$sdk_debug_"+TEMPORARY_EVENT_PROPERTY_ROOT_PREFIX = "$sdk_debug_"def is_temporary_event_property(key: str) -> bool:@@ -43,7 +43,7 @@ def is_temporary_event_property(key: str) -> bool:A dotted key such as `$set.foo` is one flat key, so it matches only the prefix rule, never a root name."""- return key in _TEMPORARY_EVENT_PROPERTY_ROOTS or key.startswith(_TEMPORARY_EVENT_PROPERTY_ROOT_PREFIX)+ return key in TEMPORARY_EVENT_PROPERTY_ROOTS or key.startswith(TEMPORARY_EVENT_PROPERTY_ROOT_PREFIX)# Every path not declared below is a dynamic subcolumn (up to the column's max_dynamic_paths per part, thendiff --git a/posthog/hogql/ACCESS_CONTROL.md b/posthog/hogql/ACCESS_CONTROL.mdindex 08da1068dc39..931bca0f69af 100644--- a/posthog/hogql/ACCESS_CONTROL.md+++ b/posthog/hogql/ACCESS_CONTROL.md@@ -193,6 +193,7 @@ Native event JSON keeps parsing diagnostics in `$unparseable_properties`, whichNative event JSON stores a flat dotted key such as `customer.ssn` under the path `customer%2Essn`, and a read of `customer%2Essn` returns the same value. Restricting a dotted event or person property therefore also restricts its `%2E` spelling.Native reads of a parent containing restricted children use the masked JSON document instead of a raw subcolumn. This also covers multi-key `JSONHas` calls with computed keys. Unrestricted siblings remain readable.+A JSON function whose first key is computed per row reads the masked `properties` document, and the masked `temporary_properties` document on rows where the key names a moved property, so a restricted property stays unreadable through a computed key.The restriction set is loaded once per query in `prepare_ast_for_printing()` and cached per `(team_id, user_id)` for the request lifetime.diff --git a/posthog/hogql/escape_sql.py b/posthog/hogql/escape_sql.pyindex a33508bdb16d..d16810aaf4b5 100644--- a/posthog/hogql/escape_sql.py+++ b/posthog/hogql/escape_sql.py@@ -48,6 +48,11 @@ def escape_hogql_identifier(identifier: str | int) -> str:return str(identifier)if "%" in identifier:raise QueryError(f'The HogQL identifier "{identifier}" is not permitted as it contains the "%" character')+ return quote_hogql_identifier(identifier)+++def quote_hogql_identifier(identifier: str) -> str:+ """Quote an identifier without validating whether it is safe to interpolate into SQL."""# HogQL allows dollars in the identifier.if re.match(r"^[A-Za-z_$][A-Za-z0-9_$]*$", identifierdiff --git a/posthog/hogql/printer/hogql.py b/posthog/hogql/printer/hogql.pyindex b17aa8ead413..780f67ba1c4e 100644--- a/posthog/hogql/printer/hogql.py+++ b/posthog/hogql/printer/hogql.py@@ -3,6 +3,7 @@ from typing import ClassVar, cast, get_argsfrom posthog.hogql import astfrom posthog.hogql.constants import HogQLDialectfrom posthog.hogql.errors import ImpossibleASTError, QueryError+from posthog.hogql.escape_sql import quote_hogql_identifierfrom posthog.hogql.printer.base import BasePrinter@@ -58,12 +59,15 @@ class HogQLPrinter(BasePrinter):return ".".join(parts)def visit_json_subcolumn_access(self, node: ast.JsonSubcolumnAccess) -> str:+ # Only the ClickHouse printer prints this node as HogQL, to name a result column, and it removes `%` from that+ # name. So a native JSON key may keep a `%`, which `_print_identifier` refuses.+ keys = [quote_hogql_identifier(key) for key in node.keys]parts = [self.visit(node.expr)]- if node.access_type == "sub_object" and node.keys:- parts.append("^" + self._print_identifier(node.keys[0]))- parts.extend(self._print_identifier(key) for key in node.keys[1:])+ if node.access_type == "sub_object" and keys:+ parts.append("^" + keys[0])+ parts.extend(keys[1:])return ".".join(parts)- parts.extend(self._print_identifier(key) for key in node.keys)+ parts.extend(keys)return ".".join(parts)def _render_aggregation_name(self, node: ast.Call, func_meta) -> str:diff --git a/posthog/hogql/printer/test/test_printer.py b/posthog/hogql/printer/test/test_printer.pyindex ebb8e3735297..b30cdd965d2f 100644--- a/posthog/hogql/printer/test/test_printer.py+++ b/posthog/hogql/printer/test/test_printer.py@@ -1592,14 +1592,6 @@ class TestPrinter(BaseTest):)self.assertEqual(value, expected, expression)- @override_settings(CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA=True)- def test_new_events_schema_runtime_first_property_keys_fail_fast(self) -> None:- context = HogQLContext(team_id=self.team.pk, enable_select_queries=True)-- for expression in ("JSONHas(properties, event)", "JSONExtractRaw(properties, event)"):- with pytest.raises(QueryError, match="constant first key"):- self._expr(expression, context)-def test_property_groups_optimized_in_comparisons(self) -> None:# The IN operator works much like equality when the right hand side of the expression is all constants. Like# equality, it also needs to handle the empty string special case.diff --git a/posthog/hogql/property_planner.py b/posthog/hogql/property_planner.pyindex e809cac31615..568fd717a236 100644--- a/posthog/hogql/property_planner.py+++ b/posthog/hogql/property_planner.py@@ -301,15 +301,8 @@ def _plan_property_source(context=context,)- if (- context.uses_new_events_schema()- and table_name == "events"- and field_name- in (- "properties",- "person_properties",- )- ):+ # The native events table has no materialized, dmat or property-group columns for any of its blobs.+ if context.uses_new_events_schema() and table_name == "events":return _json_source_plan(table_name=table_name, field_name=field_name, property_name=property_name, context=context)diff --git a/posthog/hogql/test/test_query.py b/posthog/hogql/test/test_query.pyindex 8ec51b06882b..fbf791cd87fe 100644--- a/posthog/hogql/test/test_query.py+++ b/posthog/hogql/test/test_query.py@@ -1524,8 +1524,15 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):"array_obj_array_obj",]:self.assertIn(f"events.properties.{property_key}", clickhouse)- self.assertIn(json_dynamic_read_sql("events.properties", ["array_str", 1]), clickhouse)- self.assertIn(json_dynamic_read_sql("events.properties", ["obj_array", "id", 1]), clickhouse)+ # An index reads the JSON text of the value, so a row holding a non-array there reads NULL.+ self.assertIn(+ f"JSONExtractRaw({json_dynamic_read_sql('events.properties', ['array_str'], as_json=True)}, ",+ clickhouse,+ )+ self.assertIn(+ f"JSONExtractRaw({json_dynamic_read_sql('events.properties', ['obj_array', 'id'], as_json=True)}, ",+ clickhouse,+ )else:self.assertEqual(expected_legacy_clickhouse, clickhouse)self.assertEqual(response.results[0], tuple(random_uuid for x in alternatives))diff --git a/posthog/hogql/transforms/clickhouse_property_resolution.py b/posthog/hogql/transforms/clickhouse_property_resolution.pyindex 91ca2cea7ea9..507aa3c94497 100644--- a/posthog/hogql/transforms/clickhouse_property_resolution.py+++ b/posthog/hogql/transforms/clickhouse_property_resolution.py@@ -52,6 +52,9 @@ from posthog.hogql.visitor import CloningVisitor, clone_exprfrom posthog.clickhouse.events_json import (DISTRIBUTED_EVENTS_JSON_TABLE,+ EVENTS_PROPERTIES_JSON_SUBCOLUMNS,+ TEMPORARY_EVENT_PROPERTY_ROOT_PREFIX,+ TEMPORARY_EVENT_PROPERTY_ROOTS,TEMPORARY_PROPERTIES_COLUMN,is_temporary_event_property,)@@ -143,6 +146,12 @@ def resolve_materialized_property_source(if json_source := resolve_json_subcolumn_source(field_type, table_name, field_name, property_name, context):return json_source+ # The registries below list columns of the legacy events table. The native table has no materialized, dmat or+ # property-group columns, so the reads that reach this point on it (`groupN_properties` keys, and paths that+ # overlap a restriction) stay JSON reads.+ if context.uses_new_events_schema() and table_name in ("events", DISTRIBUTED_EVENTS_JSON_TABLE):+ return None+if context.modifiers.materializationMode == "disabled":return None@@ -417,6 +426,21 @@ def _json_subcolumn_access(return value+def _is_declared_array_path(+ field_type: ast.FieldType, keys: Sequence[str | int], source: MaterializedPropertySource+) -> bool:+ """Whether the native events table declares an array type for the path, so that every row holds an array there."""+ if source.json_column is not None or field_type.name != "properties":+ return False+ table_type: ast.Type | None = field_type.table_type+ while isinstance(table_type, (ast.TableAliasType, ast.ColumnAliasedTableType)):+ table_type = table_type.table_type+ if not isinstance(table_type, ast.TableType):+ return False+ declared_type = EVENTS_PROPERTIES_JSON_SUBCOLUMNS.get(".".join(str(key) for key in keys), "")+ return declared_type.startswith("Array(")++def _dynamic_json_scalar_string_expr(value: ast.Expr, *, as_json: bool) -> ast.Expr:json_value = ast.Call(name="nullIf",@@ -489,6 +513,16 @@ def _json_subcolumn_value_expr(source: MaterializedPropertySource,as_json: bool = False,) -> ast.Expr:+ index_position = next((position for position, key in enumerate(keys) if isinstance(key, int)), None)+ if index_position is not None and not _is_declared_array_path(field_type, keys[:index_position], source):+ # ClickHouse runs arrayElement on every type a Dynamic path holds in the block, so one row with a string or+ # a number at the path fails the whole query. Index the JSON text of the value instead, as the legacy table+ # indexes the raw document, so that such a row reads NULL.+ document = _json_subcolumn_value_expr(+ field_type, cast(Sequence[str], keys[:index_position]), source=source, as_json=True+ )+ return ast.PropertyAccess(expr=document, keys=list(keys[index_position:]), type=ast.StringType(nullable=True))+value = _json_subcolumn_access(field_type, keys, source=source, is_nullable=True)scalar_value = _dynamic_json_scalar_string_expr(value, as_json=as_json)scalar_or_null = ast.Call(@@ -505,7 +539,7 @@ def _json_subcolumn_value_expr(],type=ast.StringType(nullable=True),)- if any(isinstance(key, int) for key in keys):+ if index_position is not None:return scalar_or_nullobject_value = _dynamic_json_object_string_expr(field_type, list(cast(Sequence[str], keys)), source=source)return ast.Call(@@ -597,6 +631,54 @@ _TEMPORARY_PROPERTY_JSON_PATH_FUNCTIONS = frozenset(})+_JSON_KEY_PATH_FUNCTIONS = _TEMPORARY_PROPERTY_JSON_PATH_FUNCTIONS | {+ "JSONExtract",+ "JSONExtractBool",+ "JSONExtractFloat",+ "JSONExtractInt",+ "JSONExtractRaw",+ "JSONExtractString",+ "JSONExtractUInt",+ "JSONHas",+}+++def _names_temporary_event_property(key: ast.Expr) -> ast.Expr:+ """The SQL form of `is_temporary_event_property`, for a key that is computed per row."""+ name = _call("toString", [key])+ return _call(+ "or",+ [+ _call("has", [ast.Array(exprs=[_const(root) for root in sorted(TEMPORARY_EVENT_PROPERTY_ROOTS)]), name]),+ _call("startsWith", [clone_expr(name), _const(TEMPORARY_EVENT_PROPERTY_ROOT_PREFIX)]),+ ],+ )+++RUNTIME_FEATURE_FLAG_KEY_ERROR = (+ "A feature flag property can't be read through a key computed per row. "+ "Use a constant key instead, for example properties.`$feature/my-flag`."+)+++def _names_feature_flag_property(key: ast.Expr) -> ast.Expr:+ """Whether a key that is computed per row names `$feature/<key>` or `$active_feature_flags`."""+ name = _call("toString", [key])+ return _call(+ "ifNull",+ [+ _call(+ "or",+ [+ _call("startsWith", [name, _const(FEATURE_FLAG_PROPERTY_PREFIX)]),+ _call("equals", [clone_expr(name), _const("$active_feature_flags")]),+ ],+ ),+ _const(0),+ ],+ )++_JSON_PATH_FIRST_MEMBER = re.compile(r"""^\$(?:\.(?:"(?P<dot_quoted>[^"]*)"|(?P<dot>[^.\[]+))|\[(?:"(?P<bracket_double>[^"]*)"|'(?P<bracket_single>[^']*)')\])""")@@ -1203,21 +1285,17 @@ class ClickHousePropertyResolver(CloningVisitor):if node.name in ("toFloat", "toInt") and len(node.args) == 1:access = self._lowered_property_operand(node.args[0])- if access is not None:+ # An array index reads through the JSON text of the value, so the cast wraps that read instead.+ if access is not None and all(isinstance(key, str) for key in access.keys):field_type = _blob_field_type_of(access)assert field_type is not None- source = resolve_materialized_property_source(- field_type,- str(access.keys[0])- if any(isinstance(key, int) for key in access.keys)- else ".".join(cast(list[str], access.keys)),- self.context,- )+ keys = cast(list[str], access.keys)+ source = resolve_materialized_property_source(field_type, ".".join(keys), self.context)if source is not None and source.kind == "json_subcolumn":return ast.Call(name="accurateCastOrNull",args=[- _json_subcolumn_access(field_type, access.keys, source=source, is_nullable=True),+ _json_subcolumn_access(field_type, keys, source=source, is_nullable=True),_sentinel("Float64" if node.name == "toFloat" else "Int64"),],type=node.type,@@ -1235,6 +1313,10 @@ class ClickHousePropertyResolver(CloningVisitor):if temporary_property_json_function is not None:return temporary_property_json_function+ runtime_key_json_function = self._rewrite_json_function_with_runtime_key(node)+ if runtime_key_json_function is not None:+ return runtime_key_json_function+temporary_property_json_value = self._rewrite_json_value_on_temporary_property(node)if temporary_property_json_value is not None:return temporary_property_json_value@@ -1311,8 +1393,7 @@ class ClickHousePropertyResolver(CloningVisitor):if not isinstance(field_type, ast.FieldType) or not _is_events_properties(field_type, self.context):return Noneif not isinstance(node.args[1], ast.Constant):- # A key computed per row can name a moved property, which the serialized `properties` document lacks.- raise QueryError(f"{node.name} over native event properties requires a constant first key")+ return Nonefirst_key = node.args[1].valueif not isinstance(first_key, str) or not is_temporary_event_property(first_key):return None@@ -1344,6 +1425,50 @@ class ClickHousePropertyResolver(CloningVisitor):filter_expr=node.filter_expr,)+ def _rewrite_json_function_with_runtime_key(self, node: ast.Call) -> ast.Expr | None:+ """`f(properties, <key computed per row>, ...)` on native events, reading the document that holds the key.++ The serialized `properties` document has no moved keys, so a row whose key names one reads the serialized+ `temporary_properties` document instead. The printer drops restricted keys from both documents. Neither+ document holds `$feature/<key>`, so a row whose key names a flag fails the query instead of reading as missing.+ """+ if (+ not self.context.uses_new_events_schema()+ or node.name not in _JSON_KEY_PATH_FUNCTIONS+ or len(node.args) < 2+ or isinstance(node.args[1], ast.Constant)+ ):+ return None+ field_type = resolve_field_type(node.args[0])+ if not isinstance(field_type, ast.FieldType) or not _is_events_properties(field_type, self.context):+ return None+ key = self.visit(node.args[1])+ document = ast.Call(+ name="multiIf",+ args=[+ _call(+ "throwIf", [_names_feature_flag_property(clone_expr(key)), _const(RUNTIME_FEATURE_FLAG_KEY_ERROR)]+ ),+ _const(""),+ _names_temporary_event_property(clone_expr(key)),+ _temporary_properties_document(field_type),+ self.visit(node.args[0]),+ ],+ type=ast.StringType(nullable=False),+ )+ return ast.Call(+ start=node.start,+ end=node.end,+ type=node.type,+ name=node.name,+ args=[document, key, *[self.visit(arg) for arg in node.args[2:]]],+ params=node.params,+ distinct=node.distinct,+ within_group=node.within_group,+ order_by=node.order_by,+ filter_expr=node.filter_expr,+ )+def _rewrite_json_value_on_temporary_property(self, node: ast.Call) -> ast.Expr | None:"""`JSON_VALUE(properties, '$."$set".email')` on native events, applied to the `temporary_properties` document.@@ -1599,7 +1724,8 @@ class ClickHousePropertyResolver(CloningVisitor):first_key_arg = node.args[1]if not isinstance(first_key_arg, ast.Constant):- raise QueryError("JSONHas over native event properties requires a constant first key")+ # A key computed per row reads the serialized document, which the printer masks for restricted keys.+ return Noneif not isinstance(first_key_arg.value, str):return ast.Constant(value=False, type=ast.BooleanType(nullable=False))first_key = first_key_arg.valuediff --git a/posthog/hogql/transforms/property_types.py b/posthog/hogql/transforms/property_types.pyindex d7fd91f605a4..5aa840a695bb 100644--- a/posthog/hogql/transforms/property_types.py+++ b/posthog/hogql/transforms/property_types.py@@ -15,7 +15,6 @@ from posthog.hogql.database.schema.events import (from posthog.hogql.database.schema.flag_evaluations import FlagEvaluationsTablefrom posthog.hogql.database.schema.groups import GroupsTablefrom posthog.hogql.database.schema.persons import PersonsTable, RawPersonsTable-from posthog.hogql.errors import QueryErrorfrom posthog.hogql.escape_sql import escape_hogql_identifierfrom posthog.hogql.helpers.timestamp_visitor import parse_zoned_datetime_stringfrom posthog.hogql.property_metadata import load_property_metadata@@ -369,11 +368,12 @@ class PropertySwapper(CloningVisitor):"person_properties",)):- if property_path is None:- if self._json_extract_has_runtime_path(node):- raise QueryError("JSONExtract over native event properties requires a constant first key")+ first_key = self._json_extract_first_key(node)+ if first_key is None:+ # A key computed per row can name any property, so the call keeps the whole document. The native+ # document stores `$feature/<key>` in the `$feature_flags` map, so a key naming a flag reads as missing.return None- return self._json_extract_subcolumn_expr(node, field_arg, field_type, property_path)+ return self._json_extract_subcolumn_expr(node, field_arg, field_type, first_key)if property_path is None:return None@@ -426,23 +426,20 @@ class PropertySwapper(CloningVisitor):return property_path@staticmethod- def _json_extract_has_runtime_path(node: ast.Call) -> bool:- if node.name == "JSONExtract":- path_args = node.args[1:-1]- elif node.name in _JSON_EXTRACT_SCALAR_CASTS or node.name == "JSONExtractRaw":- path_args = node.args[1:]- else:- return False- return any(not isinstance(arg, ast.Constant) for arg in path_args)+ def _json_extract_first_key(node: ast.Call) -> str | int | None:+ path_args = node.args[1:-1] if node.name == "JSONExtract" else node.args[1:]+ if not path_args or not isinstance(path_args[0], ast.Constant):+ return None+ first_key = path_args[0].value+ return first_key if isinstance(first_key, str | int) else Nonedef _json_extract_subcolumn_expr(self,node: ast.Call,field_arg: ast.Field,field_type: ast.FieldType,- property_path: list[str | int],+ first_key: str | int,) -> ast.Expr | None:- first_key = property_path[0]if not isinstance(first_key, str):return ast.Call(start=node.start,diff --git a/posthog/hogql/transforms/test/test_property_types.py b/posthog/hogql/transforms/test/test_property_types.pyindex 2affe64e7f6b..38c28b195348 100644--- a/posthog/hogql/transforms/test/test_property_types.py+++ b/posthog/hogql/transforms/test/test_property_types.py@@ -10,6 +10,7 @@ from posthog.test.base import (ClickhouseTestMixin,NewEventsSchemaSnapshotExtension,_create_event,+ cleanup_materialized_columns,flush_persons_and_events,get_indexes_from_explain,materialized,@@ -34,7 +35,6 @@ from posthog.schema import HogQLQueryModifiers, MaterializationModefrom posthog.hogql import astfrom posthog.hogql.context import HogQLContextfrom posthog.hogql.database.database import Database-from posthog.hogql.errors import QueryErrorfrom posthog.hogql.functions.clickhouse.json import JSON_FUNCTIONSfrom posthog.hogql.functions.udfs import JSON_DROP_KEYS_CLICKHOUSE_NAMEfrom posthog.hogql.parser import parse_select@@ -55,10 +55,12 @@ from posthog.hogql.transforms.property_types import PropertySwapper, build_propefrom posthog.hogql.type_system import ComparisonCompatibilityfrom posthog.clickhouse.client import sync_execute+from posthog.errors import ExposedCHQueryErrorfrom posthog.models import PropertyDefinition, Teamfrom posthog.models.event.sql import EVENTS_PROPERTIES_JSON_TYPE, PERSON_PROPERTIES_JSON_TYPEfrom posthog.models.group.util import create_groupfrom posthog.models.property.util import get_property_string_expr+from posthog.property_columns import TableColumnfrom posthog.schema_enums import PropertyGroupsModefrom posthog.test.test_utils import create_group_type_mapping_without_created_at@@ -169,20 +171,37 @@ class TestNewEventsSchemaArraySubcolumns(SimpleTestCase):)assert rows == [(None, 1, 0), (None, 1, 0), ("null", 0, 1), ("Chrome", 0, 1), ("[]", 0, 1), ("{}", 0, 1)]- @parameterized.expand([("declared", EVENTS_PROPERTIES_JSON_TYPE()), ("dynamic", "JSON")])- def test_numeric_casts_preserve_mixed_native_types(self, _name: str, json_type: str) -> None:+ @parameterized.expand(+ [+ (+ name,+ json_type,+ "toFloat(properties.$screen_height), toFloat(properties.custom), toFloat(properties.nested.score)",+ 3,+ True,+ )+ for name, json_type in (("declared", EVENTS_PROPERTIES_JSON_TYPE()), ("dynamic", "JSON"))+ ]+ + [+ (+ f"{name}_indexed",+ json_type,+ "toFloat(properties.numbers[1]), toFloat(properties.objects[1].score)",+ 2,+ False,+ )+ for name, json_type in (("declared", EVENTS_PROPERTIES_JSON_TYPE()), ("dynamic", "JSON"))+ ]+ )+ def test_numeric_casts_preserve_mixed_native_types(+ self, _name: str, json_type: str, select: str, width: int, reads_subcolumn_directly: bool+ ) -> None:context = self._context()with patch("posthog.hogql.printer.utils.build_property_swapper"):- printed, _ = prepare_and_print_ast(- parse_select(- "SELECT toFloat(properties.$screen_height), toFloat(properties.custom), "- "toFloat(properties.nested.score), toFloat(properties.numbers[1]), toFloat(properties.objects[1].score) FROM events"- ),- context,- "clickhouse",- )- for unwanted in ("dynamicElement", "JSONExtract", "replaceRegexpAll", "toJSONString"):- assert unwanted not in printed, printed+ printed, _ = prepare_and_print_ast(parse_select(f"SELECT {select} FROM events"), context, "clickhouse")+ if reads_subcolumn_directly:+ for unwanted in ("dynamicElement", "JSONExtract", "replaceRegexpAll", "toJSONString"):+ assert unwanted not in printed, printedvalues = [42, 2**63, 2.5, "3.75", "invalid", None, ""]rows = sync_execute("WITH events_json AS (SELECT 1 AS team_id, CAST(arrayJoin(%(documents)s), %(json_type)s) AS properties) "@@ -205,13 +224,13 @@ class TestNewEventsSchemaArraySubcolumns(SimpleTestCase):},)assert rows == [- (42.0,) * 5,- (float(2**63),) * 5,- (2.5,) * 5,- (3.75,) * 5,- (None,) * 5,- (None,) * 5,- (None,) * 5,+ (42.0,) * width,+ (float(2**63),) * width,+ (2.5,) * width,+ (3.75,) * width,+ (None,) * width,+ (None,) * width,+ (None,) * width,]def test_negative_multi_icontains_array_property_stays_optimized(self) -> None:@@ -1475,7 +1494,7 @@ _JSON_SCHEMA_PARITY_PROPERTIES: st.SearchStrategy[dict[str, object]] = st.fixed_not settings.CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA,reason="requires both event tables created by the new-schema CI variant (#63448)",)-class TestEventsSchemaPropertyParity(ClickhouseTestMixin, HypothesisDjangoTestCase, BaseTest):+class TestEventsSchemaStorageSemantics(ClickhouseTestMixin, HypothesisDjangoTestCase, BaseTest):def _query_properties(self, event_uuid: str, use_new_events_schema: bool) -> tuple[Any, ...]:response = execute_hogql_query("SELECT properties.dynamic_value, properties.$browser, JSONHas(properties, '$browser'), "@@ -1532,6 +1551,24 @@ class TestEventsSchemaPropertyParity(ClickhouseTestMixin, HypothesisDjangoTestCaelse:assert native[2] == legacy[2]++_RUNTIME_JSON_KEY_SELECT = (+ "SELECT JSONExtractString(properties, properties.k), JSONHas(properties, properties.k), "+ "JSONType(properties, properties.k), JSONExtractRaw(properties, concat('sec', 'ret')), "+ "arrayMap(key -> JSONExtractString(properties, key), ['a', 'secret']), "+ "JSONExtractString(properties, '$set', concat('em', 'ail')), "+ "JSONExtractString(properties, concat('$', 'set'), 'email'), JSONLength(properties, concat('$', 'set')), "+ "JSONHas(properties, concat('$', 'set'))"+)+++# A @given test runs setUp outside the per-test transaction, so the team it creates stays until the class ends and+# collides with the team that the next test in the same class creates. Keep @given tests out of this class.+ not settings.CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA,+ reason="requires both event tables created by the new-schema CI variant (#63448)",+)+class TestEventsSchemaPropertyParity(ClickhouseTestMixin, BaseTest):def test_feature_flag_interfaces_work_across_event_schemas(self) -> None:native_uuid = _create_event(team=self.team,@@ -1746,13 +1783,6 @@ class TestEventsSchemaPropertyParity(ClickhouseTestMixin, HypothesisDjangoTestCaassert all(legacy_row), legacy_rowassert native_row == legacy_row- with pytest.raises(QueryError, match="requires a constant first key"):- execute_hogql_query(- f"SELECT JSONLength(properties, concat('$', 'set')) FROM events WHERE uuid = '{event_uuid}'",- team=self.team,- context=HogQLContext(team_id=self.team.pk, enable_select_queries=True, use_new_events_schema=True),- )-for restricted_name, restricted_query, expected in (("$set",@@ -1782,6 +1812,167 @@ class TestEventsSchemaPropertyParity(ClickhouseTestMixin, HypothesisDjangoTestCa)assert restricted.results == [expected], restricted_name+ def test_computed_feature_flag_key_fails_on_the_native_table(self) -> None:+ _create_event(+ team=self.team,+ distinct_id="computed-flag-key",+ event="computed-flag-key",+ properties={"$feature/checkout": "control", "$active_feature_flags": ["checkout"]},+ )+ flush_persons_and_events()+ query = (+ "SELECT JSONExtractString(properties, concat('$feature/', 'checkout')) "+ "FROM events WHERE event = 'computed-flag-key'"+ )++ legacy = execute_hogql_query(+ query,+ team=self.team,+ context=HogQLContext(team_id=self.team.pk, enable_select_queries=True, use_new_events_schema=False),+ )+ assert legacy.results == [("control",)]++ with pytest.raises(ExposedCHQueryError, match="can't be read through a key computed per row"):+ execute_hogql_query(+ query,+ team=self.team,+ context=HogQLContext(team_id=self.team.pk, enable_select_queries=True, use_new_events_schema=True),+ )++ @parameterized.expand(+ [+ (+ "runtime_json_keys",+ _RUNTIME_JSON_KEY_SELECT,+ None,+ None,+ [+ ("1", 1, "String", '"s1"', ["1", "s1"], "[email protected]", "[email protected]", 1, 1),+ ("s2", 1, "String", '"s2"', ["3", "s2"], "", "", 0, 0),+ ("", 0, "Null", "", ["", ""], "", "", 0, 0),+ ],+ ),+ (+ "runtime_json_keys_restricted",+ _RUNTIME_JSON_KEY_SELECT,+ "secret",+ None,+ [+ ("1", 1, "String", "", ["1", ""], "[email protected]", "[email protected]", 1, 1),+ ("", 0, "Null", "", ["3", ""], "", "", 0, 0),+ ("", 0, "Null", "", ["", ""], "", "", 0, 0),+ ],+ ),+ (+ "runtime_json_keys_restricted_moved",+ _RUNTIME_JSON_KEY_SELECT,+ "$set",+ None,+ [+ ("1", 1, "String", '"s1"', ["1", "s1"], "", "", 0, 0),+ ("s2", 1, "String", '"s2"', ["3", "s2"], "", "", 0, 0),+ ("", 0, "Null", "", ["", ""], "", "", 0, 0),+ ],+ ),+ (+ "moved_key_read_as_a_deeper_key",+ "SELECT JSONExtractString(properties, 'by_tier', JSONExtractString(properties, '$set_once', 'tier'))",+ None,+ None,+ [("ok",), ("",), ("",)],+ ),+ (+ "array_index_over_mixed_types",+ "SELECT properties.arr.1, properties.arr[1], properties.nested_arr.1.2, properties.arr_obj.1.id, "+ "toFloat(properties.nested_arr.1.2)",+ None,+ None,+ [("x", "x", "2", "1", 2.0), (None, None, None, None, None), (None, None, None, None, None)],+ ),+ (+ "array_index_on_a_declared_array",+ "SELECT properties.$exception_functions[-1], properties.$exception_functions.1",+ None,+ None,+ [("second", "first"), (None, None), (None, None)],+ ),+ (+ "percent_in_key",+ "SELECT JSONExtractString(properties, 'completion%'), JSONHas(properties, 'completion%'), "+ "JSONExtractRaw(properties, 'completion%'), JSONExtractInt(properties, 'completion%')",+ None,+ None,+ [("50", 1, '"50"', 50), ("", 0, "", 0), ("", 0, "", 0)],+ ),+ (+ "materialized_group_property",+ "SELECT goe_0.properties.name, goe_0.properties.name = 'Org One'",+ None,+ "name",+ [("Org One", 1), (None, 0), (None, 0)],+ ),+ ]+ )+ def test_query_shapes_read_the_same_on_both_schemas(+ self,+ _name: str,+ select: str,+ restricted_property: str | None,+ materialized_group_property: str | None,+ expected: list[tuple[Any, ...]],+ ) -> None:+ for minute, properties, group0_properties in (+ (+ 30,+ {+ "k": "a",+ "a": "1",+ "secret": "s1",+ "arr": ["x", "y"],+ "nested_arr": [[1, 2], [3]],+ "arr_obj": [{"id": 1}],+ "completion%": "50",+ "by_tier": {"gold": "ok"},+ "$exception_functions": ["first", "second"],+ "$set": {"email": "[email protected]"},+ "$set_once": {"tier": "gold"},+ },+ {"name": "Org One"},+ ),+ (31, {"k": "secret", "a": "3", "secret": "s2", "arr": "notarr", "nested_arr": 7, "arr_obj": "o"}, None),+ (32, {"k": "missing", "arr": 5}, None),+ ):+ _create_event(+ team=self.team,+ distinct_id="shape-parity",+ event="shape-parity",+ timestamp=f"2024-01-15T10:{minute}:00Z",+ properties=properties,+ group0_properties=group0_properties,+ )+ flush_persons_and_events()+ if materialized_group_property is not None:+ columns = pytest.importorskip("ee.clickhouse.materialized_columns.columns")+ columns.materialize(+ "events", materialized_group_property, table_column=cast(TableColumn, "group0_properties")+ )+ self.addCleanup(cleanup_materialized_columns)++ for use_new_events_schema in (False, True):+ context = HogQLContext(+ team_id=self.team.pk, enable_select_queries=True, use_new_events_schema=use_new_events_schema+ )+ if restricted_property is not None:+ context.restricted_properties = {+ RestrictedProperty(name=restricted_property, property_type=PropertyDefinition.Type.EVENT)+ }+ response = execute_hogql_query(+ f"{select} FROM events WHERE event = 'shape-parity' ORDER BY timestamp",+ team=self.team,+ context=context,+ )+ assert response.results == expected, use_new_events_schema+# ── Timezone index pruning tests ──────────────────────────────────────────────#