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.

fix(hogql): read moved event properties from temporary_properties (#107043)

Sandy Spicerc92f3c579e5e
diff --git a/.github/new-events-schema-targets.txt b/.github/new-events-schema-targets.txt
index b5d653fafcb6..c84bc1d0e676 100644
--- a/.github/new-events-schema-targets.txt
+++ b/.github/new-events-schema-targets.txt
@@ -41,6 +41,7 @@ products/web_analytics/backend/hogql_queries
# Code outside HogQL that builds events SQL itself and branches on the schema
posthog/dags/tests/test_deletes.py
+posthog/models/person/test/test_point_in_time_properties_integration.py
posthog/models/team/test_production_event_activation.py
posthog/models/test/test_deletion_targets.py
posthog/tasks/test/test_ai_observability_usage_report.py
diff --git a/docs/internal/clickhouse-utility-udfs.md b/docs/internal/clickhouse-utility-udfs.md
index b3d77d5df8c1..478987c778de 100644
--- a/docs/internal/clickhouse-utility-udfs.md
+++ b/docs/internal/clickhouse-utility-udfs.md
@@ -73,6 +73,10 @@ Both functions use the same executable. The temporary entry point uses `--tempor
Documents exceeding the shared depth limit produce `{}` in the temporary output; the permanent cleaner quarantines the original document.
Native events retain `temporary_properties` for 60 days after insertion, including historical events; TTL merges clear the column asynchronously.
+On native events, HogQL reads a property in this allowlist from `temporary_properties`: property access such as `properties.$set.email`, filters, `JSONHas`, `JSONLength`, `JSONType`, the `JSONExtract*` functions with the property as their first key, and `JSON_VALUE` with the property as the first member of its path.
+These functions reject a first key computed per row, because such a key can name a moved property.
+Whole-document reads of `properties`, such as `SELECT properties`, do not include these properties, because rebuilding them would serialize `temporary_properties` on every row read.
+`is_temporary_event_property` in `posthog/clickhouse/events_json.py` mirrors the allowlist, so update both together.
Fresh installations use the updated schema definitions. Existing tables require a manual schema rollout and feature-flag query compatibility before native reads are enabled.
Native-event queries derive `$active_feature_flags` from the `$feature_flags` map, excluding empty and `false` values and restricted flags. `$false` counts as active, and reads of `$feature/<key>`, `$feature_flags.<key>` and the `$feature_flags` map return it as `false`. Whole-document reads of `properties`, and batch exports of the whole `$feature_flags` map, return it as stored; single-flag export fields and filters map it back. Array order follows the stored map rather than the original SDK evaluation order. No separate active-flags column is required.
diff --git a/posthog/clickhouse/events_json.py b/posthog/clickhouse/events_json.py
index 4df827e8f935..98da5ee85703 100644
--- a/posthog/clickhouse/events_json.py
+++ b/posthog/clickhouse/events_json.py
@@ -13,6 +13,40 @@ WRITABLE_EVENTS_JSON_TABLE = "writable_events_json"
DISTRIBUTED_EVENTS_JSON_TABLE = "events_json"
KAFKA_EVENTS_NATIVE_JSON_TABLE = "kafka_events_json_native_json"
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(
+ {
+ "$set",
+ "$set_once",
+ "$unset",
+ "$group_set",
+ "$feature_flag_request_id",
+ "$debug_first_full_snapshot_timestamp",
+ "$snapshot_max_depth_exceeded",
+ "$sess_rec_flush_size",
+ "$session_recording_remote_config",
+ "$session_recording_network_payload_capture",
+ "$session_recording_canvas_recording",
+ "$replay_script_config",
+ "$sent_at",
+ "$lib_rate_limit_remaining_tokens",
+ "$lib_custom_api_host",
+ }
+)
+_TEMPORARY_EVENT_PROPERTY_ROOT_PREFIX = "$sdk_debug_"
+
+
+def is_temporary_event_property(key: str) -> bool:
+ """Whether the native cleaner stores this top-level event property in `temporary_properties`.
+
+ A dotted key is classified by the part before its first dot, as the cleaner does before it expands the key.
+ """
+ if not key.startswith("$"):
+ return False
+ root = key.split(".", 1)[0]
+ return root in _TEMPORARY_EVENT_PROPERTY_ROOTS or root.startswith(_TEMPORARY_EVENT_PROPERTY_ROOT_PREFIX)
EVENTS_PROPERTIES_JSON_SUBCOLUMN_DECLARED_TYPES: dict[str, str] = {
diff --git a/posthog/hogql/printer/clickhouse.py b/posthog/hogql/printer/clickhouse.py
index 1c760536b8ed..e101c5b57bc8 100644
--- a/posthog/hogql/printer/clickhouse.py
+++ b/posthog/hogql/printer/clickhouse.py
@@ -43,6 +43,7 @@ from posthog.hogql.restricted_properties import RESTRICTABLE_JSON_BLOB_COLUMNS,
from posthog.hogql.type_system import parse_sql_runtime_type
from posthog.hogql.visitor import GetFieldsTraverser, clone_expr
+from posthog.clickhouse.events_json import TEMPORARY_PROPERTIES_COLUMN
from posthog.exchange_rate_constants import EXCHANGE_RATE_DECIMAL_PRECISION, EXCHANGE_RATE_DICTIONARY_NAME
from posthog.uuidt import UUIDT
from posthog.week_start_day import WeekStartDay
@@ -569,7 +570,7 @@ class ClickHousePrinter(BasePrinter):
resolved_field = type.resolve_database_field(self.context)
if not isinstance(resolved_field, StringJSONDatabaseField):
return None
- if resolved_field.name not in ("properties", "person_properties"):
+ if resolved_field.name not in ("properties", "person_properties", TEMPORARY_PROPERTIES_COLUMN):
return None
if not isinstance(type.table_type, ast.BaseTableType):
return None
diff --git a/posthog/hogql/restricted_properties.py b/posthog/hogql/restricted_properties.py
index 550b0cc6f9b3..e1217f7a437d 100644
--- a/posthog/hogql/restricted_properties.py
+++ b/posthog/hogql/restricted_properties.py
@@ -9,7 +9,7 @@ from posthog.hogql.database.schema.flag_evaluations import FlagEvaluationsTable
from posthog.hogql.database.schema.groups import GroupsTable, RawGroupsTable
from posthog.hogql.database.schema.persons import PersonsTable, RawPersonsTable
-from posthog.clickhouse.events_json import UNPARSEABLE_PROPERTIES_KEY
+from posthog.clickhouse.events_json import TEMPORARY_PROPERTIES_COLUMN, UNPARSEABLE_PROPERTIES_KEY
from posthog.constants import GROUP_TYPES_LIMIT
logger = structlog.get_logger(__name__)
@@ -21,6 +21,8 @@ RESTRICTABLE_JSON_BLOB_COLUMNS: frozenset[str] = frozenset(
{
"properties", # events.properties, persons.properties, groups.group_properties reads via the HogQL name
"person_properties", # EventsPersonSubTable (PoE mode)
+ # Not in the catalog. The property resolver reads it as the masked document for a restricted moved property.
+ TEMPORARY_PROPERTIES_COLUMN,
"group_properties", # groups / raw_groups
# EventsGroupSubTable (group-on-events mode) exposes each group type's blob on the events table.
*(f"group{index}_properties" for index in range(GROUP_TYPES_LIMIT)),
diff --git a/posthog/hogql/transforms/clickhouse_property_resolution.py b/posthog/hogql/transforms/clickhouse_property_resolution.py
index c974ddb78f4e..629badd4b773 100644
--- a/posthog/hogql/transforms/clickhouse_property_resolution.py
+++ b/posthog/hogql/transforms/clickhouse_property_resolution.py
@@ -21,6 +21,7 @@ so it treats both an empty string and the literal text `"null"` as "not set". Th
exist in the blob" test, but tightening it would change query results.
"""
+import re
from collections.abc import Sequence
from dataclasses import dataclass, replace
from typing import Literal, cast
@@ -29,7 +30,7 @@ from posthog.hogql import ast
from posthog.hogql.base import _T_AST
from posthog.hogql.constants import EXCEPTION_STRING_ARRAY_PROPERTIES, FEATURE_FLAG_FALSE_VARIANT_SENTINEL
from posthog.hogql.context import HogQLContext
-from posthog.hogql.database.models import DatabaseField, MapStringDatabaseField
+from posthog.hogql.database.models import DatabaseField, MapStringDatabaseField, StringJSONDatabaseField
from posthog.hogql.errors import QueryError
from posthog.hogql.functions.mapping import HOGQL_COMPARISON_MAPPING
from posthog.hogql.printer.base import resolve_field_type
@@ -49,7 +50,11 @@ from posthog.hogql.type_system import (
from posthog.hogql.utils import ilike_matches, like_matches
from posthog.hogql.visitor import CloningVisitor, clone_expr
-from posthog.clickhouse.events_json import DISTRIBUTED_EVENTS_JSON_TABLE
+from posthog.clickhouse.events_json import (
+ DISTRIBUTED_EVENTS_JSON_TABLE,
+ TEMPORARY_PROPERTIES_COLUMN,
+ is_temporary_event_property,
+)
from posthog.clickhouse.property_groups import property_groups
from posthog.clickhouse.workload import Workload
from posthog.schema_enums import MaterializationMode, PropertyGroupsMode
@@ -89,6 +94,7 @@ class MaterializedPropertySource:
has_ngram_lower_index: bool = False
has_bloom_filter_index: bool = False
has_bloom_filter_lower_index: bool = False
+ json_column: str | None = None
def _unwrap_to_table_type(field_type: ast.FieldType) -> ast.TableType | None:
@@ -184,6 +190,11 @@ def resolve_json_subcolumn_source(
column=property_name,
is_nullable=True,
column_type="Dynamic",
+ json_column=(
+ TEMPORARY_PROPERTIES_COLUMN
+ if field_name == "properties" and is_temporary_event_property(property_name)
+ else None
+ ),
)
@@ -252,41 +263,54 @@ def _sentinel(value: str) -> ast.Constant:
return ast.Constant(value=value, inline_sentinel=True)
-def _augment_plain_table_type(table_type: ast.TableType, column_name: str, is_nullable: bool) -> ast.TableType:
+def _augment_plain_table_type(
+ table_type: ast.TableType, column_name: str, is_nullable: bool, database_field: type[DatabaseField]
+) -> ast.TableType:
table = table_type.table
if table.has_field(column_name):
return table_type
- synthetic = DatabaseField(name=column_name, nullable=is_nullable)
+ synthetic = database_field(name=column_name, nullable=is_nullable)
augmented = table.model_copy(update={"fields": {**table.fields, column_name: synthetic}})
return ast.TableType(table=augmented)
def _augment_table_type(
- table_type: ast.Type, column_name: str, *, is_nullable: bool
+ table_type: ast.Type, column_name: str, *, is_nullable: bool, database_field: type[DatabaseField]
) -> ast.TableType | ast.TableAliasType | None:
if isinstance(table_type, ast.VirtualTableType):
# PoE person properties: the physical mat/group columns live on the underlying events table.
- return _augment_table_type(table_type.table_type, column_name, is_nullable=is_nullable)
+ return _augment_table_type(
+ table_type.table_type, column_name, is_nullable=is_nullable, database_field=database_field
+ )
if isinstance(table_type, (ast.TableAliasType, ast.ColumnAliasedTableType)):
inner = table_type.table_type
if not isinstance(inner, ast.TableType):
return None
return ast.TableAliasType(
- alias=table_type.alias, table_type=_augment_plain_table_type(inner, column_name, is_nullable)
+ alias=table_type.alias,
+ table_type=_augment_plain_table_type(inner, column_name, is_nullable, database_field),
)
if isinstance(table_type, ast.TableType):
- return _augment_plain_table_type(table_type, column_name, is_nullable)
+ return _augment_plain_table_type(table_type, column_name, is_nullable, database_field)
return None
-def _synthetic_column_field(field_type: ast.FieldType, column_name: str, *, is_nullable: bool) -> ast.Field | None:
+def _synthetic_column_field(
+ field_type: ast.FieldType,
+ column_name: str,
+ *,
+ is_nullable: bool,
+ database_field: type[DatabaseField] = DatabaseField,
+) -> ast.Field | None:
"""A typed `Field` for a physical ClickHouse column that the HogQL schema doesn't know about.
Materialized / dmat / property-group columns exist on the table but aren't in the HogQL schema, so a plain `Field`
can't resolve to them. Build a fake `DatabaseField` on a copy of the table and point a fresh `FieldType` at it,
keeping any table alias so the printed prefix (`events.` / `e.`) is unchanged.
"""
- table_type = _augment_table_type(field_type.table_type, column_name, is_nullable=is_nullable)
+ table_type = _augment_table_type(
+ field_type.table_type, column_name, is_nullable=is_nullable, database_field=database_field
+ )
if table_type is None:
return None
return ast.Field(
@@ -295,6 +319,19 @@ def _synthetic_column_field(field_type: ast.FieldType, column_name: str, *, is_n
)
+def _temporary_properties_document(field_type: ast.FieldType) -> ast.Field:
+ """The `temporary_properties` blob of the events table that `field_type` reads from.
+
+ It is a JSON blob field, so the printer serializes it and drops restricted keys from it as it does for
+ `properties`. Reads of a moved key use it when a restricted child hides the key's subcolumn.
+ """
+ document = _synthetic_column_field(
+ field_type, TEMPORARY_PROPERTIES_COLUMN, is_nullable=False, database_field=StringJSONDatabaseField
+ )
+ assert document is not None
+ return document
+
+
def _materialized_head_expr(
source: MaterializedPropertySource,
field_type: ast.FieldType,
@@ -360,8 +397,14 @@ def _json_subcolumn_access(
if not isinstance(key, str):
break
path.append(key)
+ json_field = (
+ ast.Field(chain=[field_type.name], type=field_type)
+ if source.json_column is None
+ else _synthetic_column_field(field_type, source.json_column, is_nullable=False)
+ )
+ assert json_field is not None
value: ast.Expr = ast.JsonSubcolumnAccess(
- expr=ast.Field(chain=[field_type.name], type=field_type),
+ expr=json_field,
keys=path,
access_type=access_type,
type=_column_constant_type_for_read(source, is_nullable=is_nullable),
@@ -595,8 +638,41 @@ def _is_events_properties(field_type: ast.FieldType, context: HogQLContext) -> b
)
+def _is_moved_events_property(field_type: ast.FieldType, key: str, context: HogQLContext) -> bool:
+ """Whether `key` of native `events.properties` is stored in `temporary_properties` instead."""
+ return (
+ context.uses_new_events_schema()
+ and is_temporary_event_property(key)
+ and _is_events_properties(field_type, context)
+ )
+
+
FEATURE_FLAG_PROPERTY_PREFIX = "$feature/"
+# JSON functions that take a key path and that nothing earlier rewrites to read one property. The printer passes them
+# the serialized `properties` document, which never holds a key the native cleaner moves to `temporary_properties`.
+_TEMPORARY_PROPERTY_JSON_PATH_FUNCTIONS = frozenset(
+ {
+ "JSONExtractArrayRaw",
+ "JSONExtractKeys",
+ "JSONExtractKeysAndValues",
+ "JSONExtractKeysAndValuesRaw",
+ "JSONLength",
+ "JSONType",
+ }
+)
+
+_JSON_PATH_FIRST_MEMBER = re.compile(
+ r"""^\$(?:\.(?:"(?P<dot_quoted>[^"]*)"|(?P<dot>[^.\[]+))|\[(?:"(?P<bracket_double>[^"]*)"|'(?P<bracket_single>[^']*)')\])"""
+)
+
+
+def _json_path_first_member(path: str) -> str | None:
+ match = _JSON_PATH_FIRST_MEMBER.match(path)
+ if match is None:
+ return None
+ return next(member for member in match.groups() if member is not None)
+
def _is_virtual_feature_flag_key(key: str) -> bool:
"""Whether a native events property is rebuilt from the `$feature_flags` map instead of read under its own name."""
@@ -800,6 +876,9 @@ def _substitute_value_read(node: ast.PropertyAccess, context: HogQLContext) -> a
source = resolve_materialized_property_source(field_type, first_key, context)
if source is None:
+ if _is_moved_events_property(field_type, first_key, context):
+ _record_property_usage(context, None)
+ return ast.PropertyAccess(expr=_temporary_properties_document(field_type), keys=node.keys, type=node.type)
# A physical Map column (logs/spans/metrics attributes) reads an un-grouped key via map subscript — the JSON
# fallback would print JSONExtract, which ClickHouse rejects on a Map. Plain JSON blobs (events.properties)
# keep the JSON fallback.
@@ -1217,6 +1296,14 @@ class ClickHousePropertyResolver(CloningVisitor):
if feature_flag_extract is not None:
return feature_flag_extract
+ temporary_property_json_function = self._rewrite_json_function_on_temporary_property(node)
+ if temporary_property_json_function is not None:
+ return temporary_property_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
+
json_extract_on_events_json = self._rewrite_json_extract_on_events_json_subcolumn(node)
if json_extract_on_events_json is not None:
return json_extract_on_events_json
@@ -1277,6 +1364,79 @@ class ClickHousePropertyResolver(CloningVisitor):
args=[ast.Call(name="ifNull", args=[value, _sentinel("")]), *[self.visit(arg) for arg in node.args[2:]]],
)
+ def _rewrite_json_function_on_temporary_property(self, node: ast.Call) -> ast.Expr | None:
+ """`f(properties, '$set', ...)` on native events, applied to the JSON of `$set` from `temporary_properties`."""
+ if (
+ not self.context.uses_new_events_schema()
+ or node.name not in _TEMPORARY_PROPERTY_JSON_PATH_FUNCTIONS
+ or len(node.args) < 2
+ ):
+ 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
+ if 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")
+ first_key = node.args[1].value
+ if not isinstance(first_key, str) or not is_temporary_event_property(first_key):
+ return None
+ source = resolve_json_subcolumn_source(
+ field_type, DISTRIBUTED_EVENTS_JSON_TABLE, "properties", first_key, self.context
+ )
+ if source is None:
+ # A restriction on the key or on one of its children leaves no source.
+ args: list[ast.Expr] = [
+ _temporary_properties_document(field_type),
+ *[self.visit(arg) for arg in node.args[1:]],
+ ]
+ else:
+ json_value = _json_subcolumn_value_expr(field_type, [first_key], source=source, as_json=True)
+ args = [
+ ast.Call(name="ifNull", args=[json_value, _sentinel("")], type=ast.StringType(nullable=False)),
+ *[self.visit(arg) for arg in node.args[2:]],
+ ]
+ return ast.Call(
+ start=node.start,
+ end=node.end,
+ type=node.type,
+ name=node.name,
+ args=args,
+ 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.
+
+ That document has the same top-level layout as `properties`, so the path applies unchanged. The printer drops
+ restricted keys from it as it does for `properties`.
+ """
+ if (
+ not self.context.uses_new_events_schema()
+ or node.name != "JSON_VALUE"
+ or len(node.args) != 2
+ or not isinstance(node.args[1], ast.Constant)
+ or not isinstance(node.args[1].value, str)
+ ):
+ return None
+ first_member = _json_path_first_member(node.args[1].value)
+ if first_member is None or not is_temporary_event_property(first_member):
+ 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
+ return ast.Call(
+ start=node.start,
+ end=node.end,
+ type=node.type,
+ name=node.name,
+ args=[_temporary_properties_document(field_type), self.visit(node.args[1])],
+ )
+
def _rewrite_feature_flag_json_has(self, node: ast.Call) -> ast.Expr | None:
if (
not self.context.uses_new_events_schema()
@@ -1385,6 +1545,20 @@ class ClickHousePropertyResolver(CloningVisitor):
return self.visit_property_access(property_access)
return None
source = resolve_materialized_property_source(field_type, property_name, self.context)
+ if source is None and _is_moved_events_property(field_type, property_name, self.context):
+ # toJSONString of the extracted text would quote an object as a string, so extract the raw JSON instead.
+ _record_property_usage(self.context, None)
+ return ast.Call(
+ name="nullIf",
+ args=[
+ ast.Call(
+ name="JSONExtractRaw",
+ args=[_temporary_properties_document(field_type), ast.Constant(value=property_name)],
+ ),
+ _sentinel(""),
+ ],
+ type=ast.StringType(nullable=True),
+ )
if source is None or source.kind != "json_subcolumn":
return None
@@ -1498,7 +1672,15 @@ class ClickHousePropertyResolver(CloningVisitor):
return ast.Constant(value=False, type=ast.BooleanType(nullable=False))
if native_property_path_overlaps_restriction(first_key, field_type.table_type, self.context):
# Read the masked document so nested and computed keys cannot inspect a restricted child.
- return None
+ if not _is_moved_events_property(field_type, first_key, self.context):
+ return None
+ return ast.Call(
+ start=node.start,
+ end=node.end,
+ type=node.type,
+ name=node.name,
+ args=[_temporary_properties_document(field_type), *[self.visit(arg) for arg in node.args[1:]]],
+ )
source = resolve_json_subcolumn_source(
field_type, table_type.table.to_printed_clickhouse(self.context), field.name, first_key, self.context
diff --git a/posthog/hogql/transforms/test/test_property_types.py b/posthog/hogql/transforms/test/test_property_types.py
index c276e02da3b3..a2b5903fcc0c 100644
--- a/posthog/hogql/transforms/test/test_property_types.py
+++ b/posthog/hogql/transforms/test/test_property_types.py
@@ -34,6 +34,8 @@ from posthog.schema import HogQLQueryModifiers, MaterializationMode
from posthog.hogql import ast
from posthog.hogql.context import HogQLContext
from posthog.hogql.database.database import Database
+from posthog.hogql.errors import QueryError
+from posthog.hogql.functions.clickhouse.json import JSON_FUNCTIONS
from posthog.hogql.functions.udfs import JSON_DROP_KEYS_CLICKHOUSE_NAME
from posthog.hogql.parser import parse_select
from posthog.hogql.printer import prepare_and_print_ast
@@ -1657,6 +1659,129 @@ class TestEventsSchemaPropertyParity(ClickhouseTestMixin, HypothesisDjangoTestCa
)
assert inactive.results == [("[]", 1, 1)]
+ def test_moved_mutation_properties_read_the_same_on_both_schemas(self) -> None:
+ event_uuid = _create_event(
+ team=self.team,
+ distinct_id="moved-properties",
+ event="$identify",
+ properties={
+ "$set": {"email": "[email protected]", "plan": {"tier": "pro"}},
+ "$set_once": {"initial_referrer": "https://example.com", "is_beta": True},
+ "$unset": ["old_key"],
+ "$sdk_debug_replay_flushed_size": 42,
+ "$browser": "Firefox",
+ },
+ )
+ flush_persons_and_events()
+
+ query = (
+ "SELECT properties.$set.email, JSONExtractString(properties, '$set', 'email'), "
+ "JSONHas(properties, '$set'), JSONHas(properties, '$set', 'plan', 'tier'), "
+ "properties.$set_once.initial_referrer, properties.$set.plan.tier, JSONLength(properties, '$set'), "
+ "JSONType(properties, '$unset'), JSONExtractKeys(properties, '$set'), "
+ "JSONExtractArrayRaw(properties, '$unset'), toFloat(properties.$sdk_debug_replay_flushed_size), "
+ "properties.$sdk_debug_replay_flushed_size, properties.$browser, JSONExtractRaw(properties, '$set'), "
+ "properties.$unset, JSONExtractKeysAndValuesRaw(properties, '$set') "
+ f"FROM events WHERE uuid = '{event_uuid}' AND properties.$set.email = '[email protected]'"
+ )
+ for use_new_events_schema in (False, True):
+ response = execute_hogql_query(
+ query,
+ team=self.team,
+ context=HogQLContext(
+ team_id=self.team.pk, enable_select_queries=True, use_new_events_schema=use_new_events_schema
+ ),
+ )
+ assert response.results == [
+ (
+ 1,
+ 1,
+ "https://example.com",
+ "pro",
+ 2,
+ "Array",
+ ["email", "plan"],
+ ['"old_key"'],
+ 42.0,
+ "42",
+ "Firefox",
+ '{"email":"[email protected]","plan":{"tier":"pro"}}',
+ '["old_key"]',
+ [("email", '"[email protected]"'), ("plan", '{"tier":"pro"}')],
+ )
+ ], use_new_events_schema
+
+ # One call per registered JSON function, so a newly registered function fails here until native reads the
+ # moved key. isValidJSON and JSONArrayLength take no key path.
+ moved_key_calls = {
+ "JSONHas": "JSONHas(properties, '$set', 'email')",
+ "JSONLength": "JSONLength(properties, '$set')",
+ "JSONType": "JSONType(properties, '$set')",
+ "JSONExtract": "JSONExtract(properties, '$set', 'email', 'String')",
+ "JSONExtractUInt": "JSONExtractUInt(properties, '$sdk_debug_replay_flushed_size')",
+ "JSONExtractInt": "JSONExtractInt(properties, '$sdk_debug_replay_flushed_size')",
+ "JSONExtractFloat": "JSONExtractFloat(properties, '$sdk_debug_replay_flushed_size')",
+ "JSONExtractBool": "JSONExtractBool(properties, '$set_once', 'is_beta')",
+ "JSONExtractString": "JSONExtractString(properties, '$set', 'email')",
+ "JSONExtractKeys": "JSONExtractKeys(properties, '$set')",
+ "JSONExtractRaw": "JSONExtractRaw(properties, '$set', 'plan')",
+ "JSONExtractArrayRaw": "JSONExtractArrayRaw(properties, '$unset')",
+ "JSONExtractKeysAndValues": "JSONExtractKeysAndValues(properties, '$set_once', 'String')",
+ "JSONExtractKeysAndValuesRaw": "JSONExtractKeysAndValuesRaw(properties, '$set_once')",
+ "JSON_VALUE": "JSON_VALUE(properties, '$.\"$set\".email')",
+ }
+ assert set(moved_key_calls) | {"isValidJSON", "JSONArrayLength"} == set(JSON_FUNCTIONS)
+ legacy_row, native_row = (
+ execute_hogql_query(
+ f"SELECT {', '.join(moved_key_calls.values())} FROM events WHERE uuid = '{event_uuid}'",
+ team=self.team,
+ context=HogQLContext(
+ team_id=self.team.pk, enable_select_queries=True, use_new_events_schema=use_new_events_schema
+ ),
+ ).results[0]
+ for use_new_events_schema in (False, True)
+ )
+ assert all(legacy_row), legacy_row
+ assert 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",
+ "SELECT properties.$set.email, JSONExtractRaw(properties, '$set'), JSONHas(properties, '$set'), "
+ "JSONLength(properties, '$set'), JSONExtractKeys(properties, '$set'), "
+ "properties.$set_once.initial_referrer, JSON_VALUE(properties, '$.\"$set\".email')",
+ (None, "", 0, 0, [], "https://example.com", ""),
+ ),
+ (
+ "$set.plan",
+ "SELECT properties.$set.email, JSONExtractString(properties, '$set', 'email'), "
+ "JSONExtractRaw(properties, '$set'), JSONHas(properties, '$set', 'plan'), "
+ "JSONLength(properties, '$set'), properties.$set.plan.tier",
+ ("[email protected]", "[email protected]", '{"email":"[email protected]"}', 0, 1, None),
+ ),
+ ):
+ restricted_context = HogQLContext(
+ team_id=self.team.pk, enable_select_queries=True, use_new_events_schema=True
+ )
+ restricted_context.restricted_properties = {
+ RestrictedProperty(name=restricted_name, property_type=PropertyDefinition.Type.EVENT)
+ }
+ restricted = execute_hogql_query(
+ f"{restricted_query} FROM events WHERE uuid = '{event_uuid}'",
+ team=self.team,
+ context=restricted_context,
+ )
+ assert restricted.results == [expected], restricted_name
+
# ── Timezone index pruning tests ──────────────────────────────────────────────
#