: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(hogql): push constant-key JSONExtractString into lazy-table argMax (#61184)
Andy Zhao523fcd556431
diff --git a/posthog/hogql/printer/utils.py b/posthog/hogql/printer/utils.pyindex ab6292282584..26f3c393514f 100644--- a/posthog/hogql/printer/utils.py+++ b/posthog/hogql/printer/utils.py@@ -32,6 +32,10 @@ from posthog.hogql.transforms.geoip_dict_fallback import (geoip_dict_fallback_enabled_for_team,)from posthog.hogql.transforms.in_cohort import resolve_in_cohorts, resolve_in_cohorts_conjoined+from posthog.hogql.transforms.json_property_pushdown import (+ has_rewritable_json_extract,+ rewrite_json_extract_to_property,+)from posthog.hogql.transforms.lazy_tables import resolve_lazy_tablesfrom posthog.hogql.transforms.logical_property_lowering import lower_property_accessfrom posthog.hogql.transforms.projection_pushdown import pushdown_projections@@ -160,6 +164,22 @@ def prepare_ast_for_printing(resolver_factory=resolver_factory,)+ # Project constant-key JSONExtractString on argMax lazy tables (groups/persons) into the+ # aggregate, so it does not materialize the whole JSON blob per row. Rewrites the call to a+ # property access and re-resolves, so the resolver assigns types rather than us building them.+ # Must run after type resolution and before lazy-table resolution.+ if dialect == "clickhouse" and has_rewritable_json_extract(node, context):+ with context.timings.measure("rewrite_json_extract_to_property"):+ node = rewrite_json_extract_to_property(node, context)+ with context.timings.measure("resolve_types_after_json_pushdown"):+ node = resolve_types(+ node,+ context,+ dialect=dialect,+ scopes=[scope.type for scope in stack if scope.type is not None] if stack else None,+ resolver_factory=resolver_factory,+ )+if context.enable_type_aware_cast_simplification:with context.timings.measure("type_aware_cast_simplification"):node = simplify_redundant_type_operations(node, context, dialect)diff --git a/posthog/hogql/transforms/json_property_pushdown.py b/posthog/hogql/transforms/json_property_pushdown.pynew file mode 100644index 000000000000..750a0cb89573--- /dev/null+++ b/posthog/hogql/transforms/json_property_pushdown.py@@ -0,0 +1,103 @@+from posthog.hogql import ast+from posthog.hogql.context import HogQLContext+from posthog.hogql.database.models import StringJSONDatabaseField+from posthog.hogql.visitor import CloningVisitor, TraversingVisitor++# JSON-string extraction calls that are equivalent to a HogQL string property access.+# Other JSONExtract* variants (Int/Float/Bool/Raw) return non-string types, so the property-access+# rewrite would change the result type; those are intentionally left untouched.+STRING_EXTRACT_FUNCTIONS = {"JSONExtractString"}+++def _matched_property_access(node: ast.AST, context: HogQLContext):+ """If `node` is `JSONExtractString(<lazy-table JSON field>, '<constant key>')`, return+ (field_chain, key) so it can be rewritten to a property access. Otherwise return None."""+ if not isinstance(node, ast.Call) or node.name not in STRING_EXTRACT_FUNCTIONS or len(node.args) != 2:+ return None++ field_arg, key = node.args+ if not isinstance(key, ast.Constant) or not isinstance(key.value, str):+ return None++ # The column reference may be wrapped in a field alias by the resolver; unwrap to the Field.+ inner = field_arg.expr if isinstance(field_arg, ast.Alias) else field_arg+ if not isinstance(inner, ast.Field):+ return None+ field_type = field_arg.type+ if isinstance(field_type, ast.FieldAliasType):+ field_type = field_type.type+ if not isinstance(field_type, ast.FieldType):+ return None++ # Only the argMax-based lazy tables (groups/persons) benefit, since they aggregate each+ # requested field. Unwrap aliases/virtual tables to find the underlying table type.+ table_type = field_type.table_type+ while isinstance(table_type, (ast.TableAliasType, ast.ColumnAliasedTableType, ast.VirtualTableType)):+ table_type = table_type.table_type+ if not isinstance(table_type, (ast.LazyTableType, ast.LazyJoinType)):+ return None++ if not isinstance(field_type.resolve_database_field(context), StringJSONDatabaseField):+ return None++ return inner.chain, key.value+++def has_rewritable_json_extract(node: ast.AST, context: HogQLContext) -> bool:+ finder = _Finder(context)+ finder.visit(node)+ return finder.found+++def rewrite_json_extract_to_property(node: ast.AST, context: HogQLContext):+ """+ Rewrite `JSONExtractString(<lazy-table JSON field>, '<constant key>')` into+ `ifNull(<field>.<key>, '')`.++ The argMax-based lazy tables (`groups`, `persons`) aggregate each requested field, so accessing a+ property via dot syntax projects only that single field into the argMax, whereas an explicit+ `JSONExtractString(properties, 'name')` requests the whole `properties` field and makes the argMax+ materialize the entire JSON blob per group/person, which can exhaust memory.++ Property access returns NULL for a missing key while `JSONExtractString` returns ''; the+ `ifNull(..., '')` wrapper restores that, so the rewrite matches `JSONExtractString` for scalar+ values and missing keys and keeps the non-nullable String type.++ Emits untyped nodes; the caller re-runs type resolution to assign types.+ """+ return _Transformer(context).visit(node)+++class _Finder(TraversingVisitor):+ def __init__(self, context: HogQLContext):+ super().__init__()+ self.context = context+ self.found = False++ def visit(self, node: ast.AST | None):+ if not self.found:+ super().visit(node)++ def visit_call(self, node: ast.Call):+ if _matched_property_access(node, self.context) is not None:+ self.found = True+ return+ super().visit_call(node)+++class _Transformer(CloningVisitor):+ def __init__(self, context: HogQLContext):+ super().__init__(clear_types=True)+ self.context = context++ def visit_call(self, node: ast.Call):+ matched = _matched_property_access(node, self.context)+ if matched is not None:+ chain, key = matched+ # JSONExtractString returns '' for a missing key; property access returns NULL. Wrap in+ # ifNull(..., '') to keep that contract and the non-nullable String type.+ return ast.Call(+ name="ifNull",+ args=[ast.Field(chain=[*chain, key]), ast.Constant(value="")],+ )+ return super().visit_call(node)diff --git a/posthog/hogql/transforms/test/test_json_property_pushdown.py b/posthog/hogql/transforms/test/test_json_property_pushdown.pynew file mode 100644index 000000000000..3570e3ff2b38--- /dev/null+++ b/posthog/hogql/transforms/test/test_json_property_pushdown.py@@ -0,0 +1,43 @@+from posthog.test.base import BaseTest++from parameterized import parameterized++from posthog.hogql.context import HogQLContext+from posthog.hogql.parser import parse_select+from posthog.hogql.printer import prepare_and_print_ast+++class TestJSONPropertyPushdown(BaseTest):+ def _print(self, query: str) -> str:+ context = HogQLContext(team_id=self.team.pk, enable_select_queries=True)+ printed, _ = prepare_and_print_ast(parse_select(query), context, dialect="clickhouse")+ return printed++ @parameterized.expand(["groups", "persons"])+ def test_json_extract_string_projects_single_field(self, table: str):+ printed = self._print(f"SELECT JSONExtractString(properties, 'name') AS name FROM {table}")+ self.assertIn("properties___name", printed)++ @parameterized.expand(["groups", "persons"])+ def test_json_extract_string_matches_ifnull_property_access(self, table: str):+ extract = self._print(f"SELECT JSONExtractString(properties, 'name') AS name FROM {table}")+ wrapped = self._print(f"SELECT ifNull(properties.name, '') AS name FROM {table}")+ self.assertEqual(extract, wrapped)++ def test_whole_properties_access_still_aggregates_blob(self):+ printed = self._print("SELECT key, properties FROM groups")+ self.assertIn("argMax(tuple(groups.group_properties)", printed)+ self.assertNotIn("properties___name", printed)++ def test_non_constant_key_is_not_rewritten(self):+ printed = self._print("SELECT key, JSONExtractString(properties, key) AS name FROM groups")+ self.assertIn("argMax(tuple(groups.group_properties)", printed)++ def test_does_not_rewrite_on_hogql_dialect(self):+ context = HogQLContext(team_id=self.team.pk, enable_select_queries=True)+ printed, _ = prepare_and_print_ast(+ parse_select("SELECT JSONExtractString(properties, 'name') AS name FROM groups"),+ context,+ dialect="hogql",+ )+ self.assertIn("JSONExtractString", printed)