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.

chore(messaging): migrate person-properties backfill to HogQL (#60509)

Gustavo H. Strassburgerc2f5c75d3289
diff --git a/posthog/temporal/messaging/backfill_precalculated_person_properties_coordinator_workflow.py b/posthog/temporal/messaging/backfill_precalculated_person_properties_coordinator_workflow.py
index ac8ab1a63b71..a01f9c2dd5dd 100644
--- a/posthog/temporal/messaging/backfill_precalculated_person_properties_coordinator_workflow.py
+++ b/posthog/temporal/messaging/backfill_precalculated_person_properties_coordinator_workflow.py
@@ -10,11 +10,23 @@ import temporalio.activity
import temporalio.workflow
import temporalio.exceptions
+from posthog.hogql import ast
+
from posthog.temporal.common.base import PostHogWorkflow
from posthog.temporal.common.clickhouse import get_client
from posthog.temporal.messaging.backfill_precalculated_person_properties_workflow import (
BackfillPrecalculatedPersonPropertiesInputs,
)
+from posthog.temporal.messaging.hogql_compile import compile_hogql_for_streaming
+
+
+def _combine_where(exprs: list[ast.Expr]) -> ast.Expr | None:
+ """Combine a list of WHERE expressions with AND, or return None for an empty list."""
+ if not exprs:
+ return None
+ if len(exprs) == 1:
+ return exprs[0]
+ return ast.And(exprs=exprs)
@dataclasses.dataclass
@@ -50,24 +62,33 @@ async def get_person_id_ranges_page_activity(inputs: PersonIdRangesPageInputs) -
# Fetch one extra row to check if there's more data
query_limit = limit + 1
- after_clause = "AND id > %(after_person_id)s" if inputs.after_person_id is not None else ""
- person_filter_clause = "AND id = %(person_id)s" if inputs.person_id is not None else ""
- query = f"""
- SELECT id as person_id
- FROM person FINAL
- WHERE team_id = %(team_id)s
- AND is_deleted = 0
- {after_clause}
- {person_filter_clause}
- ORDER BY id
- LIMIT %(limit)s
- FORMAT JSONEachRow
- """
- query_params: dict[str, object] = {"team_id": inputs.team_id, "limit": query_limit}
+ where_exprs: list[ast.Expr] = []
if inputs.after_person_id is not None:
- query_params["after_person_id"] = inputs.after_person_id
+ where_exprs.append(
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.Gt,
+ left=ast.Field(chain=["id"]),
+ right=ast.Constant(value=inputs.after_person_id),
+ )
+ )
if inputs.person_id is not None:
- query_params["person_id"] = inputs.person_id
+ where_exprs.append(
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.Eq,
+ left=ast.Field(chain=["id"]),
+ right=ast.Constant(value=inputs.person_id),
+ )
+ )
+
+ ranges_query_ast = ast.SelectQuery(
+ select=[ast.Alias(alias="person_id", expr=ast.Field(chain=["id"]))],
+ select_from=ast.JoinExpr(table=ast.Field(chain=["persons"])),
+ where=_combine_where(where_exprs),
+ order_by=[ast.OrderExpr(expr=ast.Field(chain=["id"]), order="ASC")],
+ limit=ast.Constant(value=query_limit),
+ )
+
+ query, query_params = await compile_hogql_for_streaming(ranges_query_ast, team_id=inputs.team_id)
ranges: list[tuple[str, str]] = []
current_batch_start: str | None = None
diff --git a/posthog/temporal/messaging/backfill_precalculated_person_properties_workflow.py b/posthog/temporal/messaging/backfill_precalculated_person_properties_workflow.py
index d78496da0109..6d6e4e8f5af5 100644
--- a/posthog/temporal/messaging/backfill_precalculated_person_properties_workflow.py
+++ b/posthog/temporal/messaging/backfill_precalculated_person_properties_workflow.py
@@ -13,6 +13,8 @@ import temporalio.workflow
import temporalio.exceptions
from structlog.contextvars import bind_contextvars
+from posthog.hogql import ast
+
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
from posthog.kafka_client.client import _KafkaProducer
from posthog.kafka_client.routing import get_producer
@@ -22,6 +24,7 @@ from posthog.temporal.common.clickhouse import get_client
from posthog.temporal.common.heartbeat import Heartbeater
from posthog.temporal.common.logger import get_logger
from posthog.temporal.messaging.filter_storage import get_filters_and_properties
+from posthog.temporal.messaging.hogql_compile import compile_hogql_for_streaming
from posthog.temporal.messaging.types import PersonPropertyFilter
from common.hogvm.python.execute import BytecodeResult, execute_bytecode
@@ -33,24 +36,30 @@ LOGGER = get_logger(__name__)
MAX_OPTIMIZED_PROPERTIES = 100 # Safety limit to avoid query complexity issues
-def build_person_properties_select_clause(person_properties: list[str]) -> tuple[str, dict[str, str], dict[str, str]]:
- """Build ClickHouse SELECT expressions for the requested person properties.
+def build_person_properties_select_exprs(
+ person_properties: list[str],
+) -> tuple[list[ast.Alias], dict[str, str]]:
+ """Build HogQL SELECT expressions for the requested person properties.
- Property names come from cohort filters, so they must stay out of the SQL string.
- The returned clause contains only generated aliases and query parameter placeholders.
+ Property names come from cohort filters, so they must never be substring-concatenated
+ into SQL. Using ``ast.Field(chain=["properties", key])`` keeps the key out of the printed
+ SQL: HogQL either rewrites to a materialized column or routes the key through context
+ parameters when emitting ``JSONExtract``.
"""
- property_selects: list[str] = []
- property_alias_mapping: dict[str, str] = {}
- property_query_params: dict[str, str] = {}
+ selects: list[ast.Alias] = []
+ alias_mapping: dict[str, str] = {}
for i, prop in enumerate(person_properties):
- safe_alias = f"prop_{i}"
- property_key_param = f"property_key_{i}"
- property_selects.append(f"JSONExtract(properties, %({property_key_param})s, 'String') as `{safe_alias}`")
- property_alias_mapping[safe_alias] = prop
- property_query_params[property_key_param] = prop
+ alias = f"prop_{i}"
+ selects.append(
+ ast.Alias(
+ alias=alias,
+ expr=ast.Field(chain=["properties", prop]),
+ )
+ )
+ alias_mapping[alias] = prop
- return ",\n ".join(property_selects), property_alias_mapping, property_query_params
+ return selects, alias_mapping
def format_cohort_ids_for_logging(cohort_ids: list[int]) -> str:
@@ -476,53 +485,73 @@ async def backfill_precalculated_person_properties_activity(
# Not in activity context (e.g., during tests), skip metrics
pass
- # Build optimized query to only fetch needed person properties
+ # Build the HogQL SELECT list — either targeted property accessors (so HogQL can use
+ # materialized columns when present) or the full ``properties`` JSON as a fallback.
property_alias_mapping: dict[str, str] = {}
- property_query_params: dict[str, str] = {}
+ select_exprs: list[ast.Expr] = [ast.Alias(alias="person_id", expr=ast.Field(chain=["id"]))]
- if person_properties and len(person_properties) <= MAX_OPTIMIZED_PROPERTIES:
- properties_clause, property_alias_mapping, property_query_params = build_person_properties_select_clause(
- person_properties
- )
+ # A '%' in a property key makes the HogQL printer raise (it can resolve the accessor to a
+ # column identifier, and '%' is banned there). Such keys are rare but valid person-property
+ # names, so when any appear we fall back to fetching the full ``properties`` JSON: the
+ # consumer evaluates filters against the full dict regardless, which keeps these keys working.
+ has_identifier_unsafe_key = any("%" in prop for prop in person_properties)
- logger.info(
- f"Optimized query: fetching {len(person_properties)} specific properties with parameterized keys"
- )
+ if person_properties and len(person_properties) <= MAX_OPTIMIZED_PROPERTIES and not has_identifier_unsafe_key:
+ property_exprs, property_alias_mapping = build_person_properties_select_exprs(person_properties)
+ select_exprs.extend(property_exprs)
+
+ logger.info(f"Optimized query: fetching {len(person_properties)} specific properties via HogQL")
else:
- # Fallback to all properties if we have too many properties or can't determine which ones are needed
- properties_clause = "properties"
+ select_exprs.append(ast.Field(chain=["properties"]))
if person_properties and len(person_properties) > MAX_OPTIMIZED_PROPERTIES:
logger.warning(
f"Too many properties ({len(person_properties)} > {MAX_OPTIMIZED_PROPERTIES}) - falling back to fetching all properties for performance"
)
+ elif has_identifier_unsafe_key:
+ logger.warning(
+ "Property key contains '%' (not a valid HogQL identifier) - falling back to fetching all properties"
+ )
else:
logger.warning(
"Falling back to fetching all properties - could not determine specific properties needed"
)
- person_filter_clause = "AND id = %(person_id)s" if inputs.person_id is not None else ""
- persons_query = f"""
- SELECT
- id as person_id,
- {properties_clause}
- FROM person FINAL
- WHERE team_id = %(team_id)s
- AND id >= %(start_person_id)s
- AND id <= %(end_person_id)s
- AND is_deleted = 0
- {person_filter_clause}
- ORDER BY id
- FORMAT JSONEachRow
- """
-
- query_params = {
- "team_id": inputs.team_id,
- "start_person_id": inputs.start_person_id,
- "end_person_id": inputs.end_person_id,
- **property_query_params,
- }
+ where_exprs: list[ast.Expr] = [
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.GtEq,
+ left=ast.Field(chain=["id"]),
+ right=ast.Constant(value=inputs.start_person_id),
+ ),
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.LtEq,
+ left=ast.Field(chain=["id"]),
+ right=ast.Constant(value=inputs.end_person_id),
+ ),
+ ]
if inputs.person_id is not None:
- query_params["person_id"] = inputs.person_id
+ where_exprs.append(
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.Eq,
+ left=ast.Field(chain=["id"]),
+ right=ast.Constant(value=inputs.person_id),
+ )
+ )
+
+ persons_query_ast = ast.SelectQuery(
+ select=select_exprs,
+ # The HogQL ``persons`` table handles ``team_id`` scoping, argMax/FINAL dedup, and
+ # ``is_deleted = 0`` filtering automatically. Note it also adds an implicit
+ # ``argMax(created_at) < now() + 1 day`` clamp, so future-dated persons (clock skew /
+ # backdated imports) are excluded — unlike the old raw-SQL ``person FINAL`` query.
+ select_from=ast.JoinExpr(table=ast.Field(chain=["persons"])),
+ where=ast.And(exprs=where_exprs),
+ order_by=[ast.OrderExpr(expr=ast.Field(chain=["id"]), order="ASC")],
+ # No explicit limit: compile_hogql_for_streaming uses LimitContext.COHORT_CALCULATION,
+ # which injects LIMIT 1_000_000_000. ID ranges are bounded by batch_size (default
+ # 1000 persons), so this cap is never reached in practice.
+ )
+
+ persons_query, query_params = await compile_hogql_for_streaming(persons_query_ast, team_id=inputs.team_id)
last_person_id = inputs.start_person_id
batch_count = 0
diff --git a/posthog/temporal/messaging/hogql_compile.py b/posthog/temporal/messaging/hogql_compile.py
new file mode 100644
index 000000000000..40e54b1dbeed
--- /dev/null
+++ b/posthog/temporal/messaging/hogql_compile.py
@@ -0,0 +1,33 @@
+from typing import Any
+
+from posthog.hogql import ast
+from posthog.hogql.constants import LimitContext
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.printer import prepare_and_print_ast
+
+from posthog.sync import database_sync_to_async_pool
+
+
+@database_sync_to_async_pool
+def compile_hogql_for_streaming(node: ast.SelectQuery, *, team_id: int) -> tuple[str, dict[str, Any]]:
+ """Compile a HogQL ``SelectQuery`` to ClickHouse SQL for the streaming HTTP client.
+
+ Backfill workflows in this package run HogQL on a background path that has no
+ request-scoped user. They need the activity to behave identically to the previous
+ raw-SQL implementation, so property access-control restrictions are explicitly
+ bypassed with ``restricted_properties=set()`` — otherwise the printer would call
+ ``get_restricted_properties_for_team(team_id, user=None)``, which applies any
+ property-level rules and would silently change cohort evaluation results compared
+ to the raw-SQL baseline.
+
+ Returns the printed SQL and the parameter dict captured on the printer context.
+ """
+ hogql_context = HogQLContext(
+ team_id=team_id,
+ enable_select_queries=True,
+ limit_context=LimitContext.COHORT_CALCULATION,
+ output_format="JSONEachRow",
+ restricted_properties=set(),
+ )
+ sql, _ = prepare_and_print_ast(node, hogql_context, "clickhouse")
+ return sql, hogql_context.values
diff --git a/posthog/temporal/messaging/realtime_cohort_calculation_workflow.py b/posthog/temporal/messaging/realtime_cohort_calculation_workflow.py
index 0a0e0d0ac44e..b9dee9834294 100644
--- a/posthog/temporal/messaging/realtime_cohort_calculation_workflow.py
+++ b/posthog/temporal/messaging/realtime_cohort_calculation_workflow.py
@@ -328,6 +328,11 @@ async def process_realtime_cohort_calculation_activity(inputs: RealtimeCohortCal
def build_query(cohort_obj):
realtime_query = HogQLRealtimeCohortQuery(cohort=cohort_obj, team=cohort_obj.team)
current_members_query = realtime_query.get_query()
+ # Note: restricted_properties is not set here (defaults to None), so the printer
+ # will call get_restricted_properties_for_team and apply any property access-control
+ # rules configured for the team. This is intentionally different from the backfill
+ # path in hogql_compile.py, which bypasses restrictions to match raw-SQL semantics.
+ # Realtime cohort calculation should respect property restrictions.
hogql_context = HogQLContext(
team_id=cohort_obj.team_id,
enable_select_queries=True,
diff --git a/posthog/temporal/messaging/test/test_backfill_precalculated_person_properties_coordinator_workflow.py b/posthog/temporal/messaging/test/test_backfill_precalculated_person_properties_coordinator_workflow.py
index c365edb63df2..9bb52bd7a114 100644
--- a/posthog/temporal/messaging/test/test_backfill_precalculated_person_properties_coordinator_workflow.py
+++ b/posthog/temporal/messaging/test/test_backfill_precalculated_person_properties_coordinator_workflow.py
@@ -1,10 +1,16 @@
+from types import TracebackType
+
import pytest
from unittest.mock import Mock, patch
+from posthog.hogql import ast
+
from posthog.temporal.messaging.backfill_precalculated_person_properties_coordinator_workflow import (
BackfillPrecalculatedPersonPropertiesCoordinatorInputs,
BackfillPrecalculatedPersonPropertiesCoordinatorWorkflow,
+ PersonIdRangesPageInputs,
PersonIdRangesPageResult,
+ get_person_id_ranges_page_activity,
)
@@ -177,3 +183,133 @@ class TestBackfillPrecalculatedPersonPropertiesCoordinatorWorkflow:
log_calls = [str(call) for call in mock_logger.info.call_args_list]
assert any("completed successfully" in call for call in log_calls)
+
+
+def aiter(iterable):
+ """Wrap a plain iterable as an async iterator for use in tests."""
+
+ async def _aiter():
+ for item in iterable:
+ yield item
+
+ return _aiter()
+
+
+class _AsyncClientContextManager:
+ def __init__(self, client: Mock) -> None:
+ self.client = client
+
+ async def __aenter__(self) -> Mock:
+ return self.client
+
+ async def __aexit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_value: BaseException | None,
+ traceback: TracebackType | None,
+ ) -> None:
+ return None
+
+
+class TestGetPersonIdRangesPageActivity:
+ """Tests for get_person_id_ranges_page_activity's HogQL AST construction."""
+
+ @pytest.mark.asyncio
+ async def test_where_is_none_with_no_filters(self):
+ captured: dict[str, object] = {}
+
+ async def fake_compile(node, *, team_id):
+ captured["node"] = node
+ return "SELECT 1 FORMAT JSONEachRow", {}
+
+ mock_client = Mock()
+ mock_client.stream_query_as_jsonl = lambda *a, **kw: aiter([])
+
+ with (
+ patch(
+ "posthog.temporal.messaging.backfill_precalculated_person_properties_coordinator_workflow.compile_hogql_for_streaming",
+ side_effect=fake_compile,
+ ),
+ patch(
+ "posthog.temporal.messaging.backfill_precalculated_person_properties_coordinator_workflow.get_client",
+ return_value=_AsyncClientContextManager(mock_client),
+ ),
+ patch("temporalio.activity.heartbeat"),
+ ):
+ await get_person_id_ranges_page_activity(
+ PersonIdRangesPageInputs(team_id=1, batch_size=10, page_size=5, after_person_id=None)
+ )
+
+ assert "node" in captured
+ node = captured["node"]
+ assert isinstance(node, ast.SelectQuery)
+ assert node.where is None
+
+ @pytest.mark.asyncio
+ async def test_where_is_single_expr_with_only_after_person_id(self):
+ captured: dict[str, object] = {}
+
+ async def fake_compile(node, *, team_id):
+ captured["node"] = node
+ return "SELECT 1 FORMAT JSONEachRow", {}
+
+ mock_client = Mock()
+ mock_client.stream_query_as_jsonl = lambda *a, **kw: aiter([])
+
+ with (
+ patch(
+ "posthog.temporal.messaging.backfill_precalculated_person_properties_coordinator_workflow.compile_hogql_for_streaming",
+ side_effect=fake_compile,
+ ),
+ patch(
+ "posthog.temporal.messaging.backfill_precalculated_person_properties_coordinator_workflow.get_client",
+ return_value=_AsyncClientContextManager(mock_client),
+ ),
+ patch("temporalio.activity.heartbeat"),
+ ):
+ await get_person_id_ranges_page_activity(
+ PersonIdRangesPageInputs(team_id=1, batch_size=10, page_size=5, after_person_id="abc-123")
+ )
+
+ assert "node" in captured
+ node = captured["node"]
+ assert isinstance(node, ast.SelectQuery)
+ assert isinstance(node.where, ast.CompareOperation)
+ assert node.where.op == ast.CompareOperationOp.Gt
+
+ @pytest.mark.asyncio
+ async def test_where_is_and_with_both_filters(self):
+ captured: dict[str, object] = {}
+
+ async def fake_compile(node, *, team_id):
+ captured["node"] = node
+ return "SELECT 1 FORMAT JSONEachRow", {}
+
+ mock_client = Mock()
+ mock_client.stream_query_as_jsonl = lambda *a, **kw: aiter([])
+
+ with (
+ patch(
+ "posthog.temporal.messaging.backfill_precalculated_person_properties_coordinator_workflow.compile_hogql_for_streaming",
+ side_effect=fake_compile,
+ ),
+ patch(
+ "posthog.temporal.messaging.backfill_precalculated_person_properties_coordinator_workflow.get_client",
+ return_value=_AsyncClientContextManager(mock_client),
+ ),
+ patch("temporalio.activity.heartbeat"),
+ ):
+ await get_person_id_ranges_page_activity(
+ PersonIdRangesPageInputs(
+ team_id=1, batch_size=10, page_size=5, after_person_id="abc-123", person_id="def-456"
+ )
+ )
+
+ assert "node" in captured
+ node = captured["node"]
+ assert isinstance(node, ast.SelectQuery)
+ assert isinstance(node.where, ast.And)
+ assert len(node.where.exprs) == 2
+ ops = {e.op for e in node.where.exprs if isinstance(e, ast.CompareOperation)}
+ assert ast.CompareOperationOp.Gt in ops
+ assert ast.CompareOperationOp.Eq in ops
diff --git a/posthog/temporal/messaging/test/test_backfill_precalculated_person_properties_workflow.py b/posthog/temporal/messaging/test/test_backfill_precalculated_person_properties_workflow.py
index 932618447065..c1aa7081b577 100644
--- a/posthog/temporal/messaging/test/test_backfill_precalculated_person_properties_workflow.py
+++ b/posthog/temporal/messaging/test/test_backfill_precalculated_person_properties_workflow.py
@@ -6,10 +6,12 @@ from unittest.mock import Mock, patch
import temporalio.exceptions
from parameterized import parameterized
+from posthog.hogql import ast
+
from posthog.temporal.messaging.backfill_precalculated_person_properties_workflow import (
BackfillPrecalculatedPersonPropertiesInputs,
backfill_precalculated_person_properties_activity,
- build_person_properties_select_clause,
+ build_person_properties_select_exprs,
evaluate_combined_filters_sync,
flush_kafka_batch_async,
)
@@ -223,22 +225,38 @@ class TestBackfillPrecalculatedPersonPropertiesActivity:
# Basic verification that the filter was stored correctly
assert inputs.filter_storage_key == storage_key
- def test_build_person_properties_select_clause_parameterizes_property_keys(self):
+ def test_build_person_properties_select_exprs_keeps_keys_in_field_chain(self):
malicious_property = "email') FROM person WHERE team_id != %(team_id)s UNION ALL SELECT sleep(3) --"
- properties_clause, property_alias_mapping, property_query_params = build_person_properties_select_clause(
- [malicious_property]
- )
+ property_exprs, property_alias_mapping = build_person_properties_select_exprs([malicious_property])
- assert malicious_property not in properties_clause
- assert "team_id !=" not in properties_clause
- assert "%(property_key_0)s" in properties_clause
assert property_alias_mapping == {"prop_0": malicious_property}
- assert property_query_params == {"property_key_0": malicious_property}
+ assert len(property_exprs) == 1
+
+ alias_expr = property_exprs[0]
+ assert isinstance(alias_expr, ast.Alias)
+ assert alias_expr.alias == "prop_0"
+ # The malicious key must live inside an ast.Field chain — never inline as a SQL fragment.
+ field_expr = alias_expr.expr
+ assert isinstance(field_expr, ast.Field)
+ assert field_expr.chain == ["properties", malicious_property]
+
+ @pytest.mark.django_db
@pytest.mark.asyncio
async def test_activity_parameterizes_property_keys_in_clickhouse_query(self):
- malicious_property = "email') FROM person WHERE team_id != %(team_id)s UNION ALL SELECT sleep(3) --"
+ from asgiref.sync import sync_to_async
+
+ from posthog.models.organization import Organization
+ from posthog.models.team.team import Team
+
+ organization = await sync_to_async(Organization.objects.create)(name="Test Organization")
+ team = await sync_to_async(Team.objects.create)(name="Test Team", organization=organization)
+
+ # No '%' here on purpose: '%' keys take the full-properties fallback (see the dedicated test
+ # below). This key exercises the optimized per-property path and proves a SQL-fragment key
+ # stays inside the ast.Field chain rather than being concatenated into the query.
+ malicious_property = "email') FROM person WHERE team_id != 1 UNION ALL SELECT sleep(3) --"
filters = [
PersonPropertyFilter(
condition_hash="injection_condition",
@@ -247,11 +265,17 @@ class TestBackfillPrecalculatedPersonPropertiesActivity:
property_key=malicious_property,
),
]
- captured_query: dict[str, object] = {}
+ captured_ast: dict[str, object] = {}
+
+ original_prepare_and_print_ast = __import__(
+ "posthog.hogql.printer", fromlist=["prepare_and_print_ast"]
+ ).prepare_and_print_ast
+
+ def capturing_prepare_and_print_ast(node, context, dialect):
+ captured_ast["node"] = node
+ return original_prepare_and_print_ast(node, context, dialect)
async def stream_query_as_jsonl(query: str, query_parameters: dict[str, object] | None = None):
- captured_query["query"] = query
- captured_query["query_parameters"] = query_parameters
if False:
yield {} # type: ignore[unreachable]
@@ -259,7 +283,7 @@ class TestBackfillPrecalculatedPersonPropertiesActivity:
mock_client.stream_query_as_jsonl = stream_query_as_jsonl
inputs = BackfillPrecalculatedPersonPropertiesInputs(
- team_id=1,
+ team_id=team.id,
filter_storage_key="storage_key",
cohort_ids=[10],
batch_size=10,
@@ -276,6 +300,10 @@ class TestBackfillPrecalculatedPersonPropertiesActivity:
"posthog.temporal.messaging.backfill_precalculated_person_properties_workflow.get_client",
return_value=_AsyncClientContextManager(mock_client),
),
+ patch(
+ "posthog.temporal.messaging.hogql_compile.prepare_and_print_ast",
+ side_effect=capturing_prepare_and_print_ast,
+ ),
patch("posthog.temporal.messaging.backfill_precalculated_person_properties_workflow.get_producer"),
patch(
"posthog.temporal.messaging.backfill_precalculated_person_properties_workflow.Heartbeater",
@@ -286,19 +314,116 @@ class TestBackfillPrecalculatedPersonPropertiesActivity:
return_value=Mock(),
),
):
- result = await backfill_precalculated_person_properties_activity(inputs)
+ # The key may still produce an invalid identifier in the printer; the assertion that
+ # matters is that it reached the printer only inside an ast.Field chain, never as a raw
+ # SQL fragment.
+ try:
+ await backfill_precalculated_person_properties_activity(inputs)
+ except Exception:
+ pass
+
+ # The malicious key must only reach the printer wrapped in an ast.Field chain.
+ assert "node" in captured_ast, "compile_hogql_for_streaming was never called"
+ node = captured_ast["node"]
+ assert isinstance(node, ast.SelectQuery)
+ property_aliases = [
+ expr for expr in node.select if isinstance(expr, ast.Alias) and expr.alias.startswith("prop_")
+ ]
+ assert len(property_aliases) == 1
+ # The key lives inside an ast.Field chain — never concatenated into the SQL as a fragment.
+ prop_field = property_aliases[0].expr
+ assert isinstance(prop_field, ast.Field)
+ assert prop_field.chain == ["properties", malicious_property]
- assert result.persons_processed == 0
+ @pytest.mark.django_db
+ @pytest.mark.asyncio
+ async def test_activity_falls_back_to_full_properties_for_percent_keys(self):
+ from asgiref.sync import sync_to_async
+
+ from posthog.models.organization import Organization
+ from posthog.models.team.team import Team
- query = captured_query["query"]
- assert isinstance(query, str)
- assert malicious_property not in query
- assert "team_id !=" not in query
- assert "%(property_key_0)s" in query
+ organization = await sync_to_async(Organization.objects.create)(name="Test Organization")
+ team = await sync_to_async(Team.objects.create)(name="Test Team", organization=organization)
- query_parameters = captured_query["query_parameters"]
- assert isinstance(query_parameters, dict)
- assert query_parameters["property_key_0"] == malicious_property
+ # '%' is the one character HogQL refuses as an identifier, so the optimized per-property
+ # path can't be used. The backfill must fall back to selecting the full properties JSON
+ # rather than crashing the whole batch.
+ percent_property = "utm_%_source"
+ filters = [
+ PersonPropertyFilter(
+ condition_hash="percent_condition",
+ bytecode=["_H", 1, 29],
+ cohort_ids=[10],
+ property_key=percent_property,
+ ),
+ ]
+ captured_ast: dict[str, object] = {}
+
+ original_prepare_and_print_ast = __import__(
+ "posthog.hogql.printer", fromlist=["prepare_and_print_ast"]
+ ).prepare_and_print_ast
+
+ def capturing_prepare_and_print_ast(node, context, dialect):
+ captured_ast["node"] = node
+ return original_prepare_and_print_ast(node, context, dialect)
+
+ async def stream_query_as_jsonl(query: str, query_parameters: dict[str, object] | None = None):
+ if False:
+ yield {} # type: ignore[unreachable]
+
+ mock_client = Mock()
+ mock_client.stream_query_as_jsonl = stream_query_as_jsonl
+
+ inputs = BackfillPrecalculatedPersonPropertiesInputs(
+ team_id=team.id,
+ filter_storage_key="storage_key",
+ cohort_ids=[10],
+ batch_size=10,
+ start_person_id="00000000-0000-0000-0000-000000000000",
+ end_person_id="ffffffff-ffff-ffff-ffff-ffffffffffff",
+ )
+
+ with (
+ patch(
+ "posthog.temporal.messaging.backfill_precalculated_person_properties_workflow.get_filters_and_properties",
+ return_value=(filters, [percent_property], combine_filter_bytecodes(filters)),
+ ),
+ patch(
+ "posthog.temporal.messaging.backfill_precalculated_person_properties_workflow.get_client",
+ return_value=_AsyncClientContextManager(mock_client),
+ ),
+ patch(
+ "posthog.temporal.messaging.hogql_compile.prepare_and_print_ast",
+ side_effect=capturing_prepare_and_print_ast,
+ ),
+ patch("posthog.temporal.messaging.backfill_precalculated_person_properties_workflow.get_producer"),
+ patch(
+ "posthog.temporal.messaging.backfill_precalculated_person_properties_workflow.Heartbeater",
+ _NoopHeartbeater,
+ ),
+ patch(
+ "posthog.temporal.messaging.backfill_precalculated_person_properties_workflow.get_person_properties_backfill_success_metric",
+ return_value=Mock(),
+ ),
+ ):
+ await backfill_precalculated_person_properties_activity(inputs)
+
+ assert "node" in captured_ast, "compile_hogql_for_streaming was never called"
+ node = captured_ast["node"]
+ assert isinstance(node, ast.SelectQuery)
+
+ # No per-property accessors — the '%' key forced the full-properties fallback.
+ property_aliases = [
+ expr for expr in node.select if isinstance(expr, ast.Alias) and expr.alias.startswith("prop_")
+ ]
+ assert property_aliases == []
+
+ # The full ``properties`` JSON is selected instead, and the '%' key never appears as a field.
+ properties_fields = [
+ expr for expr in node.select if isinstance(expr, ast.Field) and expr.chain == ["properties"]
+ ]
+ assert len(properties_fields) == 1
class TestCombineFilterBytecodes:
diff --git a/posthog/temporal/messaging/test/test_hogql_compile.py b/posthog/temporal/messaging/test/test_hogql_compile.py
new file mode 100644
index 000000000000..1e209c881ee8
--- /dev/null
+++ b/posthog/temporal/messaging/test/test_hogql_compile.py
@@ -0,0 +1,65 @@
+import pytest
+from unittest.mock import patch
+
+from asgiref.sync import sync_to_async
+
+from posthog.hogql import ast
+
+from posthog.models.organization import Organization
+from posthog.models.team.team import Team
+from posthog.temporal.messaging.hogql_compile import compile_hogql_for_streaming
+
+
+class TestCompileHogqlForStreaming:
+ @pytest.mark.asyncio
+ async def test_bypasses_property_restrictions(self):
+ """restricted_properties=set() must skip get_restricted_properties_for_team."""
+ organization = await sync_to_async(Organization.objects.create)(name="Test Organization")
+ team = await sync_to_async(Team.objects.create)(name="Test Team", organization=organization)
+
+ node = ast.SelectQuery(
+ select=[ast.Alias(alias="person_id", expr=ast.Field(chain=["id"]))],
+ select_from=ast.JoinExpr(table=ast.Field(chain=["persons"])),
+ )
+
+ with patch(
+ "posthog.hogql.printer.utils.get_restricted_properties_for_team",
+ side_effect=AssertionError("get_restricted_properties_for_team must not be called"),
+ ):
+ sql, params = await compile_hogql_for_streaming(node, team_id=team.id)
+
+ assert "FORMAT JSONEachRow" in sql
+
+ @pytest.mark.asyncio
+ async def test_property_key_is_parameterized(self):
+ """Property keys must reach ClickHouse as parameters, not as unquoted SQL fragments.
+
+ When the ``persons`` lazy table is used, HogQL generates a subquery that references the
+ property via ``JSONExtractRaw(person.properties, %(hogql_val_N)s, ...)`` with the key as
+ a parameter, and also as a backtick-quoted column alias. The backtick quoting makes the
+ key inert as a SQL identifier — ClickHouse treats it as a column name, not executable code.
+ What must never happen is the key appearing as an unquoted SQL string or code fragment.
+ """
+ organization = await sync_to_async(Organization.objects.create)(name="Test Organization")
+ team = await sync_to_async(Team.objects.create)(name="Test Team", organization=organization)
+
+ prop_key = "email') UNION ALL SELECT sleep(3) --"
+ node = ast.SelectQuery(
+ select=[
+ ast.Alias(alias="person_id", expr=ast.Field(chain=["id"])),
+ ast.Alias(alias="prop_0", expr=ast.Field(chain=["properties", prop_key])),
+ ],
+ select_from=ast.JoinExpr(table=ast.Field(chain=["persons"])),
+ )
+
+ sql, params = await compile_hogql_for_streaming(node, team_id=team.id)
+
+ # The prop key must appear in the params dict (for the JSONExtractRaw call).
+ assert prop_key in params.values()
+ # The prop key must not appear as an unquoted SQL fragment — any occurrence must be
+ # inside backtick-quoted identifiers, which ClickHouse treats as column names.
+ assert f"'{prop_key}'" not in sql # not a SQL string literal
+ assert f'"{prop_key}"' not in sql # not a double-quoted identifier
+ assert "UNION ALL SELECT sleep" not in sql.split("`")[::2] # not outside backtick pairs
+ assert "FORMAT JSONEachRow" in sql