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.

perf(cohorts): optimize person properties backfill queries (#64306)

Gustavo H. Strassburger0ab69e483c0c
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 a01f9c2dd5dd..e410e7dcecfb 100644
--- a/posthog/temporal/messaging/backfill_precalculated_person_properties_coordinator_workflow.py
+++ b/posthog/temporal/messaging/backfill_precalculated_person_properties_coordinator_workflow.py
@@ -80,9 +80,18 @@ async def get_person_id_ranges_page_activity(inputs: PersonIdRangesPageInputs) -
)
)
+ # Enumerate person IDs straight off the raw ``person`` table with DISTINCT, not the ``persons``
+ # lazy table. We only need ID range *boundaries* here, not deduplicated / is_deleted-filtered
+ # rows -- the child workflow re-queries each range against ``raw_persons`` via ``argmax_select``
+ # with full argMax dedup and is_deleted filtering, so a deleted/duplicate ID slipping into a
+ # boundary just yields no child rows. Going through the ``persons`` lazy table would instead
+ # rewrite our ``id > cursor`` cursor filter into an unbounded ``id IN (subquery)`` with a full
+ # per-page dedup over the entire ID tail -- O(pages x tail). The direct ``SELECT DISTINCT id ...
+ # ORDER BY id LIMIT N`` reads the ``(team_id, id)`` primary key in order and stops after N IDs.
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"])),
+ distinct=True,
+ select_from=ast.JoinExpr(table=ast.Field(chain=["raw_persons"])),
where=_combine_where(where_exprs),
order_by=[ast.OrderExpr(expr=ast.Field(chain=["id"]), order="ASC")],
limit=ast.Constant(value=query_limit),
diff --git a/posthog/temporal/messaging/backfill_precalculated_person_properties_workflow.py b/posthog/temporal/messaging/backfill_precalculated_person_properties_workflow.py
index 6d6e4e8f5af5..b0388dc8a50d 100644
--- a/posthog/temporal/messaging/backfill_precalculated_person_properties_workflow.py
+++ b/posthog/temporal/messaging/backfill_precalculated_person_properties_workflow.py
@@ -14,6 +14,8 @@ import temporalio.exceptions
from structlog.contextvars import bind_contextvars
from posthog.hogql import ast
+from posthog.hogql.constants import HogQLQuerySettings
+from posthog.hogql.database.argmax import argmax_select
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
from posthog.kafka_client.client import _KafkaProducer
@@ -35,31 +37,31 @@ if TYPE_CHECKING:
LOGGER = get_logger(__name__)
MAX_OPTIMIZED_PROPERTIES = 100 # Safety limit to avoid query complexity issues
+# Alias for the full ``properties`` JSON column in the fallback query. It doubles as the format
+# discriminator for the row consumer: its presence in a row selects the fallback path. Producer and
+# consumer must use this same constant so they move together.
+FULL_PROPERTIES_KEY = "properties"
-def build_person_properties_select_exprs(
+
+def build_person_properties_select_fields(
person_properties: list[str],
-) -> tuple[list[ast.Alias], dict[str, str]]:
- """Build HogQL SELECT expressions for the requested person properties.
+) -> tuple[dict[str, list[str | int]], dict[str, str]]:
+ """Map each requested person property to an ``argmax_select`` field chain and its ``prop_N`` alias.
- 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 names come from cohort filters, so they must never be substring-concatenated into SQL.
+ Returning ``["properties", key]`` field chains keeps each key inside an ``ast.Field`` chain when
+ ``argmax_select`` wraps it in the per-person ``argMax`` aggregation: HogQL either rewrites to a
+ materialized column or routes the key through context parameters when emitting ``JSONExtract``.
"""
- selects: list[ast.Alias] = []
+ select_fields: dict[str, list[str | int]] = {}
alias_mapping: dict[str, str] = {}
for i, prop in enumerate(person_properties):
alias = f"prop_{i}"
- selects.append(
- ast.Alias(
- alias=alias,
- expr=ast.Field(chain=["properties", prop]),
- )
- )
+ select_fields[alias] = ["properties", prop]
alias_mapping[alias] = prop
- return selects, alias_mapping
+ return select_fields, alias_mapping
def format_cohort_ids_for_logging(cohort_ids: list[int]) -> str:
@@ -485,10 +487,10 @@ async def backfill_precalculated_person_properties_activity(
# Not in activity context (e.g., during tests), skip metrics
pass
- # 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.
+ # Build the per-property argmax_select fields — 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] = {}
- select_exprs: list[ast.Expr] = [ast.Alias(alias="person_id", expr=ast.Field(chain=["id"]))]
+ select_fields: dict[str, list[str | int]] = {}
# 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
@@ -497,12 +499,14 @@ async def backfill_precalculated_person_properties_activity(
has_identifier_unsafe_key = any("%" in prop for prop in person_properties)
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)
+ select_fields, property_alias_mapping = build_person_properties_select_fields(person_properties)
logger.info(f"Optimized query: fetching {len(person_properties)} specific properties via HogQL")
else:
- select_exprs.append(ast.Field(chain=["properties"]))
+ # Emitting the full ``properties`` column also flags this row as fallback-format: the
+ # consumer below keys on ``FULL_PROPERTIES_KEY`` to take the fallback path instead of
+ # reconstructing the dict from per-property ``prop_N`` columns.
+ select_fields[FULL_PROPERTIES_KEY] = [FULL_PROPERTIES_KEY]
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"
@@ -516,6 +520,10 @@ async def backfill_precalculated_person_properties_activity(
"Falling back to fetching all properties - could not determine specific properties needed"
)
+ # These predicates are set as a direct ``WHERE`` on the argMax aggregation below, so they
+ # apply *before* dedup. They must stay id-only (``id`` is the GROUP BY key, so filtering on it
+ # yields the same rows pre- and post-dedup). Adding a non-id predicate here (e.g. a
+ # ``properties.x`` filter) would match raw pre-dedup rows and quietly select the wrong persons.
where_exprs: list[ast.Expr] = [
ast.CompareOperation(
op=ast.CompareOperationOp.GtEq,
@@ -537,19 +545,30 @@ async def backfill_precalculated_person_properties_activity(
)
)
- 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.
+ # Deduplicate straight off the raw ``person`` table with ``argmax_select`` instead of the
+ # ``persons`` lazy table. ``argmax_select`` is the exact helper the ``persons`` table uses
+ # internally, so the semantics are identical: ``team_id`` scoping (added by the printer),
+ # latest-version-per-id dedup, ``is_deleted = 0`` filtering, and the
+ # ``argMax(created_at) < now() + 1 day`` clamp that drops future-dated persons. The win: going
+ # straight to ``raw_persons`` avoids the ``persons`` lazy table rewriting our ID-range filter
+ # into an ``id IN (subquery)`` that scans the range twice; the direct ``WHERE`` reads the
+ # ``(team_id, id)`` primary key once.
+ # Output column for the person UUID is ``id`` (argmax_select aliases the group field by name).
+ persons_query_ast = argmax_select(
+ table_name="raw_persons",
+ select_fields=select_fields,
+ group_fields=["id"],
+ argmax_field="version",
+ deleted_field="is_deleted",
+ timestamp_field_to_clamp="created_at",
)
+ persons_query_ast.where = ast.And(exprs=where_exprs)
+ persons_query_ast.order_by = [ast.OrderExpr(expr=ast.Field(chain=["id"]), order="ASC")]
+ # optimize_aggregation_in_order lets ClickHouse aggregate as it streams the primary key in
+ # order, so the GROUP BY + ORDER BY id never buffers the whole range. No explicit limit:
+ # compile_hogql_for_streaming uses LimitContext.COHORT_CALCULATION (LIMIT 1_000_000_000), and
+ # ID ranges are bounded by batch_size (default 1000 persons), so the cap is never reached.
+ persons_query_ast.settings = HogQLQuerySettings(optimize_aggregation_in_order=True)
persons_query, query_params = await compile_hogql_for_streaming(persons_query_ast, team_id=inputs.team_id)
@@ -583,26 +602,30 @@ async def backfill_precalculated_person_properties_activity(
"First row received from ClickHouse query",
team_id=inputs.team_id,
time_to_first_row_seconds=round(query_first_row_time - query_start_time, 2),
- first_person_id=str(row["person_id"]),
+ first_person_id=str(row["id"]),
)
first_row = False
batch_count += 1
- person_id = str(row["person_id"])
+ person_id = str(row["id"])
last_person_id = person_id # Track the last person ID for next cursor
# Handle both optimized (individual property columns) and fallback (full properties JSON) formats
- if person_properties and "properties" not in row:
+ if person_properties and FULL_PROPERTIES_KEY not in row:
# Optimized format: reconstruct properties dict from individual columns using alias mapping
reconstructed_properties = {}
for alias, original_prop_name in property_alias_mapping.items():
value = row.get(alias)
- if value: # Only include non-empty values
+ # The HogQL property extract maps a missing key to SQL NULL (-> None here),
+ # while a present falsey value (0, false, "") comes back as a non-null string.
+ # Keying on ``is not None`` keeps those present-but-falsey values instead of
+ # silently turning them into a missing key, matching the full-properties fallback.
+ if value is not None:
reconstructed_properties[original_prop_name] = value
parsed_properties = parse_person_properties(reconstructed_properties, person_id)
else:
# Fallback format: use full properties JSON
- parsed_properties = parse_person_properties(row.get("properties"), person_id)
+ parsed_properties = parse_person_properties(row.get(FULL_PROPERTIES_KEY), person_id)
# Evaluate all filters in a single VM call
person_filter_start = time.monotonic()
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 9bb52bd7a114..a23e9b5ca779 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
@@ -3,6 +3,8 @@ from types import TracebackType
import pytest
from unittest.mock import Mock, patch
+import temporalio.exceptions
+
from posthog.hogql import ast
from posthog.temporal.messaging.backfill_precalculated_person_properties_coordinator_workflow import (
@@ -97,6 +99,45 @@ 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)
+ @pytest.mark.asyncio
+ async def test_raises_when_child_workflow_fails(self):
+ inputs = BackfillPrecalculatedPersonPropertiesCoordinatorInputs(
+ team_id=123,
+ filter_storage_key="test-key",
+ cohort_ids=[1],
+ batch_size=100,
+ concurrent_workflows=2,
+ )
+
+ mock_workflow_info = Mock()
+ mock_workflow_info.workflow_id = "test-coordinator-failure"
+
+ page_result = PersonIdRangesPageResult(ranges=[("person1", "person100")], cursor=None)
+
+ workflow = BackfillPrecalculatedPersonPropertiesCoordinatorWorkflow()
+
+ class _FailingHandle:
+ def __await__(self):
+ async def _coro():
+ raise RuntimeError("child boom")
+
+ return _coro().__await__()
+
+ failing_handle = _FailingHandle()
+
+ async def mock_start_child_workflow(inputs_arg, logger, batch_num, start_id, end_id, handles):
+ handles.append(failing_handle)
+
+ with (
+ patch("temporalio.workflow.info", return_value=mock_workflow_info),
+ patch("temporalio.workflow.execute_activity", return_value=page_result),
+ patch.object(workflow, "_start_child_workflow_for_range", side_effect=mock_start_child_workflow),
+ patch("asyncio.wait", return_value=({failing_handle}, set())),
+ patch("temporalio.workflow.logger"),
+ ):
+ with pytest.raises(temporalio.exceptions.ApplicationError, match="child workflows failed"):
+ await workflow.run(inputs)
+
@pytest.mark.asyncio
async def test_handles_no_person_ranges(self):
inputs = BackfillPrecalculatedPersonPropertiesCoordinatorInputs(
@@ -244,6 +285,13 @@ class TestGetPersonIdRangesPageActivity:
node = captured["node"]
assert isinstance(node, ast.SelectQuery)
assert node.where is None
+ # Pagination must enumerate IDs off the raw ``person`` table with DISTINCT, not the
+ # ``persons`` lazy table -- otherwise ``id > cursor`` is wrapped in an unbounded
+ # ``id IN (...)`` subquery that GROUP BYs the whole ID tail on every page.
+ assert node.distinct is True
+ assert isinstance(node.select_from, ast.JoinExpr)
+ assert isinstance(node.select_from.table, ast.Field)
+ assert node.select_from.table.chain == ["raw_persons"]
@pytest.mark.asyncio
async def test_where_is_single_expr_with_only_after_person_id(self):
@@ -313,3 +361,79 @@ class TestGetPersonIdRangesPageActivity:
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
+
+
+class TestPageActivityRowConsumption:
+ """Stream real rows through get_person_id_ranges_page_activity.
+
+ The AST tests above stream zero rows, so the row-consumption code — which reads ``row["person_id"]``
+ and batches IDs into ranges — was never exercised. These feed real rows through it.
+ """
+
+ @pytest.mark.asyncio
+ async def test_rows_batched_into_ranges(self):
+ rows = [{"person_id": f"p{i}"} for i in range(1, 5)]
+ mock_client = Mock()
+ mock_client.stream_query_as_jsonl = lambda *a, **kw: aiter(rows)
+ module = "posthog.temporal.messaging.backfill_precalculated_person_properties_coordinator_workflow"
+ with (
+ patch(f"{module}.compile_hogql_for_streaming", side_effect=lambda node, *, team_id: ("SELECT 1", {})),
+ patch(f"{module}.get_client", return_value=_AsyncClientContextManager(mock_client)),
+ patch("temporalio.activity.heartbeat"),
+ ):
+ result = await get_person_id_ranges_page_activity(
+ PersonIdRangesPageInputs(team_id=1, batch_size=2, page_size=10, after_person_id=None)
+ )
+ assert result.ranges == [("p1", "p2"), ("p3", "p4")]
+ assert result.cursor is None # 4 rows < limit (20), no more data
+
+ @pytest.mark.asyncio
+ async def test_has_more_data_sets_cursor(self):
+ # batch_size=2, page_size=1 -> limit=2; a 3rd (limit+1) row signals more data and sets the cursor.
+ rows = [{"person_id": f"p{i}"} for i in range(1, 4)]
+ mock_client = Mock()
+ mock_client.stream_query_as_jsonl = lambda *a, **kw: aiter(rows)
+ module = "posthog.temporal.messaging.backfill_precalculated_person_properties_coordinator_workflow"
+ with (
+ patch(f"{module}.compile_hogql_for_streaming", side_effect=lambda node, *, team_id: ("SELECT 1", {})),
+ patch(f"{module}.get_client", return_value=_AsyncClientContextManager(mock_client)),
+ patch("temporalio.activity.heartbeat"),
+ ):
+ result = await get_person_id_ranges_page_activity(
+ PersonIdRangesPageInputs(team_id=1, batch_size=2, page_size=1, after_person_id=None)
+ )
+ assert result.ranges == [("p1", "p2")]
+ assert result.cursor == "p2" # last processed ID, used as the next page's after_person_id
+
+
+class TestDrainCompleted:
+ """The coordinator surfaces child failures via _drain_completed -> ApplicationError.
+
+ The workflow test patches asyncio.wait to (set(), set()), so the failure-counting branch was never
+ hit. This exercises _drain_completed directly with a failing handle.
+ """
+
+ @pytest.mark.asyncio
+ async def test_counts_completed_and_failed_and_removes_handles(self):
+ class _Handle:
+ def __init__(self, fail: bool) -> None:
+ self._fail = fail
+
+ def __await__(self):
+ async def _coro():
+ if self._fail:
+ raise RuntimeError("child boom")
+ return None
+
+ return _coro().__await__()
+
+ ok = _Handle(fail=False)
+ bad = _Handle(fail=True)
+ handles = [ok, bad]
+
+ workflow = BackfillPrecalculatedPersonPropertiesCoordinatorWorkflow()
+ completed, failed = await workflow._drain_completed({ok, bad}, handles, Mock()) # type: ignore[arg-type] # fake handles stand in for ChildWorkflowHandle
+
+ assert completed == 1
+ assert failed == 1
+ assert handles == [] # both drained handles removed from the in-flight list
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 c1aa7081b577..4dda4f9402b0 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
@@ -7,11 +7,12 @@ import temporalio.exceptions
from parameterized import parameterized
from posthog.hogql import ast
+from posthog.hogql.visitor import TraversingVisitor
from posthog.temporal.messaging.backfill_precalculated_person_properties_workflow import (
BackfillPrecalculatedPersonPropertiesInputs,
backfill_precalculated_person_properties_activity,
- build_person_properties_select_exprs,
+ build_person_properties_select_fields,
evaluate_combined_filters_sync,
flush_kafka_batch_async,
)
@@ -22,6 +23,22 @@ from common.hogvm.python.execute import execute_bytecode
from common.hogvm.python.operation import Operation
+class _FieldChainCollector(TraversingVisitor):
+ """Collect every ``ast.Field`` chain reachable from a node (e.g. inside argMax wrappers)."""
+
+ def __init__(self) -> None:
+ self.chains: list[list[str | int]] = []
+
+ def visit_field(self, node: ast.Field) -> None:
+ self.chains.append(list(node.chain))
+
+
+def _collect_field_chains(node: ast.Expr) -> list[list[str | int]]:
+ collector = _FieldChainCollector()
+ collector.visit(node)
+ return collector.chains
+
+
class _NoopHeartbeater:
details: tuple[str, ...]
@@ -56,6 +73,16 @@ class _AsyncClientContextManager:
return None
+def aiter(iterable):
+ """Wrap a sync iterable as an async iterator for mocking ``stream_query_as_jsonl``."""
+
+ async def _aiter():
+ for item in iterable:
+ yield item
+
+ return _aiter()
+
+
class TestFlushKafkaBatchAsync:
"""Tests for the flush_kafka_batch_async helper function."""
@@ -225,22 +252,16 @@ class TestBackfillPrecalculatedPersonPropertiesActivity:
# Basic verification that the filter was stored correctly
assert inputs.filter_storage_key == storage_key
- def test_build_person_properties_select_exprs_keeps_keys_in_field_chain(self):
+ def test_build_person_properties_select_fields_keeps_keys_in_field_chain(self):
malicious_property = "email') FROM person WHERE team_id != %(team_id)s UNION ALL SELECT sleep(3) --"
- property_exprs, property_alias_mapping = build_person_properties_select_exprs([malicious_property])
+ select_fields, property_alias_mapping = build_person_properties_select_fields([malicious_property])
assert property_alias_mapping == {"prop_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]
+ # The malicious key must live inside an argmax_select field chain — never inline as a SQL
+ # fragment. argmax_select wraps the chain in an ``ast.Field``, keeping the key parameterized.
+ assert select_fields == {"prop_0": ["properties", malicious_property]}
@pytest.mark.django_db
@pytest.mark.asyncio
@@ -326,14 +347,18 @@ class TestBackfillPrecalculatedPersonPropertiesActivity:
assert "node" in captured_ast, "compile_hogql_for_streaming was never called"
node = captured_ast["node"]
assert isinstance(node, ast.SelectQuery)
+ # The child queries raw_persons directly (via argmax_select), not the persons lazy table.
+ assert isinstance(node.select_from, ast.JoinExpr)
+ assert isinstance(node.select_from.table, ast.Field)
+ assert node.select_from.table.chain == ["raw_persons"]
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]
+ # The key lives inside an ast.Field chain (wrapped in argMax by argmax_select) — never
+ # concatenated into the SQL as a fragment.
+ prop_chains = _collect_field_chains(property_aliases[0])
+ assert any(chain[-2:] == ["properties", malicious_property] for chain in prop_chains)
@pytest.mark.django_db
@pytest.mark.asyncio
@@ -419,11 +444,136 @@ class TestBackfillPrecalculatedPersonPropertiesActivity:
]
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"]
+ # The full ``properties`` JSON is selected instead (argmax_select aliases it as "properties"),
+ # and the '%' key never appears as a field chain element anywhere in the query.
+ properties_aliases = [
+ expr for expr in node.select if isinstance(expr, ast.Alias) and expr.alias == "properties"
+ ]
+ assert len(properties_aliases) == 1
+ assert any(chain[-1:] == ["properties"] for chain in _collect_field_chains(properties_aliases[0]))
+ assert all(percent_property not in chain for chain in _collect_field_chains(node))
+
+
+class TestActivityRowConsumption:
+ """End-to-end row streaming through the child activity.
+
+ The other activity tests stream zero rows (``compile`` is patched and the client yields nothing),
+ so the row-consumption code — which now reads ``row["id"]`` and reconstructs properties from
+ ``prop_N`` columns — was never exercised. These feed real rows through it.
+ """
+
+ def _module(self, name: str) -> str:
+ return f"posthog.temporal.messaging.backfill_precalculated_person_properties_workflow.{name}"
+
+ async def _run_with_rows(self, person_properties, rows):
+ """Run the activity over ``rows``; return (result, captured_query_node, produced_messages, eval_globals)."""
+ filters = [
+ PersonPropertyFilter(
+ condition_hash="cond1",
+ bytecode=["_H", 1, Operation.TRUE],
+ cohort_ids=[10],
+ property_key=person_properties[0] if person_properties else None,
+ )
]
- assert len(properties_fields) == 1
+
+ captured: dict[str, object] = {}
+
+ async def compile_stub(node, *, team_id):
+ captured["node"] = node
+ return "SELECT 1", {}
+
+ eval_globals: list[dict] = []
+
+ def eval_stub(combined_bytecode, flts, hog_globals, person_id, detailed_logging=False):
+ eval_globals.append(hog_globals)
+ return {"cond1": True}
+
+ produced: list[dict] = []
+ producer = Mock()
+
+ def _produce(**kwargs):
+ produced.append(kwargs["data"])
+ return Mock()
+
+ producer.produce = _produce
+
+ mock_client = Mock()
+ mock_client.stream_query_as_jsonl = lambda *a, **kw: aiter(rows)
+
+ inputs = BackfillPrecalculatedPersonPropertiesInputs(
+ team_id=1,
+ 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(
+ self._module("get_filters_and_properties"),
+ return_value=(filters, list(person_properties), combine_filter_bytecodes(filters)),
+ ),
+ patch(self._module("compile_hogql_for_streaming"), side_effect=compile_stub),
+ patch(self._module("get_client"), return_value=_AsyncClientContextManager(mock_client)),
+ patch(self._module("evaluate_combined_filters_with_fallback_sync"), side_effect=eval_stub),
+ patch(self._module("get_producer"), return_value=producer),
+ patch(self._module("Heartbeater"), _NoopHeartbeater),
+ patch(self._module("get_person_properties_backfill_success_metric"), return_value=Mock()),
+ ):
+ result = await backfill_precalculated_person_properties_activity(inputs)
+
+ return result, captured.get("node"), produced, eval_globals
+
+ @pytest.mark.asyncio
+ async def test_optimized_rows_reconstruct_properties_and_produce(self):
+ # Optimized format: per-property prop_N columns, no "properties" key, person UUID under "id".
+ pid = "11111111-1111-1111-1111-111111111111"
+ rows = [{"id": pid, "prop_0": "[email protected]"}]
+
+ result, node, produced, eval_globals = await self._run_with_rows(["email"], rows)
+
+ # row["id"] is consumed and reconstruction maps prop_0 -> email.
+ assert result.persons_processed == 1
+ assert result.last_person_id == pid
+ assert eval_globals[0] == {"person": {"properties": {"email": "[email protected]"}}}
+ assert len(produced) == 1
+ assert produced[0]["person_id"] == pid
+ assert produced[0]["condition"] == "cond1"
+
+ # Locks the flat single-pass query shape the child optimization depends on: WHERE filters the
+ # raw_persons scan before the GROUP BY, with no id-IN-subquery indirection.
+ assert isinstance(node, ast.SelectQuery)
+ assert node.where is not None
+ assert node.group_by is not None
+ assert isinstance(node.select_from, ast.JoinExpr)
+ assert isinstance(node.select_from.table, ast.Field)
+ assert node.select_from.table.chain == ["raw_persons"]
+
+ @pytest.mark.asyncio
+ async def test_optimized_rows_keep_present_falsey_values_and_drop_missing(self):
+ # A missing key comes back as SQL NULL (None); a present falsey value comes back as a
+ # non-null string. The reconstruction must keep the falsey value and drop only the None,
+ # otherwise a present-but-falsey property silently becomes a missing key.
+ pid = "33333333-3333-3333-3333-333333333333"
+ rows = [{"id": pid, "prop_0": "", "prop_1": "0", "prop_2": "false", "prop_3": None}]
+
+ _result, _node, _produced, eval_globals = await self._run_with_rows(["empty", "zero", "flag", "absent"], rows)
+
+ assert eval_globals[0] == {"person": {"properties": {"empty": "", "zero": "0", "flag": "false"}}}
+
+ @pytest.mark.asyncio
+ async def test_fallback_rows_use_full_properties_json(self):
+ # Fallback format: a "properties" JSON column is present, so the consumer parses it directly.
+ pid = "22222222-2222-2222-2222-222222222222"
+ rows = [{"id": pid, "properties": '{"email": "[email protected]"}'}]
+
+ result, _node, produced, eval_globals = await self._run_with_rows([], rows)
+
+ assert result.persons_processed == 1
+ assert result.last_person_id == pid
+ assert eval_globals[0] == {"person": {"properties": {"email": "[email protected]"}}}
+ assert len(produced) == 1
class TestCombineFilterBytecodes: