: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(web-analytics): apply cohort filters in web vitals path breakdown (#116712)
posthog[bot]244d3b6f75a9
diff --git a/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_vitals_path_breakdown.ambr b/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_vitals_path_breakdown.ambrindex 3807fb1a93de..9f1b5010885f 100644--- a/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_vitals_path_breakdown.ambr+++ b/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_vitals_path_breakdown.ambr@@ -329,3 +329,89 @@use_hive_partitioning=0'''# ---+# name: TestWebVitalsPathBreakdownQueryRunner.test_test_account_cohort_filter_is_applied+ '''+ SELECT person_id+ FROM person_static_cohort+ WHERE team_id = 99999+ AND cohort_id = 99999+ AND person_id IN ['00000000-0000-4000-8000-000000000001']+ GROUP BY person_id+ '''+# ---+# name: TestWebVitalsPathBreakdownQueryRunner.test_test_account_cohort_filter_is_applied.1+ '''+ SELECT band AS band,+ path AS path,+ value AS value+ FROM+ (SELECT multiIf(ifNull(lessOrEquals(value, 100.0), 0), 'good', ifNull(lessOrEquals(value, 200.0), 0), 'needs_improvements', 'poor') AS band,+ path AS path,+ value AS value+ FROM+ (SELECT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$pathname'), ''), 'null'), '^"|"$', '') AS path,+ quantile(0.75)(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$web_vitals_INP_value'), ''), 'null'), '^"|"$', ''), 'Float64')) AS value+ FROM events+ WHERE and(equals(events.team_id, 99999), and(equals(events.event, '$web_vitals'), isNotNull(path), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-08 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-15 23:59:59', 'UTC')))), 0), 1))+ GROUP BY path+ HAVING ifNull(greaterOrEquals(value, 0), 0)))+ ORDER BY value ASC,+ path ASC+ LIMIT 20 BY band+ LIMIT 100 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ optimize_rewrite_aggregate_function_with_if=0,+ optimize_min_inequality_conjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestWebVitalsPathBreakdownQueryRunner.test_test_account_cohort_filter_is_applied.2+ '''+ SELECT band AS band,+ path AS path,+ value AS value+ FROM+ (SELECT multiIf(ifNull(lessOrEquals(value, 100.0), 0), 'good', ifNull(lessOrEquals(value, 200.0), 0), 'needs_improvements', 'poor') AS band,+ path AS path,+ value AS value+ FROM+ (SELECT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$pathname'), ''), 'null'), '^"|"$', '') AS path,+ quantile(0.75)(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$web_vitals_INP_value'), ''), 'null'), '^"|"$', ''), 'Float64')) AS value+ FROM events+ LEFT OUTER JOIN+ (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) 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 equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 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), and(equals(events.event, '$web_vitals'), isNotNull(path), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-08 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-15 23:59:59', 'UTC')))), 0), notIn(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id),+ (SELECT person_static_cohort.person_id AS person_id+ FROM person_static_cohort+ WHERE and(equals(person_static_cohort.team_id, 99999), equals(person_static_cohort.cohort_id, 99999))))))+ GROUP BY path+ HAVING ifNull(greaterOrEquals(value, 0), 0)))+ ORDER BY value ASC,+ path ASC+ LIMIT 20 BY band+ LIMIT 100 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ optimize_rewrite_aggregate_function_with_if=0,+ optimize_min_inequality_conjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---diff --git a/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_vitals_path_breakdown.new_events_schema.ambr b/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_vitals_path_breakdown.new_events_schema.ambrindex e96245ccf818..3f11c3fd8e4a 100644--- a/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_vitals_path_breakdown.new_events_schema.ambr+++ b/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_vitals_path_breakdown.new_events_schema.ambr@@ -349,3 +349,83 @@output_format_json_escape_forward_slashes=0'''# ---+# name: TestWebVitalsPathBreakdownQueryRunner.test_test_account_cohort_filter_is_applied[new_events_schema.1]+ '''+ SELECT band AS band,+ path AS path,+ value AS value+ FROM+ (SELECT multiIf(ifNull(lessOrEquals(value, 100.0), 0), 'good', ifNull(lessOrEquals(value, 200.0), 0), 'needs_improvements', 'poor') AS band,+ path AS path,+ value AS value+ FROM+ (SELECT if(notEquals(toJSONString(events.properties.^`$pathname`), '{}'), toJSONString(events.properties.^`$pathname`), if(isNull(nullIf(toString(events.properties.`$pathname`), '')), NULL, if(and(in(ascii(toString(events.properties.`$pathname`)), tuple(91, 123)), in(ascii(toJSONString(events.properties.`$pathname`)), tuple(91, 123))), nullIf(nullIf(toJSONString(events.properties.`$pathname`), '[]'), '{}'), toString(events.properties.`$pathname`)))) AS path,+ quantile(0.75)(accurateCastOrNull(events.properties.`$web_vitals_INP_value`, 'Float64')) AS value+ FROM events_json AS events+ LEFT OUTER JOIN+ (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) 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 equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 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), and(equals(events.event, '$web_vitals'), isNotNull(path), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-08 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-15 23:59:59', 'UTC')))), 0), notIn(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id),+ (SELECT person_static_cohort.person_id AS person_id+ FROM person_static_cohort+ WHERE and(equals(person_static_cohort.team_id, 99999), equals(person_static_cohort.cohort_id, 99999))))))+ GROUP BY path+ HAVING ifNull(greaterOrEquals(value, 0), 0)))+ ORDER BY value ASC,+ path ASC+ LIMIT 20 BY band+ LIMIT 100 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ optimize_rewrite_aggregate_function_with_if=0,+ optimize_min_inequality_conjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0,+ json_type_escape_dots_in_keys=1,+ output_format_json_escape_forward_slashes=0+ '''+# ---+# name: TestWebVitalsPathBreakdownQueryRunner.test_test_account_cohort_filter_is_applied[new_events_schema]+ '''+ SELECT band AS band,+ path AS path,+ value AS value+ FROM+ (SELECT multiIf(ifNull(lessOrEquals(value, 100.0), 0), 'good', ifNull(lessOrEquals(value, 200.0), 0), 'needs_improvements', 'poor') AS band,+ path AS path,+ value AS value+ FROM+ (SELECT if(notEquals(toJSONString(events.properties.^`$pathname`), '{}'), toJSONString(events.properties.^`$pathname`), if(isNull(nullIf(toString(events.properties.`$pathname`), '')), NULL, if(and(in(ascii(toString(events.properties.`$pathname`)), tuple(91, 123)), in(ascii(toJSONString(events.properties.`$pathname`)), tuple(91, 123))), nullIf(nullIf(toJSONString(events.properties.`$pathname`), '[]'), '{}'), toString(events.properties.`$pathname`)))) AS path,+ quantile(0.75)(accurateCastOrNull(events.properties.`$web_vitals_INP_value`, 'Float64')) AS value+ FROM events_json AS events+ WHERE and(equals(events.team_id, 99999), and(equals(events.event, '$web_vitals'), isNotNull(path), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-08 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-15 23:59:59', 'UTC')))), 0), 1))+ GROUP BY path+ HAVING ifNull(greaterOrEquals(value, 0), 0)))+ ORDER BY value ASC,+ path ASC+ LIMIT 20 BY band+ LIMIT 100 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ optimize_rewrite_aggregate_function_with_if=0,+ optimize_min_inequality_conjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0,+ json_type_escape_dots_in_keys=1,+ output_format_json_escape_forward_slashes=0+ '''+# ---diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_vitals_path_breakdown.py b/products/web_analytics/backend/hogql_queries/test/test_web_vitals_path_breakdown.pyindex 8e589f0064bb..a846de85f86a 100644--- a/products/web_analytics/backend/hogql_queries/test/test_web_vitals_path_breakdown.py+++ b/products/web_analytics/backend/hogql_queries/test/test_web_vitals_path_breakdown.py@@ -3,6 +3,7 @@ from posthog.test.base import (APIBaseTest,ClickhouseTestMixin,_create_event,+ _create_person,flush_persons_and_events,snapshot_clickhouse_queries,)@@ -18,6 +19,7 @@ from posthog.schema import (WebVitalsPathBreakdownResultItem,)+from products.cohorts.backend.models.cohort import Cohortfrom products.web_analytics.backend.hogql_queries.web_vitals_path_breakdown import WebVitalsPathBreakdownQueryRunner@@ -49,6 +51,7 @@ class TestWebVitalsPathBreakdownQueryRunner(ClickhouseTestMixin, APIBaseTest):metric: WebVitalsMetric = WebVitalsMetric.INP,percentile: PropertyMathType = PropertyMathType.P75,properties=None,+ filter_test_accounts: bool = False,):with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):query = WebVitalsPathBreakdownQuery(@@ -57,6 +60,7 @@ class TestWebVitalsPathBreakdownQueryRunner(ClickhouseTestMixin, APIBaseTest):percentile=percentile,thresholds=thresholds,properties=properties or [],+ filterTestAccounts=filter_test_accounts,)runner = WebVitalsPathBreakdownQueryRunner(team=self.team, query=query)@@ -281,6 +285,48 @@ class TestWebVitalsPathBreakdownQueryRunner(ClickhouseTestMixin, APIBaseTest):results,)+ def test_test_account_cohort_filter_is_applied(self):+ _create_person(team_id=self.team.pk, distinct_ids=["visitor"])+ _create_person(team_id=self.team.pk, distinct_ids=["scanner"])+ self._create_events(+ [+ ("visitor", [("2025-01-10", "/path1", 50)]),+ ("scanner", [("2025-01-10", "/path1", 500), ("2025-01-10", "/path2", 500)]),+ ],+ WebVitalsMetric.INP,+ )+ cohort = Cohort.objects.create(team=self.team, name="scanners", groups=[], is_static=True)+ cohort.insert_users_by_list(["scanner"])+ self.team.test_account_filters = [{"key": "id", "type": "cohort", "value": cohort.pk, "operator": "not_in"}]+ self.team.save()++ unfiltered = self._run_web_vitals_path_breakdown_query("2025-01-08", "2025-01-15", (100, 200)).results+ filtered = self._run_web_vitals_path_breakdown_query(+ "2025-01-08", "2025-01-15", (100, 200), filter_test_accounts=True+ ).results++ self.assertEqual(+ [+ WebVitalsPathBreakdownResult(+ good=[],+ needs_improvements=[],+ poor=[+ WebVitalsPathBreakdownResultItem(path="/path1", value=387.5),+ WebVitalsPathBreakdownResultItem(path="/path2", value=500),+ ],+ )+ ],+ unfiltered,+ )+ self.assertEqual(+ [+ WebVitalsPathBreakdownResult(+ good=[WebVitalsPathBreakdownResultItem(path="/path1", value=50)], needs_improvements=[], poor=[]+ )+ ],+ filtered,+ )+def test_path_cleaning_filters(self):self._create_events([diff --git a/products/web_analytics/backend/hogql_queries/web_analytics_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/web_analytics_lazy_precompute.pyindex bad1402d6582..db741d1f1fea 100644--- a/products/web_analytics/backend/hogql_queries/web_analytics_lazy_precompute.py+++ b/products/web_analytics/backend/hogql_queries/web_analytics_lazy_precompute.py@@ -326,7 +326,7 @@ def check_common_eligible(# bounded by the per-team shape ceiling in `web_ensure_precomputed`. Session and# cohort filters are refused: the precompute INSERT applies the whole list userlessly,# but the live runners handle those types differently per family (web vitals drops- # them entirely), so precomputing them would serve a different population than the+ # session filters), so precomputing them would serve a different population than the# live fallback. Those queries fall through to the live path, which applies them right.for prop in query.properties or []:if (diff --git a/products/web_analytics/backend/hogql_queries/web_lazy_precompute_common.py b/products/web_analytics/backend/hogql_queries/web_lazy_precompute_common.pyindex d30815e69477..99cc3ac5e347 100644--- a/products/web_analytics/backend/hogql_queries/web_lazy_precompute_common.py+++ b/products/web_analytics/backend/hogql_queries/web_lazy_precompute_common.py@@ -1008,7 +1008,7 @@ def check_common_eligibility(# cache key, bounded by the per-team shape ceiling in `web_ensure_precomputed`.# Session and cohort filters are refused: the precompute INSERT applies the whole# list userlessly, but the live runners handle those types differently per family- # (web vitals drops them entirely), so precomputing them would serve a different+ # (web vitals drops session filters), so precomputing them would serve a different# population than the live fallback. Those queries fall through to the live path,# which applies them correctly.for prop in properties:diff --git a/products/web_analytics/backend/hogql_queries/web_vitals_path_breakdown.py b/products/web_analytics/backend/hogql_queries/web_vitals_path_breakdown.pyindex ea109ceec439..cc8de5748b87 100644--- a/products/web_analytics/backend/hogql_queries/web_vitals_path_breakdown.py+++ b/products/web_analytics/backend/hogql_queries/web_vitals_path_breakdown.py@@ -74,7 +74,9 @@ HAVING value >= 0def _event_properties(self) -> ast.Expr:properties = [- p for p in self.query.properties + self._test_account_filters if get_property_type(p) in ["event", "person"]+ p+ for p in self.query.properties + self._test_account_filters+ if get_property_type(p) in ["event", "person", "cohort"]]return property_to_expr(properties, team=self.team, scope="event")