:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(property-vals): event values from aggregated table behind flag (#61837)
Andy Zhao01dfe9b09557
diff --git a/posthog/hogql_queries/property_values_query_runner.py b/posthog/hogql_queries/property_values_query_runner.pyindex 174e2188ffaa..d05839303107 100644--- a/posthog/hogql_queries/property_values_query_runner.py+++ b/posthog/hogql_queries/property_values_query_runner.py@@ -1,8 +1,13 @@import jsonimport uuidfrom datetime import datetime+from functools import cached_propertyfrom typing import Any, Optional, cast+from django.utils import timezone++import posthoganalytics+from posthog.schema import (CachedPropertyValuesQueryResponse,PropertyType,@@ -19,8 +24,17 @@ from posthog.caching.utils import (cache_target_age as _cache_target_age,)from posthog.hogql_queries.query_runner import AnalyticsQueryRunner+from posthog.models import PropertyDefinition+from posthog.queries.property_values import (+ get_event_property_values_from_aggregated_table,+ get_person_property_values_for_key,+)from posthog.utils import convert_property_value, flatten, relative_date_parse+from products.access_control.backend.property_access_control import get_restricted_property_names++PROPERTY_VALUES_TABLE_FLAG = "property-values-table"+class PropertyValuesQueryRunner(AnalyticsQueryRunner[PropertyValuesQueryResponse]):query: PropertyValuesQuery@@ -47,6 +61,8 @@ class PropertyValuesQueryRunner(AnalyticsQueryRunner[PropertyValuesQueryResponsereturn self._calculate_event()def _calculate_event(self) -> PropertyValuesQueryResponse:+ if self._use_property_values_table:+ return self._calculate_event_from_table()result = execute_hogql_query(self._event_query(),team=self.team,@@ -62,13 +78,43 @@ class PropertyValuesQueryRunner(AnalyticsQueryRunner[PropertyValuesQueryResponsemodifiers=self.modifiers,)+ @cached_property+ def _use_property_values_table(self) -> bool:+ # Column and virtual lookups stay on the events scan: the table only+ # holds keys from the properties blob. event_names is deliberately not+ # a fallback: the table has no event dimension, so flagged teams get+ # event-agnostic value suggestions for event-scoped requests.+ if self.query.is_column or self.query.property_key.startswith("$virt_"):+ return False+ if not posthoganalytics.feature_enabled(PROPERTY_VALUES_TABLE_FLAG, str(self.team.pk)):+ return False+ # Restricted keys stay on the events scan: the table read bypasses HogQL+ # property resolution, which is where property access control is enforced.+ # self.user is None on the events endpoint path, which fail-closes to the+ # events scan for any key restricted for anyone on the team.+ restricted = get_restricted_property_names(+ team_id=self.team.pk, user=self.user, property_type=PropertyDefinition.Type.EVENT+ )+ return self.query.property_key not in restricted++ def _calculate_event_from_table(self) -> PropertyValuesQueryResponse:+ rows = cast(+ list,+ get_event_property_values_from_aggregated_table(+ self.query.property_key, self.team, self.query.search_value+ ),+ )+ return PropertyValuesQueryResponse(+ results=self._format_table_results(rows),+ timings=self.timings.to_list(),+ modifiers=self.modifiers,+ )+def _calculate_person(self) -> PropertyValuesQueryResponse:# Use the raw SQL person query — the HogQL persons virtual table does full argMax dedup# which is correct but much slower (30s vs 4s on large teams). The raw SQL approximates# dedup with uniq(id) - uniqIf(id, is_deleted != 0) and caps at 100k rows, which is# fast enough and good enough for autocomplete.- from posthog.queries.property_values import get_person_property_values_for_key-rows = cast(list, get_person_property_values_for_key(self.query.property_key, self.team, self.query.search_value))@@ -79,8 +125,6 @@ class PropertyValuesQueryRunner(AnalyticsQueryRunner[PropertyValuesQueryResponse)def _event_query(self) -> ast.SelectQuery:- from django.utils import timezone-key = self.query.property_keyis_virtual = key.startswith("$virt_")chain: list[str | int] = [key] if (self.query.is_column or is_virtual) else ["properties", key]@@ -161,6 +205,23 @@ class PropertyValuesQueryRunner(AnalyticsQueryRunner[PropertyValuesQueryResponsevalues.append(json.loads(cleaned))except (json.JSONDecodeError, TypeError):values.append(cleaned)+ return self._to_property_value_items(values)++ def _format_table_results(self, rows: list) -> list[PropertyValueItem]:+ # Values are stored as the raw strings the aggregator coerced at fan-out, so+ # JSON-ish values (arrays, numbers, bools) parse and arrays flatten into+ # individual entries, matching the events-scan formatting. No '\\"' unescape+ # is needed here since the table stores clean strings.+ values: list[Any] = []+ for row in rows:+ raw = row[0]+ try:+ values.append(json.loads(raw))+ except (json.JSONDecodeError, TypeError):+ values.append(raw)+ return self._to_property_value_items(values)++ def _to_property_value_items(self, values: list[Any]) -> list[PropertyValueItem]:return [PropertyValueItem(name=convert_property_value(v)) for v in flatten(values)]def _format_person_results(self, rows: list) -> list[PropertyValueItem]:diff --git a/posthog/hogql_queries/test/test_property_values_query_runner.py b/posthog/hogql_queries/test/test_property_values_query_runner.pyindex 0aa4e40d5b54..f6c786af1b5e 100644--- a/posthog/hogql_queries/test/test_property_values_query_runner.py+++ b/posthog/hogql_queries/test/test_property_values_query_runner.py@@ -1,9 +1,13 @@+from datetime import datetime, timedelta+from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person, flush_persons_and_eventsfrom unittest.mock import patchfrom parameterized import parameterized+from posthog.clickhouse.client import sync_executefrom posthog.hogql_queries.property_values_query_runner import (+ PROPERTY_VALUES_TABLE_FLAG,CachedPropertyValuesQueryResponse,PropertyType,PropertyValueItem,@@ -252,3 +256,150 @@ class TestPropertyValuesQueryRunner(ClickhouseTestMixin, APIBaseTest):assert len(slo_started_calls) == 1captured_props = slo_started_calls[0].kwargs["properties"]assert captured_props["execution_mode"] == expected_value+++class TestPropertyValuesQueryRunnerAggregatedTable(ClickhouseTestMixin, APIBaseTest):+ def _run(self, query: PropertyValuesQuery) -> list[PropertyValueItem]:+ runner = PropertyValuesQueryRunner(team=self.team, query=query)+ return runner.calculate().results++ def _flag_on(self):+ return patch(+ "posthog.hogql_queries.property_values_query_runner.posthoganalytics.feature_enabled",+ side_effect=lambda flag, *args, **kwargs: flag == PROPERTY_VALUES_TABLE_FLAG,+ )++ def _insert_rows(self, rows: list[tuple]) -> None:+ sync_execute(+ "INSERT INTO property_values (team_id, property_type, property_key, property_value, property_count, last_seen) VALUES",+ rows,+ )++ def test_values_ordered_by_summed_count(self):+ now = datetime.now()+ self._insert_rows(+ [+ (self.team.pk, "event", "browser", "Chrome", 3, now),+ (self.team.pk, "event", "browser", "Chrome", 4, now),+ (self.team.pk, "event", "browser", "Firefox", 2, now),+ ]+ )++ with self._flag_on():+ results = self._run(PropertyValuesQuery(property_type=PropertyType.EVENT, property_key="browser"))+ assert [r.name for r in results] == ["Chrome", "Firefox"]+ assert results[0].count is None++ @parameterized.expand(+ [+ ("lowercase_needle", "chr", {"Chrome"}),+ ("uppercase_needle", "FIRE", {"Firefox"}),+ ("non_matching", "edge", set()),+ ("percent_wildcard", "%", set()),+ ("underscore_wildcard", "chr_me", set()),+ ]+ )+ def test_search_is_case_insensitive_and_escapes_wildcards(self, _name, search_value, expected_names):+ now = datetime.now()+ self._insert_rows(+ [+ (self.team.pk, "event", "browser", "Chrome", 3, now),+ (self.team.pk, "event", "browser", "Firefox", 2, now),+ ]+ )++ with self._flag_on():+ results = self._run(+ PropertyValuesQuery(property_type=PropertyType.EVENT, property_key="browser", search_value=search_value)+ )+ assert {r.name for r in results} == expected_names++ def test_values_not_seen_in_seven_days_are_excluded(self):+ self._insert_rows(+ [+ (self.team.pk, "event", "browser", "Chrome", 3, datetime.now()),+ (self.team.pk, "event", "browser", "Netscape", 100, datetime.now() - timedelta(days=10)),+ ]+ )++ with self._flag_on():+ results = self._run(PropertyValuesQuery(property_type=PropertyType.EVENT, property_key="browser"))+ assert {r.name for r in results} == {"Chrome"}++ def test_other_team_values_are_excluded(self):+ self._insert_rows([(self.team.pk + 999999, "event", "browser", "Chrome", 3, datetime.now())])++ with self._flag_on():+ results = self._run(PropertyValuesQuery(property_type=PropertyType.EVENT, property_key="browser"))+ assert results == []++ def test_person_type_rows_are_excluded(self):+ self._insert_rows(+ [+ (self.team.pk, "event", "browser", "Chrome", 3, datetime.now()),+ (self.team.pk, "person", "browser", "PersonChrome", 3, datetime.now()),+ ]+ )++ with self._flag_on():+ results = self._run(PropertyValuesQuery(property_type=PropertyType.EVENT, property_key="browser"))+ assert {r.name for r in results} == {"Chrome"}++ def test_json_array_value_is_flattened(self):+ self._insert_rows([(self.team.pk, "event", "tags", '["python", "django"]', 3, datetime.now())])++ with self._flag_on():+ results = self._run(PropertyValuesQuery(property_type=PropertyType.EVENT, property_key="tags"))+ assert {r.name for r in results} == {"python", "django"}++ def test_event_scoped_request_is_served_unscoped_from_table(self):+ self._insert_rows([(self.team.pk, "event", "browser", "TableValue", 3, datetime.now())])+ _create_event(event="$pageview", distinct_id="u1", team=self.team, properties={"browser": "EventScopedValue"})++ with self._flag_on():+ results = self._run(+ PropertyValuesQuery(property_type=PropertyType.EVENT, property_key="browser", event_names=["$pageview"])+ )+ assert {r.name for r in results} == {"TableValue"}++ def test_restricted_property_key_uses_events_scan(self):+ self._insert_rows([(self.team.pk, "event", "browser", "TableOnly", 3, datetime.now())])+ _create_event(event="$pageview", distinct_id="u1", team=self.team, properties={"browser": "EventOnly"})++ with (+ self._flag_on(),+ patch(+ "posthog.hogql_queries.property_values_query_runner.get_restricted_property_names",+ return_value={"browser"},+ ),+ ):+ results = self._run(PropertyValuesQuery(property_type=PropertyType.EVENT, property_key="browser"))+ assert {r.name for r in results} == {"EventOnly"}++ def test_is_column_uses_events_scan(self):+ self._insert_rows([(self.team.pk, "event", "event", "TableOnly", 3, datetime.now())])+ _create_event(event="$pageview", distinct_id="u1", team=self.team, properties={})++ with self._flag_on():+ results = self._run(+ PropertyValuesQuery(property_type=PropertyType.EVENT, property_key="event", is_column=True)+ )+ assert {r.name for r in results} == {"$pageview"}++ def test_virtual_key_uses_events_scan(self):+ runner = PropertyValuesQueryRunner(+ team=self.team,+ query=PropertyValuesQuery(property_type=PropertyType.EVENT, property_key="$virt_initial_channel_type"),+ )+ with self._flag_on():+ assert runner._use_property_values_table is False++ def test_flag_off_uses_events_scan(self):+ self._insert_rows([(self.team.pk, "event", "browser", "TableOnly", 3, datetime.now())])++ with patch(+ "posthog.hogql_queries.property_values_query_runner.posthoganalytics.feature_enabled",+ return_value=False,+ ):+ results = self._run(PropertyValuesQuery(property_type=PropertyType.EVENT, property_key="browser"))+ assert results == []diff --git a/posthog/queries/property_values.py b/posthog/queries/property_values.pyindex 6771cac1718b..2044ef676f9d 100644--- a/posthog/queries/property_values.py+++ b/posthog/queries/property_values.py@@ -79,6 +79,44 @@ def get_property_values_for_key(return result+# property_values_distributed routes to the aggregated table on the aux cluster.+SELECT_EVENT_PROPERTY_VALUES_FROM_AGGREGATED_TABLE_SQL = """+SELECT property_value, sum(property_count) AS prop_count+FROM property_values_distributed+WHERE team_id = %(team_id)s+ AND property_type = 'event'+ AND property_key = %(key)s+ AND last_seen >= now() - INTERVAL 7 DAY+ {value_filter}+GROUP BY property_value+ORDER BY prop_count DESC+LIMIT 10+"""+++def get_event_property_values_from_aggregated_table(key: str, team: Team, value: Optional[str] = None) -> list:+ with tracer.start_as_current_span("get_event_property_values_from_aggregated_table") as span:+ span.set_attribute("team_id", team.pk)+ span.set_attribute("property_key", key)+ span.set_attribute("has_value_filter", value is not None)++ params: dict = {"team_id": team.pk, "key": key}+ value_filter = ""+ if value:+ escaped = value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")+ value_filter = "AND lower(property_value) LIKE %(value)s"+ params["value"] = f"%{escaped.lower()}%"++ result = insight_sync_execute(+ SELECT_EVENT_PROPERTY_VALUES_FROM_AGGREGATED_TABLE_SQL.format(value_filter=value_filter),+ params,+ query_type="get_event_property_values_from_aggregated_table",+ team_id=team.pk,+ )+ span.set_attribute("result_count", len(result))+ return result++def get_person_property_values_for_key(key: str, team: Team, value: Optional[str] = None):with tracer.start_as_current_span("get_person_property_values_for_key") as span:span.set_attribute("team_id", team.pk)diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_mean_metric.ambr b/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_mean_metric.ambrindex 9949fba14211..6506f2a21ed9 100644--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_mean_metric.ambr+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_mean_metric.ambr@@ -127,6 +127,60 @@use_hive_partitioning=0'''# ---+# name: TestExperimentMeanMetric.test_conversion_window_extends_to_last_exposure_1_precomputed+ '''+ WITH exposures AS+ (SELECT accurateCastOrNull(t.entity_id, 'UUID') AS entity_id,+ if(ifNull(greater(uniqExact(t.variant), 1), 0), '$multiple', argMin(t.variant, toTimeZone(t.first_exposure_time, 'UTC'))) AS variant,+ min(toTimeZone(t.first_exposure_time, 'UTC')) AS first_exposure_time,+ max(toTimeZone(t.last_exposure_time, 'UTC')) AS last_exposure_time,+ argMin(t.exposure_event_uuid, toTimeZone(t.first_exposure_time, 'UTC')) AS exposure_event_uuid,+ argMin(t.exposure_session_id, toTimeZone(t.first_exposure_time, 'UTC')) AS exposure_session_id+ FROM experiment_exposures_preaggregated AS t+ WHERE and(equals(t.team_id, 99999), in(t.job_id, ['00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000']), equals(t.team_id, 99999), greaterOrEquals(t.first_exposure_time, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), lessOrEquals(t.first_exposure_time, assumeNotNull(toDateTime('2020-01-10 00:00:00', 'UTC'))))+ GROUP BY entity_id),+ metric_events AS+ (SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS entity_id,+ toTimeZone(events.timestamp, 'UTC') AS timestamp,+ coalesce(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'amount'), ''), 'null'), '^"|"$', ''), 'Float64'), 0) AS value+ FROM events+ LEFT OUTER JOIN+ (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,+ person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 99999)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ WHERE and(equals(events.team_id, 99999), greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), less(events.timestamp, plus(assumeNotNull(toDateTime('2020-01-10 00:00:00', 'UTC')), toIntervalSecond(86400))), equals(events.event, 'purchase'))),+ entity_metrics AS+ (SELECT exposures.entity_id AS entity_id,+ exposures.variant AS variant,+ sum(coalesce(accurateCastOrNull(metric_events.value, 'Float64'), 0)) AS value+ FROM exposures+ LEFT JOIN metric_events ON and(equals(exposures.entity_id, metric_events.entity_id), and(greaterOrEquals(toTimeZone(metric_events.timestamp, 'UTC'), exposures.first_exposure_time), less(toTimeZone(metric_events.timestamp, 'UTC'), plus(exposures.last_exposure_time, toIntervalSecond(86400)))))+ GROUP BY exposures.entity_id,+ exposures.variant)+ SELECT entity_metrics.variant AS variant,+ count(entity_metrics.entity_id) AS num_users,+ sum(entity_metrics.value) AS total_sum,+ sum(power(entity_metrics.value, 2)) AS total_sum_of_squares+ FROM entity_metrics+ GROUP BY entity_metrics.variant+ LIMIT 50000 SETTINGS join_algorithm='grace_hash',+ grace_hash_join_initial_buckets=2,+ load_balancing='in_order',+ readonly=2,+ max_execution_time=600,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=39728447488,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---# name: TestExperimentMeanMetric.test_count_distinct_property_values_via_hogql_0_direct'''WITH exposures AS