:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(persons): build properties_at_time via HogQL instead of raw SQL (#91452)
Sandy Spicere5d173635cf2
diff --git a/posthog/api/person.py b/posthog/api/person.pyindex 43cc07b67a6d..4861758336c9 100644--- a/posthog/api/person.py+++ b/posthog/api/person.py@@ -1911,7 +1911,7 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):# Build point-in-time properties using the pre-fetched distinct_idstag_queries(product=ProductKey.PERSONS, feature=Feature.QUERY, team_id=self.team_id)point_in_time_properties = build_person_properties_at_time(- team_id=self.team_id,+ team=self.team,timestamp=timestamp,distinct_ids=distinct_ids_queried,include_set_once=include_set_once,diff --git a/posthog/clickhouse/backoff.py b/posthog/clickhouse/backoff.pynew file mode 100644index 000000000000..21ac64dbef79--- /dev/null+++ b/posthog/clickhouse/backoff.py@@ -0,0 +1,14 @@+from typing import Optional++from posthog.dataclasses import frozen+++@frozen+class ExponentialBackoff:+ delay: float+ max_delay: Optional[float] = None+ exp: float = 2.0++ def __call__(self, attempt: int) -> float:+ delay = self.delay * (attempt**self.exp)+ return min(delay, self.max_delay) if self.max_delay is not None else delaydiff --git a/posthog/clickhouse/client/limit.py b/posthog/clickhouse/client/limit.pyindex ac2bf3f622af..e2c88be7362d 100644--- a/posthog/clickhouse/client/limit.py+++ b/posthog/clickhouse/client/limit.py@@ -11,7 +11,7 @@ from celery import current_taskfrom prometheus_client import Counterfrom posthog import redis, settings-from posthog.clickhouse.cluster import ExponentialBackoff+from posthog.clickhouse.backoff import ExponentialBackofffrom posthog.clickhouse.query_tagging import Product, add_fallback_query_tags, get_query_tags, tag_queriesfrom posthog.constants import AvailableFeaturefrom posthog.dataclasses import frozen@@ -158,7 +158,7 @@ class RateLimit:max_concurrency = max(1, max_concurrency // 4)# p80 is below 1.714ms, therefore max retry is 1.714s- backoff = ExponentialBackoff(self.retry or 0.15, max_delay=1.714, exp=1.5)+ backoff = ExponentialBackoff(delay=self.retry or 0.15, max_delay=1.714, exp=1.5)count = 1wait_total = 0.0# Atomically check, remove expired if limit hit, and add the new taskdiff --git a/posthog/clickhouse/cluster.py b/posthog/clickhouse/cluster.pyindex d61d04d5270c..3145cde07cb9 100644--- a/posthog/clickhouse/cluster.py+++ b/posthog/clickhouse/cluster.py@@ -11,7 +11,7 @@ from concurrent.futures import ALL_COMPLETED, FIRST_EXCEPTION, Future, ThreadPoofrom copy import copyfrom dataclasses import dataclass, fieldfrom datetime import datetime-from typing import Any, ClassVar, Generic, Literal, NamedTuple, Optional, TypeVar+from typing import Any, ClassVar, Generic, Literal, NamedTuple, TypeVarfrom clickhouse_driver import Clientfrom clickhouse_driver.errors import ServerException@@ -699,17 +699,6 @@ class Query:return f"Query(query={query!r}, parameters={params_repr}, settings={self.settings!r})"-@dataclass-class ExponentialBackoff:- delay: float- max_delay: Optional[float] = None- exp: float = 2.0-- def __call__(self, attempt: int) -> float:- delay = self.delay * (attempt**self.exp)- return min(delay, self.max_delay) if self.max_delay is not None else delay--@dataclassclass RetryPolicy:max_attempts: intdiff --git a/posthog/clickhouse/test/test_schema.py b/posthog/clickhouse/test/test_schema.pyindex d9c38fec0416..a79bc7f4251a 100644--- a/posthog/clickhouse/test/test_schema.py+++ b/posthog/clickhouse/test/test_schema.py@@ -96,6 +96,7 @@ def test_events_json_table_uses_dedicated_kafka_consumer_group(settings):({"ordinary": "discard"}, None),],)[email protected]("clickhouse_database")def test_person_property_mutation_projection(properties: dict[str, object], expected: dict[str, object] | None) -> None:select = PERSON_PROPERTY_MUTATION_LOG_MV_SQL().split("AS SELECT", 1)[1]rows = sync_execute(@@ -130,6 +131,7 @@ def test_person_property_mutation_projection(properties: dict[str, object], expe],ids=["aligned", "backdated", "future", "bucket_rounding", "subsecond", "floor", "mixed", "negative", "clamp"],)[email protected]("clickhouse_database")def test_logs_volume_bucket_retention_covers_raw_expiry(timestamp_offset: timedelta,observed_delay: timedelta,diff --git a/posthog/clickhouse/test/test_session_replay_mode.py b/posthog/clickhouse/test/test_session_replay_mode.pyindex ea76e5c1240f..655067c41984 100644--- a/posthog/clickhouse/test/test_session_replay_mode.py+++ b/posthog/clickhouse/test/test_session_replay_mode.py@@ -16,6 +16,7 @@ from posthog.session_recordings.sql.session_replay_event_sql import (@pytest.mark.parametrize("mv_sql", [SESSION_REPLAY_EVENTS_TABLE_MV_SQL, SESSION_REPLAY_EVENTS_WS_MV_SQL])[email protected]("clickhouse_database")def test_replay_metadata_reads_old_parts_and_classified_blocks(mv_sql: Callable[..., str]) -> None:suffix = uuid4().hexsource = f"replay_mode_source_{suffix}"diff --git a/posthog/conftest.py b/posthog/conftest.pyindex 3f2bca6a0163..8d3b968e8156 100644--- a/posthog/conftest.py+++ b/posthog/conftest.py@@ -36,6 +36,20 @@ from posthog.test import flush_lock_guardlogger = logging.getLogger(__name__)[email protected](scope="package")+def clickhouse_database() -> None:+ # SQL-only tests need a database without the Postgres setup tied to django_db_setup.+ Database(+ settings.CLICKHOUSE_DATABASE,+ db_url=settings.CLICKHOUSE_HTTP_URL,+ username=settings.CLICKHOUSE_USER,+ password=settings.CLICKHOUSE_PASSWORD,+ cluster=settings.CLICKHOUSE_CLUSTER,+ verify_ssl_cert=settings.CLICKHOUSE_VERIFY,+ trust_env=False,+ ).create_database()++def create_clickhouse_tables():# Create clickhouse tables to default before running test# Mostly so that test runs locally work correctlydiff --git a/posthog/dags/common/resources.py b/posthog/dags/common/resources.pyindex 2a02c152fefc..194ed4444d33 100644--- a/posthog/dags/common/resources.py+++ b/posthog/dags/common/resources.py@@ -15,6 +15,7 @@ import posthoganalyticsfrom clickhouse_driver.errors import Error, ErrorCodesfrom posthog import settings+from posthog.clickhouse.backoff import ExponentialBackofffrom posthog.clickhouse.client.connection import (ClickHouseCredentials,ClickHouseUser,@@ -22,7 +23,7 @@ from posthog.clickhouse.client.connection import (get_clickhouse_creds,is_file_backed_user,)-from posthog.clickhouse.cluster import ClickhouseCluster, ExponentialBackoff, RetryPolicy, get_cluster+from posthog.clickhouse.cluster import ClickhouseCluster, RetryPolicy, get_clusterfrom posthog.kafka_client.client import _KafkaProducerfrom posthog.kafka_client.profiles import KafkaClusterProfilefrom posthog.kafka_client.routing import get_producer@@ -105,7 +106,7 @@ class ClickhouseClusterResource(dagster.ConfigurableResource):client_settings=self.client_settings,retry_policy=RetryPolicy(max_attempts=self.retry_max_attempts,- delay=ExponentialBackoff(20, max_delay=60),+ delay=ExponentialBackoff(delay=20, max_delay=60),exceptions=_is_retryable_clickhouse_exception,),)@@ -136,7 +137,7 @@ class OpsClickhouseClusterResource(dagster.ConfigurableResource):},retry_policy=RetryPolicy(max_attempts=2,- delay=ExponentialBackoff(20, max_delay=60),+ delay=ExponentialBackoff(delay=20, max_delay=60),exceptions=_is_retryable_clickhouse_exception,),)@@ -180,7 +181,7 @@ class BackupsClickhouseClusterResource(dagster.ConfigurableResource):client_settings=self.client_settings,retry_policy=RetryPolicy(max_attempts=8,- delay=ExponentialBackoff(20, max_delay=60),+ delay=ExponentialBackoff(delay=20, max_delay=60),exceptions=_is_retryable_clickhouse_exception,),connection_overrides=_dedicated_user_connection_overrides(creds),@@ -218,7 +219,7 @@ class PartBreakerClickhouseClusterResource(dagster.ConfigurableResource):client_settings=self.client_settings,retry_policy=RetryPolicy(max_attempts=8,- delay=ExponentialBackoff(20, max_delay=60),+ delay=ExponentialBackoff(delay=20, max_delay=60),exceptions=_is_retryable_clickhouse_exception,),connection_overrides=_dedicated_user_connection_overrides(creds),diff --git a/posthog/hogql/transforms/test/test_property_types.py b/posthog/hogql/transforms/test/test_property_types.pyindex 44b580423bc0..b05b231c54ad 100644--- a/posthog/hogql/transforms/test/test_property_types.py+++ b/posthog/hogql/transforms/test/test_property_types.py@@ -80,6 +80,7 @@ def _normalize_snapshot_sql(sql: str) -> str:@override_settings(CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA=True)[email protected]("clickhouse_database")class TestNewEventsSchemaArraySubcolumns(SimpleTestCase):def _context(self, use_new_events_schema: bool | None = None) -> HogQLContext:team = Team(id=1, project_id=1)diff --git a/posthog/models/person/__init__.py b/posthog/models/person/__init__.pyindex dd9b0faeef6d..310f22b7c1ad 100644--- a/posthog/models/person/__init__.py+++ b/posthog/models/person/__init__.py@@ -1,10 +1,8 @@from .person import Person, PersonDistinctId, PersonOverride, PersonOverrideMapping-from .point_in_time_properties import build_person_properties_at_time__all__ = ["Person","PersonDistinctId","PersonOverride","PersonOverrideMapping",- "build_person_properties_at_time",]diff --git a/posthog/models/person/point_in_time_properties.py b/posthog/models/person/point_in_time_properties.pyindex 19c3e531c24c..e4ff41222fda 100644--- a/posthog/models/person/point_in_time_properties.py+++ b/posthog/models/person/point_in_time_properties.py@@ -7,13 +7,18 @@ chronologically."""import json-from datetime import UTC, datetime, timedelta+from datetime import datetime, timedeltafrom typing import TYPE_CHECKING, Any, Optional-from posthog.clickhouse.client import sync_execute+from posthog.hogql import ast+from posthog.hogql.constants import HogQLGlobalSettings+from posthog.hogql.context import HogQLContext+from posthog.hogql.parser import parse_expr+from posthog.hogql.query import execute_hogql_queryif TYPE_CHECKING:from posthog.models.person import Person+ from posthog.models.team import TeamDEFAULT_PROPERTY_ROW_LIMIT = 100_000@@ -100,10 +105,7 @@ def get_distinct_ids_for_person_identifier(return distinct_ids-def _validate_build_inputs(team_id: int, timestamp: datetime, distinct_ids: list[str], row_limit: int) -> None:- if not isinstance(team_id, int) or team_id <= 0:- raise ValueError("team_id must be a positive integer")-+def _validate_build_inputs(timestamp: datetime, distinct_ids: list[str], row_limit: int) -> None:if not isinstance(timestamp, datetime):raise ValueError("timestamp must be a datetime object")@@ -117,34 +119,6 @@ def _validate_build_inputs(team_id: int, timestamp: datetime, distinct_ids: listraise ValueError("row_limit must be a positive integer")-def _build_property_query(include_set_once: bool, row_limit: int) -> str:- if include_set_once:- event_filter = "event IN ('$set', '$set_once') OR JSONHas(properties, '$set')"- else:- event_filter = "event = '$set' OR JSONHas(properties, '$set')"-- # Pulls every property-update event in the window. Existence is established- # upstream by get_person_and_distinct_ids_for_identifier (Postgres row);- # ``existed`` here means "had property activity in the scan window", which- # the property row count answers directly. We extract $set / $set_once raw- # JSON instead of shipping the full properties blob, and the timestamp- # window + LIMIT keeps ClickHouse from walking dead partitions.- return f"""- SELECT- JSONExtractRaw(properties, '$set') AS set_json,- JSONExtractRaw(properties, '$set_once') AS set_once_json,- event AS event_name- FROM events- WHERE team_id = %(team_id)s- AND distinct_id IN %(distinct_ids)s- AND timestamp >= %(lower_bound)s- AND timestamp <= %(upper_bound)s- AND ({event_filter})- ORDER BY timestamp ASC- LIMIT {int(row_limit)}- """--def _parse_property_json(raw: Any) -> Optional[dict]:try:parsed = json.loads(raw)@@ -176,7 +150,7 @@ def _reconstruct_properties(rows: list, include_set_once: bool) -> dict[str, Anydef build_person_properties_at_time(- team_id: int,+ team: "Team",timestamp: datetime,distinct_ids: list[str],include_set_once: bool = False,@@ -188,7 +162,7 @@ def build_person_properties_at_time(Build person properties at a specific point in time from ClickHouse events.Args:- team_id: The team ID to filter events by+ team: The team whose events are scannedtimestamp: The point in time to build properties at (events after this are ignored)distinct_ids: List of distinct_ids to query for person propertiesinclude_set_once: If True, also handles $set_once operations (default: False)@@ -201,25 +175,56 @@ def build_person_properties_at_time(Raises:ValueError: If parameters are invalid- Exception: If ClickHouse query fails"""- _validate_build_inputs(team_id, timestamp, distinct_ids, row_limit)+ _validate_build_inputs(timestamp, distinct_ids, row_limit)- query = _build_property_query(include_set_once, row_limit)+ if include_set_once:+ event_filter = "event IN ('$set', '$set_once') OR JSONHas(properties, '$set')"+ else:+ event_filter = "event = '$set' OR JSONHas(properties, '$set')"# Use provided lower_bound or default to timestamp - 2 yearseffective_lower_bound = lower_bound if lower_bound is not None else timestamp - _HISTORY_SCAN_FLOOR- params = {- "team_id": team_id,- "distinct_ids": distinct_ids,- "lower_bound": effective_lower_bound.astimezone(UTC).strftime("%Y-%m-%d %H:%M:%S"),- "upper_bound": timestamp.astimezone(UTC).strftime("%Y-%m-%d %H:%M:%S"),- }-- try:- rows = sync_execute(query, params, settings={"max_execution_time": timeout})- except Exception as e:- raise Exception(f"Failed to query ClickHouse events: {str(e)}") from e-- return _reconstruct_properties(rows, include_set_once)+ # Pulls every property-update event in the window. Existence is established+ # upstream by get_person_and_distinct_ids_for_identifier (Postgres row);+ # ``existed`` here means "had property activity in the scan window", which+ # the property row count answers directly. We extract $set / $set_once raw+ # JSON instead of shipping the full properties blob, and the timestamp+ # window + LIMIT keeps ClickHouse from walking dead partitions.+ response = execute_hogql_query(+ """+ SELECT+ JSONExtractRaw(properties, '$set') AS set_json,+ JSONExtractRaw(properties, '$set_once') AS set_once_json,+ event AS event_name+ FROM events+ WHERE distinct_id IN {distinct_ids}+ AND timestamp >= {lower_bound}+ AND timestamp <= {upper_bound}+ AND ({event_filter})+ ORDER BY timestamp ASC+ LIMIT {row_limit}+ """,+ placeholders={+ "distinct_ids": ast.Constant(value=distinct_ids),+ "lower_bound": ast.Constant(value=effective_lower_bound),+ "upper_bound": ast.Constant(value=timestamp),+ "event_filter": parse_expr(event_filter),+ "row_limit": ast.Constant(value=row_limit),+ },+ team=team,+ query_type="person_properties_at_time",+ settings=HogQLGlobalSettings(max_execution_time=timeout),+ # row_limit is the only LIMIT this scan wants. The default context caps a top-level LIMIT at+ # MAX_SELECT_RETURNED_ROWS, which would silently truncate the default row_limit, and every+ # limit context with a larger cap also overrides max_execution_time.+ #+ # The scan must not stop at the plan's events retention floor. Ingestion applies every $set to the+ # person profile regardless of retention, so a floored scan rebuilds a profile that never existed and+ # drops every property set before the window. The scan reconstructs person state. It does not expose+ # events past the floor.+ context=HogQLContext(team_id=team.pk, limit_top_select=False, apply_events_retention_floor=False),+ )++ return _reconstruct_properties(response.results, include_set_once)diff --git a/posthog/models/person/test/test_point_in_time_properties.py b/posthog/models/person/test/test_point_in_time_properties.pyindex a685f71a60d1..baae77297c32 100644--- a/posthog/models/person/test/test_point_in_time_properties.py+++ b/posthog/models/person/test/test_point_in_time_properties.py@@ -11,10 +11,13 @@ from unittest.mock import patchfrom django.test import SimpleTestCase+from posthog.schema import HogQLQueryResponse+from posthog.models.person.point_in_time_properties import (build_person_properties_at_time,get_person_and_distinct_ids_for_identifier,)+from posthog.models.team import Teamfrom posthog.personhog_client.fake_client import fake_personhog_client, get_active_fakefrom posthog.test.persons import create_person@@ -33,176 +36,144 @@ def _prop_row(class TestPointInTimeProperties(SimpleTestCase):+ def setUp(self) -> None:+ self.team = Team(id=1)+def test_build_person_properties_at_time_validation(self):timestamp = datetime(2023, 1, 1, 12, 0, 0, tzinfo=UTC)- # Test invalid team_id- with self.assertRaises(ValueError) as cm:- build_person_properties_at_time(0, timestamp, ["user123"])- self.assertIn("team_id must be a positive integer", str(cm.exception))-- with self.assertRaises(ValueError) as cm:- build_person_properties_at_time(-1, timestamp, ["user123"])- self.assertIn("team_id must be a positive integer", str(cm.exception))-# Test invalid timestampwith self.assertRaises(ValueError) as cm:- build_person_properties_at_time(1, cast(datetime, "2023-01-01"), ["user123"])+ build_person_properties_at_time(self.team, cast(datetime, "2023-01-01"), ["user123"])self.assertIn("timestamp must be a datetime object", str(cm.exception))# Test invalid distinct_ids (empty list)with self.assertRaises(ValueError) as cm:- build_person_properties_at_time(1, timestamp, [])+ build_person_properties_at_time(self.team, timestamp, [])self.assertIn("distinct_ids must be a non-empty list", str(cm.exception))# Test invalid distinct_ids (not a list)with self.assertRaises(ValueError) as cm:- build_person_properties_at_time(1, timestamp, "not_a_list") # type: ignore[arg-type]+ build_person_properties_at_time(self.team, timestamp, "not_a_list") # type: ignore[arg-type]self.assertIn("distinct_ids must be a non-empty list", str(cm.exception))# Test invalid distinct_ids (contains empty string)with self.assertRaises(ValueError) as cm:- build_person_properties_at_time(1, timestamp, ["user123", ""])+ build_person_properties_at_time(self.team, timestamp, ["user123", ""])self.assertIn("All distinct_ids must be non-empty strings", str(cm.exception))# Invalid row_limitwith self.assertRaises(ValueError) as cm:- build_person_properties_at_time(1, timestamp, ["user123"], row_limit=0)+ build_person_properties_at_time(self.team, timestamp, ["user123"], row_limit=0)self.assertIn("row_limit must be a positive integer", str(cm.exception))- @patch("posthog.models.person.point_in_time_properties.sync_execute")- def test_build_person_properties_at_time_empty_result(self, mock_sync_execute):+ @patch("posthog.models.person.point_in_time_properties.execute_hogql_query")+ def test_build_person_properties_at_time_empty_result(self, mock_execute_hogql_query):"""Zero rows means the person had no property activity at or before timestamp."""- mock_sync_execute.return_value = []+ mock_execute_hogql_query.return_value = HogQLQueryResponse(results=[])timestamp = datetime(2023, 1, 1, 12, 0, 0, tzinfo=UTC)- properties = build_person_properties_at_time(1, timestamp, ["user123"])+ properties = build_person_properties_at_time(self.team, timestamp, ["user123"])self.assertEqual(properties, {})- mock_sync_execute.assert_called_once()-- @patch("posthog.models.person.point_in_time_properties.sync_execute")- def test_build_person_properties_at_time_single_set(self, mock_sync_execute):- mock_sync_execute.return_value = [- _prop_row(set_dict={"name": "John Doe", "email": "[email protected]"}, event="$set"),- ]+ mock_execute_hogql_query.assert_called_once()++ @patch("posthog.models.person.point_in_time_properties.execute_hogql_query")+ def test_build_person_properties_at_time_single_set(self, mock_execute_hogql_query):+ mock_execute_hogql_query.return_value = HogQLQueryResponse(+ results=[+ _prop_row(set_dict={"name": "John Doe", "email": "[email protected]"}, event="$set"),+ ]+ )timestamp = datetime(2023, 1, 1, 12, 0, 0, tzinfo=UTC)- properties = build_person_properties_at_time(1, timestamp, ["user123"])+ properties = build_person_properties_at_time(self.team, timestamp, ["user123"])self.assertEqual(properties, {"name": "John Doe", "email": "[email protected]"})- @patch("posthog.models.person.point_in_time_properties.sync_execute")- def test_build_person_properties_at_time_multiple_sets(self, mock_sync_execute):- mock_sync_execute.return_value = [- _prop_row(set_dict={"name": "John", "age": 25}, event="$set"),- _prop_row(set_dict={"name": "John Doe", "location": "SF"}, event="$pageview"),- _prop_row(set_dict={"age": 26}, event="$set"),- ]+ @patch("posthog.models.person.point_in_time_properties.execute_hogql_query")+ def test_build_person_properties_at_time_multiple_sets(self, mock_execute_hogql_query):+ mock_execute_hogql_query.return_value = HogQLQueryResponse(+ results=[+ _prop_row(set_dict={"name": "John", "age": 25}, event="$set"),+ _prop_row(set_dict={"name": "John Doe", "location": "SF"}, event="$pageview"),+ _prop_row(set_dict={"age": 26}, event="$set"),+ ]+ )timestamp = datetime(2023, 1, 1, 12, 0, 0, tzinfo=UTC)- properties = build_person_properties_at_time(1, timestamp, ["user123"])+ properties = build_person_properties_at_time(self.team, timestamp, ["user123"])self.assertEqual(properties, {"name": "John Doe", "age": 26, "location": "SF"})- @patch("posthog.models.person.point_in_time_properties.sync_execute")- def test_build_person_properties_at_time_malformed_json(self, mock_sync_execute):- mock_sync_execute.return_value = [- ("invalid json", "", "$set"),- _prop_row(set_dict={"name": "John"}, event="$set"),- ("", "", "$pageview"),- ]+ @patch("posthog.models.person.point_in_time_properties.execute_hogql_query")+ def test_build_person_properties_at_time_malformed_json(self, mock_execute_hogql_query):+ mock_execute_hogql_query.return_value = HogQLQueryResponse(+ results=[+ ("invalid json", "", "$set"),+ _prop_row(set_dict={"name": "John"}, event="$set"),+ ("", "", "$pageview"),+ ]+ )timestamp = datetime(2023, 1, 1, 12, 0, 0, tzinfo=UTC)- properties = build_person_properties_at_time(1, timestamp, ["user123"])+ properties = build_person_properties_at_time(self.team, timestamp, ["user123"])self.assertEqual(properties, {"name": "John"})- @patch("posthog.models.person.point_in_time_properties.sync_execute")- def test_build_person_properties_at_time_clickhouse_error(self, mock_sync_execute):- mock_sync_execute.side_effect = Exception("ClickHouse connection failed")-- timestamp = datetime(2023, 1, 1, 12, 0, 0, tzinfo=UTC)-- with self.assertRaises(Exception) as cm:- build_person_properties_at_time(1, timestamp, ["user123"])-- self.assertIn("Failed to query ClickHouse events", str(cm.exception))-- @patch("posthog.models.person.point_in_time_properties.sync_execute")- def test_row_limit_is_passed_to_query(self, mock_sync_execute):- mock_sync_execute.return_value = []-- timestamp = datetime(2024, 6, 1, 12, 0, 0, tzinfo=UTC)-- build_person_properties_at_time(1, timestamp, ["user123"], row_limit=500)-- mock_sync_execute.assert_called_once()- args, _ = mock_sync_execute.call_args- query, params = args[0], args[1]-- self.assertIn("LIMIT 500", query)- self.assertEqual(params["upper_bound"], timestamp.astimezone(UTC).strftime("%Y-%m-%d %H:%M:%S"))-class TestPointInTimePropertiesWithSetOnce(SimpleTestCase):- @patch("posthog.models.person.point_in_time_properties.sync_execute")- def test_build_person_properties_with_set_once_basic(self, mock_sync_execute):+ def setUp(self) -> None:+ self.team = Team(id=1)++ @patch("posthog.models.person.point_in_time_properties.execute_hogql_query")+ def test_build_person_properties_with_set_once_basic(self, mock_execute_hogql_query):"""$set_once only sets properties that don't exist yet."""- mock_sync_execute.return_value = [- _prop_row(set_dict={"name": "John"}, event="$set"),- _prop_row(set_once_dict={"name": "Jane", "email": "[email protected]"}, event="$set_once"),- ]+ mock_execute_hogql_query.return_value = HogQLQueryResponse(+ results=[+ _prop_row(set_dict={"name": "John"}, event="$set"),+ _prop_row(set_once_dict={"name": "Jane", "email": "[email protected]"}, event="$set_once"),+ ]+ )timestamp = datetime(2023, 1, 1, 12, 0, 0, tzinfo=UTC)- properties = build_person_properties_at_time(1, timestamp, ["user123"], include_set_once=True)+ properties = build_person_properties_at_time(self.team, timestamp, ["user123"], include_set_once=True)# name stays as "John" (not overwritten by $set_once); email is set by $set_once since it didn't existself.assertEqual(properties, {"name": "John", "email": "[email protected]"})- @patch("posthog.models.person.point_in_time_properties.sync_execute")- def test_build_person_properties_with_set_once_order_matters(self, mock_sync_execute):- mock_sync_execute.return_value = [- _prop_row(set_once_dict={"name": "Jane", "email": "[email protected]"}, event="$set_once"),- _prop_row(set_dict={"name": "John"}, event="$set"),- ]+ @patch("posthog.models.person.point_in_time_properties.execute_hogql_query")+ def test_build_person_properties_with_set_once_order_matters(self, mock_execute_hogql_query):+ mock_execute_hogql_query.return_value = HogQLQueryResponse(+ results=[+ _prop_row(set_once_dict={"name": "Jane", "email": "[email protected]"}, event="$set_once"),+ _prop_row(set_dict={"name": "John"}, event="$set"),+ ]+ )timestamp = datetime(2023, 1, 1, 12, 0, 0, tzinfo=UTC)- properties = build_person_properties_at_time(1, timestamp, ["user123"], include_set_once=True)+ properties = build_person_properties_at_time(self.team, timestamp, ["user123"], include_set_once=True)# $set_once sets name first, then $set overwrites itself.assertEqual(properties, {"name": "John", "email": "[email protected]"})- @patch("posthog.models.person.point_in_time_properties.sync_execute")- def test_build_person_properties_with_set_once_multiple_set_once(self, mock_sync_execute):- mock_sync_execute.return_value = [- _prop_row(set_once_dict={"name": "First", "email": "[email protected]"}, event="$set_once"),- _prop_row(set_once_dict={"name": "Second", "location": "SF"}, event="$set_once"),- ]+ @patch("posthog.models.person.point_in_time_properties.execute_hogql_query")+ def test_build_person_properties_with_set_once_multiple_set_once(self, mock_execute_hogql_query):+ mock_execute_hogql_query.return_value = HogQLQueryResponse(+ results=[+ _prop_row(set_once_dict={"name": "First", "email": "[email protected]"}, event="$set_once"),+ _prop_row(set_once_dict={"name": "Second", "location": "SF"}, event="$set_once"),+ ]+ )timestamp = datetime(2023, 1, 1, 12, 0, 0, tzinfo=UTC)- properties = build_person_properties_at_time(1, timestamp, ["user123"], include_set_once=True)+ properties = build_person_properties_at_time(self.team, timestamp, ["user123"], include_set_once=True)self.assertEqual(properties,{"name": "First", "email": "[email protected]", "location": "SF"},)- @patch("posthog.models.person.point_in_time_properties.sync_execute")- def test_build_person_properties_at_time_with_distinct_ids_direct(self, mock_sync_execute):- mock_sync_execute.return_value = [- _prop_row(set_dict={"name": "Jane Doe", "email": "[email protected]"}, event="$set"),- ]-- timestamp = datetime(2023, 1, 1, 12, 0, 0, tzinfo=UTC)- properties = build_person_properties_at_time(1, timestamp, distinct_ids=["user123", "user456", "user789"])-- self.assertEqual(properties, {"name": "Jane Doe", "email": "[email protected]"})-- mock_sync_execute.assert_called_once()- call_args = mock_sync_execute.call_args- self.assertEqual(call_args[0][1]["distinct_ids"], ["user123", "user456", "user789"])-class TestGetPersonAndDistinctIdsForIdentifierValidation(SimpleTestCase):def test_both_params_raises(self):diff --git a/posthog/models/person/test/test_point_in_time_properties_integration.py b/posthog/models/person/test/test_point_in_time_properties_integration.pyindex 4d26ef12375a..b09b1d18aa31 100644--- a/posthog/models/person/test/test_point_in_time_properties_integration.py+++ b/posthog/models/person/test/test_point_in_time_properties_integration.py@@ -10,7 +10,9 @@ from datetime import UTC, datetime, timedeltafrom posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events-from posthog.models.person.point_in_time_properties import build_person_properties_at_time+from django.test import override_settings++from posthog.models.person.point_in_time_properties import DEFAULT_PROPERTY_ROW_LIMIT, build_person_properties_at_timeclass TestPointInTimePropertiesClickhouse(ClickhouseTestMixin, BaseTest):@@ -41,7 +43,7 @@ class TestPointInTimePropertiesClickhouse(ClickhouseTestMixin, BaseTest):flush_persons_and_events()properties = build_person_properties_at_time(- self.team.pk,+ self.team,upper_bound,[distinct_id],)@@ -69,7 +71,7 @@ class TestPointInTimePropertiesClickhouse(ClickhouseTestMixin, BaseTest):flush_persons_and_events()properties = build_person_properties_at_time(- self.team.pk,+ self.team,upper_bound,[distinct_id],include_set_once=True,@@ -126,7 +128,7 @@ class TestPointInTimePropertiesClickhouse(ClickhouseTestMixin, BaseTest):flush_persons_and_events()properties = build_person_properties_at_time(- self.team.pk,+ self.team,upper_bound,[distinct_id],include_set_once=True,@@ -160,7 +162,7 @@ class TestPointInTimePropertiesClickhouse(ClickhouseTestMixin, BaseTest):flush_persons_and_events()properties = build_person_properties_at_time(- self.team.pk,+ self.team,upper_bound,[distinct_id],)@@ -171,7 +173,7 @@ class TestPointInTimePropertiesClickhouse(ClickhouseTestMixin, BaseTest):upper_bound = datetime(2024, 6, 1, 12, 0, 0, tzinfo=UTC)properties = build_person_properties_at_time(- self.team.pk,+ self.team,upper_bound,["user-clickhouse-nonexistent"],)@@ -206,7 +208,7 @@ class TestPointInTimePropertiesClickhouse(ClickhouseTestMixin, BaseTest):flush_persons_and_events()properties = build_person_properties_at_time(- self.team.pk,+ self.team,upper_bound,[distinct_id],row_limit=row_limit,@@ -230,10 +232,94 @@ class TestPointInTimePropertiesClickhouse(ClickhouseTestMixin, BaseTest):)flush_persons_and_events()+ with self.capture_select_queries() as queries:+ properties = build_person_properties_at_time(+ self.team,+ upper_bound,+ [distinct_id],+ )++ self.assertEqual(properties, {"hello": "world"})+ # The default row_limit exceeds HogQL's usual top-level cap; a capped query would+ # silently drop the newest property updates on busy persons.+ self.assertEqual(len(queries), 1)+ self.assertIn(f"LIMIT {DEFAULT_PROPERTY_ROW_LIMIT}", queries[0])+ self.assertNotIn("JOIN", queries[0])++ def test_merges_property_events_across_distinct_ids(self):+ upper_bound = datetime(2024, 6, 1, 12, 0, 0, tzinfo=UTC)++ _create_event(+ event="$set",+ team=self.team,+ distinct_id="user-clickhouse-alias-a",+ properties={"$set": {"name": "Alias A"}},+ timestamp=upper_bound - timedelta(hours=2),+ )+ _create_event(+ event="$set",+ team=self.team,+ distinct_id="user-clickhouse-alias-b",+ properties={"$set": {"email": "[email protected]"}},+ timestamp=upper_bound - timedelta(hours=1),+ )+ flush_persons_and_events()++ properties = build_person_properties_at_time(+ self.team,+ upper_bound,+ ["user-clickhouse-alias-a", "user-clickhouse-alias-b"],+ )++ self.assertEqual(properties, {"name": "Alias A", "email": "[email protected]"})++ def test_window_bounds_are_instants_in_non_utc_team_timezone(self):+ self.team.timezone = "Pacific/Auckland"+ self.team.save()+ distinct_id = "user-clickhouse-timezone"+ upper_bound = datetime(2024, 6, 1, 12, 0, 0, tzinfo=UTC)++ _create_event(+ event="$set",+ team=self.team,+ distinct_id=distinct_id,+ properties={"$set": {"before": "yes"}},+ timestamp=upper_bound - timedelta(hours=1),+ )+ _create_event(+ event="$set",+ team=self.team,+ distinct_id=distinct_id,+ properties={"$set": {"after": "yes"}},+ timestamp=upper_bound + timedelta(minutes=1),+ )+ flush_persons_and_events()+properties = build_person_properties_at_time(- self.team.pk,+ self.team,upper_bound,[distinct_id],)- self.assertEqual(properties, {"hello": "world"})+ self.assertEqual(properties, {"before": "yes"})++ @override_settings(EVENTS_DATA_RETENTION_ENFORCED=True)+ def test_scan_ignores_events_retention_floor(self):+ # Ingestion applies every $set regardless of the plan's retention, so the rebuilt profile must too.+ self.team.event_retention_months = 12+ self.team.save()+ distinct_id = "user-clickhouse-retention"+ upper_bound = datetime.now(UTC)++ _create_event(+ event="$set",+ team=self.team,+ distinct_id=distinct_id,+ properties={"$set": {"plan": "legacy"}},+ timestamp=upper_bound - timedelta(days=30 * 18),+ )+ flush_persons_and_events()++ properties = build_person_properties_at_time(self.team, upper_bound, [distinct_id])++ self.assertEqual(properties, {"plan": "legacy"})diff --git a/posthog/models/usage_report_events_preagg/test/test_usage_report_events_preagg_mv.py b/posthog/models/usage_report_events_preagg/test/test_usage_report_events_preagg_mv.pyindex 10ac7760cf39..ae0e1836e715 100644--- a/posthog/models/usage_report_events_preagg/test/test_usage_report_events_preagg_mv.py+++ b/posthog/models/usage_report_events_preagg/test/test_usage_report_events_preagg_mv.py@@ -11,6 +11,7 @@ import jsonfrom datetime import datetimefrom uuid import uuid4+import pytestfrom posthog.test.base import ClickhouseTestMixinfrom django.test import SimpleTestCase@@ -51,6 +52,7 @@ def _make_event_row(distinct_id: str, event: str, lib: str, team_id: int) -> dic}[email protected]("clickhouse_database")class TestUsageReportEventsPreaggMV(ClickhouseTestMixin, SimpleTestCase):@classmethoddef setUpClass(cls) -> None:diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.pyindex 037bce5cb5c7..c69a0e58df6f 100644--- a/products/feature_flags/backend/api/feature_flag.py+++ b/products/feature_flags/backend/api/feature_flag.py@@ -5718,7 +5718,7 @@ class FeatureFlagViewSet(if feature_flag.created_at:lower_bound = min(max(lower_bound, feature_flag.created_at), timestamp)person_properties = build_person_properties_at_time(- team_id=self.team_id,+ team=self.team,timestamp=timestamp,distinct_ids=distinct_ids,include_set_once=True,