Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(web-analytics): remove events prefilter experiment (#70932)

Lucas Ricoy97c9cc4e41db
diff --git a/posthog/models/web_preaggregated/test_web_pre_aggregated_timezones.py b/posthog/models/web_preaggregated/test_web_pre_aggregated_timezones.py
index c0c4d5b5505d..ea4a64e53979 100644
--- a/posthog/models/web_preaggregated/test_web_pre_aggregated_timezones.py
+++ b/posthog/models/web_preaggregated/test_web_pre_aggregated_timezones.py
@@ -1,5 +1,4 @@
from posthog.test.base import _create_event, _create_person, flush_persons_and_events, snapshot_clickhouse_queries
-from unittest.mock import patch
from parameterized import parameterized
@@ -19,15 +18,6 @@ from products.web_analytics.backend.hogql_queries.test.web_preaggregated_test_ba
@snapshot_clickhouse_queries
class TestTimezonePreAggregatedIntegration(WebAnalyticsPreAggregatedTestBase, FloatAwareTestCase):
- def setUp(self):
- super().setUp()
- patcher = patch(
- "products.web_analytics.backend.hogql_queries.stats_table.is_web_analytics_events_prefilter_team",
- return_value=False,
- )
- patcher.start()
- self.addCleanup(patcher.stop)
-
def _setup_test_data(self):
"""Required by WebAnalyticsPreAggregatedTestBase. Each test handles its own data setup."""
pass
diff --git a/posthog/settings/data_stores.py b/posthog/settings/data_stores.py
index 9ca7405fb765..44360758b9f7 100644
--- a/posthog/settings/data_stores.py
+++ b/posthog/settings/data_stores.py
@@ -1,8 +1,6 @@
import os
import json
-import time
from contextlib import suppress
-from functools import lru_cache
from pathlib import Path
from typing import Optional
@@ -406,23 +404,6 @@ except Exception:
CLICKHOUSE_PER_TEAM_QUERY_SETTINGS = {}
-def is_web_analytics_events_prefilter_team(team_id: int | None) -> bool:
- if team_id is None:
- return False
- return team_id in _get_web_analytics_events_prefilter_teams(round(time.time() / 120))
-
-
-@lru_cache(maxsize=1)
-def _get_web_analytics_events_prefilter_teams(_ttl: int) -> list[int]:
- from posthog.models.instance_setting import get_instance_setting
-
- try:
- value = get_instance_setting("WEB_ANALYTICS_EVENTS_PREFILTER_TEAM_IDS")
- return value if isinstance(value, list) else []
- except Exception:
- return []
-
-
# Set of teams querying the data before we switched to new limits
API_QUERIES_LEGACY_TEAM_LIST: Optional[set[int]] = None
with suppress(Exception):
diff --git a/posthog/settings/dynamic_settings.py b/posthog/settings/dynamic_settings.py
index 0042a65f53dd..620f4a35728f 100644
--- a/posthog/settings/dynamic_settings.py
+++ b/posthog/settings/dynamic_settings.py
@@ -285,11 +285,6 @@ CONSTANCE_CONFIG = {
"Teams that will have web analytics cache warming enabled",
list[int],
),
- "WEB_ANALYTICS_EVENTS_PREFILTER_TEAM_IDS": (
- get_from_env("WEB_ANALYTICS_EVENTS_PREFILTER_TEAM_IDS", default=[2, 140988], type_cast=list[int]),
- "Team IDs that use prefiltered events subqueries in web analytics bounce/scroll queries for better granule pruning",
- list[int],
- ),
}
SETTINGS_ALLOWING_API_OVERRIDE = (
@@ -340,7 +335,6 @@ SETTINGS_ALLOWING_API_OVERRIDE = (
"CLICKHOUSE_KILL_SWITCH_LIGHT_TEAMS",
"CLICKHOUSE_KILL_SWITCH_FULL_TEAMS",
"CLICKHOUSE_HEDGED_APP_QUERIES",
- "WEB_ANALYTICS_EVENTS_PREFILTER_TEAM_IDS",
"REDIRECT_APP_TO_US",
"WEB_ANALYTICS_WARMING_DAYS",
"WEB_ANALYTICS_WARMING_MIN_QUERY_COUNT",
diff --git a/products/web_analytics/backend/hogql_queries/events_prefilter.py b/products/web_analytics/backend/hogql_queries/events_prefilter.py
deleted file mode 100644
index b683fb1581c8..000000000000
--- a/products/web_analytics/backend/hogql_queries/events_prefilter.py
+++ /dev/null
@@ -1,344 +0,0 @@
-from __future__ import annotations
-
-from typing import TYPE_CHECKING, Union
-
-from posthog.hogql import ast
-from posthog.hogql.constants import LimitContext
-from posthog.hogql.database.models import DatabaseField, StringDatabaseField
-from posthog.hogql.visitor import TraversingVisitor
-
-from posthog.hogql_queries.insights.paginators import HogQLHasMorePaginator
-
-if TYPE_CHECKING:
- from posthog.schema import HogQLQueryResponse
-
- from posthog.hogql.database.models import Table
-
-
-class _EventsFieldCollector(TraversingVisitor):
- """Collects events-table field names and property accesses from the entire query."""
-
- def __init__(self, events_table_type: ast.Type):
- super().__init__()
- self.events_table_type = events_table_type
- self.fields: set[str] = set()
- self.property_accesses: set[tuple[str, str]] = set() # (property_name, table_column)
-
- def visit_field(self, node: ast.Field):
- field_type = node.type
- if isinstance(field_type, ast.PropertyType):
- self._record_property_access(field_type.field_type, str(field_type.chain[0]) if field_type.chain else None)
- field_type = field_type.field_type
- if isinstance(field_type, ast.FieldType) and self._matches_events_table(field_type.table_type):
- self.fields.add(field_type.name)
-
- def _matches_events_table(self, table_type: ast.Type | None) -> bool:
- """True when `table_type` is this collector's events-table occurrence.
-
- Property resolution reads materialized / dmat / property-group columns through a copy of the events table with
- the synthetic column added (the HogQL schema doesn't know those columns), so the reads it rewrote no longer
- compare equal to the occurrence's own type. Treat such an augmented copy of the same table as a match — without
- this, those columns are left out of the prefilter subquery and the outer query fails with UNKNOWN_IDENTIFIER.
- """
- if table_type == self.events_table_type:
- return True
- candidate: ast.Type | None = table_type
- target: ast.Type | None = self.events_table_type
- if isinstance(candidate, ast.TableAliasType) and isinstance(target, ast.TableAliasType):
- if candidate.alias != target.alias:
- return False
- candidate, target = candidate.table_type, target.table_type
- if not isinstance(candidate, ast.TableType) or not isinstance(target, ast.TableType):
- return False
- # An augmented copy is the same table class with the original's fields plus the synthetic ones.
- return type(candidate.table) is type(target.table) and set(target.table.fields).issubset(candidate.table.fields)
-
- def visit_property_access(self, node: ast.PropertyAccess):
- # After the lowering pass an unmaterialized `properties.$x` read is a `PropertyAccess` over the blob `Field`,
- # not a `PropertyType`. Record the property access so `_resolve_materialized_columns` keeps the `properties`
- # column in the subquery instead of discarding it. `super()` still visits `node.expr` (the blob field).
- super().visit_property_access(node)
- blob_type = node.expr.type
- if isinstance(blob_type, ast.FieldType) and node.keys:
- self._record_property_access(blob_type, str(node.keys[0]))
-
- def _record_property_access(self, blob_field_type: ast.FieldType, property_name: str | None) -> None:
- """Record a (property, table_column) access on the events table, if this property lives there."""
- if property_name is None:
- return
- table_type = blob_field_type.table_type
- col_name = blob_field_type.name
- # Unwrap VirtualTableType (e.g. poe for person properties) to check if this property ultimately lives on the
- # events table, and resolve the actual DB column name (e.g. "person_properties" instead of "properties").
- while isinstance(table_type, ast.VirtualTableType):
- db_field = table_type.virtual_table.fields.get(blob_field_type.name)
- if isinstance(db_field, DatabaseField):
- col_name = db_field.name
- table_type = table_type.table_type
- if self._matches_events_table(table_type):
- self.property_accesses.add((property_name, col_name))
-
-
-class EventsPrefilterTransformer(TraversingVisitor):
- """Wraps FROM events in a resolved AST with a prefiltered subquery.
-
- Used by WebStatsTableQueryRunner to push timestamp predicates into
- the events table scan before the expensive session and person override
- JOINs that the lazy resolver attaches.
-
- After transformation, each FROM events becomes:
- FROM (SELECT <columns> FROM events WHERE <prefilter>) AS events
-
- Materialized columns (mat_$pathname, etc.) are resolved at print time
- by the HogQL printer and bypass the AST type system. This transformer
- detects which mat columns the query needs and adds them to the subquery
- SELECT, temporarily registering them on the events table schema so the
- printer can resolve them. If any property access lacks a mat column,
- the `properties` JSON column is included as fallback for JSONExtractRaw.
-
- Must run on a fully-resolved AST (after lazy table resolution)
- and is intentionally scoped to WebStatsTableQueryRunner.
- """
-
- def __init__(self, team_id: int, date_from: str, date_to: str):
- super().__init__()
- self.team_id = team_id
- self.date_from = date_from
- self.date_to = date_to
- self.wraps_applied = 0
- self._temp_schema_fields: list[tuple[object, str]] = []
-
- def visit_select_query(self, node: ast.SelectQuery):
- super().visit_select_query(node)
-
- if node.select_from is None:
- return
- join = node.select_from
- if not isinstance(join.table, ast.Field) or join.table.chain != ["events"]:
- return
-
- events_table_type = join.type
- if events_table_type is None:
- return
-
- def make_field(name: str) -> ast.Field:
- return ast.Field(chain=[name], type=ast.FieldType(name=name, table_type=events_table_type))
-
- prefilter = ast.And(
- exprs=[
- ast.CompareOperation(
- left=ast.Call(name="toDate", args=[make_field("timestamp")]),
- right=ast.Constant(value=self.date_from),
- op=ast.CompareOperationOp.GtEq,
- ),
- ast.CompareOperation(
- left=ast.Call(name="toDate", args=[make_field("timestamp")]),
- right=ast.Constant(value=self.date_to),
- op=ast.CompareOperationOp.LtEq,
- ),
- ]
- )
-
- # Collect ALL events-table fields from the entire query (SELECT, WHERE, GROUP BY, JOINs)
- collector = _EventsFieldCollector(events_table_type)
- collector.visit(node)
- events_columns = collector.fields
- # Always include columns needed by JOIN constraints and the prefilter itself
- events_columns.update(["timestamp", "distinct_id", "$session_id_uuid"])
-
- # Resolve materialized columns for property accesses
- mat_column_names = self._resolve_materialized_columns(
- collector.property_accesses, events_columns, events_table_type
- )
-
- # Any collected column the HogQL schema doesn't know (a synthetic materialized / dmat / property-group read
- # built by property resolution) must be registered on the table for the duration of the print, or the
- # subquery's bare SELECT of it won't resolve.
- table = self._get_events_table(events_table_type)
- if table is not None:
- for column in events_columns | mat_column_names:
- if column not in table.fields:
- table.fields[column] = StringDatabaseField(name=column)
- self._temp_schema_fields.append((table, column))
-
- inner_join = ast.JoinExpr(table=join.table, type=events_table_type)
- subquery = ast.SelectQuery(
- # Bare fields (no ast.Alias) so ClickHouse column names pass through
- # directly — the printer resolves each to its CH name, matching what
- # the outer query expects.
- select=[make_field(c) for c in sorted(events_columns | mat_column_names)],
- select_from=inner_join,
- where=prefilter,
- type=ast.SelectQueryType(),
- )
-
- join.table = subquery
- join.alias = "events"
- assert subquery.type is not None
- join.type = ast.SelectQueryAliasType(alias="events", select_query_type=subquery.type)
- self.wraps_applied += 1
-
- def _resolve_materialized_columns(
- self,
- property_accesses: set[tuple[str, str]],
- events_columns: set[str],
- events_table_type: ast.Type,
- ) -> set[str]:
- """Resolve property accesses to materialized column names.
-
- For each property access (e.g. $pathname on properties), checks if a
- materialized column exists (mat_$pathname). If so, temporarily registers
- it on the events table schema and returns the name. If any property
- lacks a mat column, keeps the corresponding JSON column (properties or
- person_properties) in events_columns for JSONExtractRaw fallback.
- """
- from typing import cast
-
- from posthog.hogql.database.models import StringDatabaseField
-
- from posthog.clickhouse.materialized_columns import get_enabled_materialized_columns
- from posthog.models.property import TableColumn
-
- if not property_accesses:
- events_columns.discard("properties")
- return set()
-
- mat_cols_map = get_enabled_materialized_columns("events")
- mat_column_names: set[str] = set()
- unmaterialized_json_columns: set[str] = set()
-
- for prop_name, table_col in property_accesses:
- key = (prop_name, cast(TableColumn, table_col))
- if key in mat_cols_map:
- ch_name = mat_cols_map[key].name
- mat_column_names.add(ch_name)
- # Temporarily register on the events table so the printer can resolve it
- table = self._get_events_table(events_table_type)
- if table is not None and ch_name not in table.fields:
- table.fields[ch_name] = StringDatabaseField(name=ch_name)
- self._temp_schema_fields.append((table, ch_name))
- else:
- unmaterialized_json_columns.add(table_col)
-
- # Add JSON columns needed for unmaterialized property accesses and
- # discard those fully covered by mat columns. person_properties is
- # accessed via the poe virtual table so won't be in events_columns
- # already — temporarily register it on the events table schema.
- for json_col in unmaterialized_json_columns:
- events_columns.add(json_col)
- if json_col != "properties":
- table = self._get_events_table(events_table_type)
- if table is not None and json_col not in table.fields:
- table.fields[json_col] = StringDatabaseField(name=json_col)
- self._temp_schema_fields.append((table, json_col))
- for json_col in {"properties", "person_properties"}:
- if json_col not in unmaterialized_json_columns:
- events_columns.discard(json_col)
-
- return mat_column_names
-
- @staticmethod
- def _get_events_table(table_type: ast.Type) -> Table | None:
- from posthog.hogql.database.models import Table as TableModel
-
- if isinstance(table_type, ast.TableType):
- return table_type.table if isinstance(table_type.table, TableModel) else None
- if isinstance(table_type, ast.TableAliasType):
- return EventsPrefilterTransformer._get_events_table(table_type.table_type)
- return None
-
- def cleanup_temp_schema_fields(self):
- for table, field_name in self._temp_schema_fields:
- if hasattr(table, "fields") and field_name in table.fields:
- del table.fields[field_name]
- self._temp_schema_fields.clear()
-
-
-class PrefilterHogQLHasMorePaginator(HogQLHasMorePaginator):
- """Paginator that applies the events prefilter AST transformation before execution."""
-
- def __init__(self, *, team_id: int, date_from: str, date_to: str, **kwargs):
- super().__init__(**kwargs)
- self.team_id = team_id
- self.date_from = date_from
- self.date_to = date_to
-
- @classmethod
- def create(
- cls,
- *,
- limit_context: LimitContext,
- team_id: int,
- date_from: str,
- date_to: str,
- limit: int | None = None,
- offset: int | None = None,
- ) -> PrefilterHogQLHasMorePaginator:
- from posthog.hogql.constants import get_default_limit_for_context, get_max_limit_for_context
-
- max_rows = get_max_limit_for_context(limit_context)
- default_rows = get_default_limit_for_context(limit_context)
- limit = min(max_rows, default_rows if (limit is None or limit <= 0) else limit)
- return cls(
- limit=limit,
- offset=offset,
- limit_context=limit_context,
- team_id=team_id,
- date_from=date_from,
- date_to=date_to,
- )
-
- def execute_hogql_query(
- self,
- query: Union[ast.SelectQuery, ast.SelectSetQuery],
- *,
- query_type: str,
- **kwargs,
- ) -> HogQLQueryResponse:
- from posthog.schema import HogQLQueryResponse
-
- from posthog.hogql.constants import get_default_hogql_global_settings
- from posthog.hogql.printer.utils import print_prepared_ast
- from posthog.hogql.query import HogQLQueryExecutor
-
- executor = HogQLQueryExecutor(
- query=self.paginate(query),
- query_type=query_type,
- **kwargs if self.limit_context is None else {"limit_context": self.limit_context, **kwargs},
- )
- executor._prepare_execution()
-
- if executor.clickhouse_prepared_ast is not None:
- transformer = EventsPrefilterTransformer(
- team_id=self.team_id,
- date_from=self.date_from,
- date_to=self.date_to,
- )
- try:
- transformer.visit(executor.clickhouse_prepared_ast)
-
- assert executor.clickhouse_context is not None
- settings = get_default_hogql_global_settings(executor.team.pk, executor.settings)
- executor.clickhouse_sql = print_prepared_ast(
- node=executor.clickhouse_prepared_ast,
- context=executor.clickhouse_context,
- dialect="clickhouse",
- settings=settings,
- pretty=True,
- )
- finally:
- transformer.cleanup_temp_schema_fields()
-
- executor._execute_clickhouse_query()
- self.response = HogQLQueryResponse(
- query=None,
- hogql=executor.hogql,
- clickhouse=executor.clickhouse_sql,
- results=executor.results,
- columns=executor.print_columns,
- types=executor.types,
- timings=executor.timings.to_list(),
- modifiers=executor.query_modifiers,
- )
- self.results = self.trim_results()
- return self.response
diff --git a/products/web_analytics/backend/hogql_queries/stats_table.py b/products/web_analytics/backend/hogql_queries/stats_table.py
index 40858acd57be..5f6bc858d068 100644
--- a/products/web_analytics/backend/hogql_queries/stats_table.py
+++ b/products/web_analytics/backend/hogql_queries/stats_table.py
@@ -29,9 +29,7 @@ from posthog.hogql.property import (
from posthog.clickhouse.query_tagging import clear_tag, get_query_tag_value
from posthog.hogql_queries.insights.paginators import HogQLHasMorePaginator
-from posthog.settings.data_stores import is_web_analytics_events_prefilter_team
-from products.web_analytics.backend.hogql_queries.events_prefilter import PrefilterHogQLHasMorePaginator
from products.web_analytics.backend.hogql_queries.stats_table_pre_aggregated import StatsTablePreAggregatedQueryBuilder
from products.web_analytics.backend.hogql_queries.stats_table_strategies import (
ChannelTypeStrategy,
@@ -93,22 +91,11 @@ class WebStatsTableQueryRunner(WebAnalyticsQueryRunner[WebStatsTableQueryRespons
limit = self.query.limit if self.query.limit else None
offset = self.query.offset if self.query.offset else None
- if is_web_analytics_events_prefilter_team(self.team.pk):
- date_from, date_to = self._events_prefilter_date_bounds()
- self.paginator = PrefilterHogQLHasMorePaginator.create(
- limit_context=LimitContext.QUERY,
- team_id=self.team.pk,
- date_from=date_from,
- date_to=date_to,
- limit=limit,
- offset=offset,
- )
- else:
- self.paginator = HogQLHasMorePaginator.from_limit_context(
- limit_context=LimitContext.QUERY,
- limit=limit,
- offset=offset,
- )
+ self.paginator = HogQLHasMorePaginator.from_limit_context(
+ limit_context=LimitContext.QUERY,
+ limit=limit,
+ offset=offset,
+ )
self.preaggregated_query_builder = StatsTablePreAggregatedQueryBuilder(self)
diff --git a/products/web_analytics/backend/hogql_queries/test/test_events_prefilter.py b/products/web_analytics/backend/hogql_queries/test/test_events_prefilter.py
deleted file mode 100644
index 81f7a9339534..000000000000
--- a/products/web_analytics/backend/hogql_queries/test/test_events_prefilter.py
+++ /dev/null
@@ -1,254 +0,0 @@
-from posthog.test.base import APIBaseTest, ClickhouseTestMixin, also_test_with_materialized_columns, materialized
-from unittest.mock import patch
-
-from posthog.schema import (
- DateRange,
- EventPropertyFilter,
- PersonPropertyFilter,
- PropertyOperator,
- WebStatsBreakdown,
- WebStatsTableQuery,
-)
-
-from posthog.hogql.context import HogQLContext
-from posthog.hogql.parser import parse_select
-from posthog.hogql.printer.utils import prepare_ast_for_printing, print_prepared_ast
-
-from products.web_analytics.backend.hogql_queries.events_prefilter import EventsPrefilterTransformer
-from products.web_analytics.backend.hogql_queries.stats_table import WebStatsTableQueryRunner
-
-
-class TestEventsPrefilterTransformer(ClickhouseTestMixin, APIBaseTest):
- def _run_prefiltered_query(self, **query_kwargs):
- query_kwargs.setdefault("properties", [])
- query_kwargs.setdefault("breakdownBy", WebStatsBreakdown.PAGE)
- query = WebStatsTableQuery(
- dateRange=DateRange(date_from="2024-01-01", date_to="2024-01-31"),
- **query_kwargs,
- )
- with patch(
- "products.web_analytics.backend.hogql_queries.stats_table.is_web_analytics_events_prefilter_team",
- return_value=True,
- ):
- runner = WebStatsTableQueryRunner(team=self.team, query=query)
- runner.calculate()
- assert runner.paginator.response is not None
- return runner.paginator.response.clickhouse or ""
-
- def test_bounce_query_wraps_from_events(self):
- sql = self._run_prefiltered_query(includeBounceRate=True)
-
- assert "toDate(events.timestamp)" in sql
- assert sql.count("toDate(events.timestamp)") >= 2 # at least one FROM events wrapped
-
- def test_avg_time_query_wraps_from_events(self):
- sql = self._run_prefiltered_query(includeAvgTimeOnPage=True)
-
- assert "toDate(events.timestamp)" in sql
-
- def test_prefilter_includes_team_id(self):
- sql = self._run_prefiltered_query(includeBounceRate=True)
-
- assert f"equals(events.team_id, {self.team.pk})" in sql
-
- def test_prefilter_date_bounds_have_buffer(self):
- query = WebStatsTableQuery(
- dateRange=DateRange(date_from="2024-01-01", date_to="2024-01-31"),
- properties=[],
- breakdownBy=WebStatsBreakdown.PAGE,
- includeBounceRate=True,
- )
- with patch(
- "products.web_analytics.backend.hogql_queries.stats_table.is_web_analytics_events_prefilter_team",
- return_value=True,
- ):
- runner = WebStatsTableQueryRunner(team=self.team, query=query)
- date_from, date_to = runner._events_prefilter_date_bounds()
-
- # Date range is Jan 1-31, buffer is ±1 day
- assert date_from == "2023-12-31"
- assert date_to == "2024-02-01"
-
- def test_prefilter_with_event_filter(self):
- query = WebStatsTableQuery(
- dateRange=DateRange(date_from="2024-01-01", date_to="2024-01-31"),
- properties=[
- EventPropertyFilter(
- key="$geoip_city_name",
- operator=PropertyOperator.EXACT,
- value=["Pretoria"],
- )
- ],
- breakdownBy=WebStatsBreakdown.PAGE,
- includeBounceRate=True,
- )
- with patch(
- "products.web_analytics.backend.hogql_queries.stats_table.is_web_analytics_events_prefilter_team",
- return_value=True,
- ):
- runner = WebStatsTableQueryRunner(team=self.team, query=query)
- runner.calculate()
- assert runner.paginator.response is not None
- sql = runner.paginator.response.clickhouse or ""
-
- assert "toDate(events.timestamp)" in sql
-
- def test_non_prefiltered_team_unchanged(self):
- query = WebStatsTableQuery(
- dateRange=DateRange(date_from="2024-01-01", date_to="2024-01-31"),
- properties=[],
- breakdownBy=WebStatsBreakdown.PAGE,
- includeBounceRate=True,
- )
- with patch(
- "products.web_analytics.backend.hogql_queries.stats_table.is_web_analytics_events_prefilter_team",
- return_value=False,
- ):
- runner = WebStatsTableQueryRunner(team=self.team, query=query)
- runner.calculate()
- assert runner.paginator.response is not None
- sql = runner.paginator.response.clickhouse or ""
-
- assert "toDate(events.timestamp)" not in sql
-
- def test_main_query_without_bounce_not_affected(self):
- query = WebStatsTableQuery(
- dateRange=DateRange(date_from="2024-01-01", date_to="2024-01-31"),
- properties=[],
- breakdownBy=WebStatsBreakdown.DEVICE_TYPE,
- )
- with patch(
- "products.web_analytics.backend.hogql_queries.stats_table.is_web_analytics_events_prefilter_team",
- return_value=True,
- ):
- runner = WebStatsTableQueryRunner(team=self.team, query=query)
- runner.calculate()
- assert runner.paginator.response is not None
- sql = runner.paginator.response.clickhouse or ""
-
- # Non-bounce queries also get wrapped since they go through the same _calculate path
- assert "toDate(events.timestamp)" in sql
-
- @also_test_with_materialized_columns(
- event_properties=["$pathname", "$geoip_city_name"],
- verify_no_jsonextract=False,
- )
- def test_bounce_with_geo_filter(self):
- sql = self._run_prefiltered_query(
- includeBounceRate=True,
- properties=[
- EventPropertyFilter(
- key="$geoip_city_name",
- operator=PropertyOperator.EXACT,
- value=["Pretoria"],
- )
- ],
- )
-
- assert "toDate(events.timestamp)" in sql
- assert sql.count("toDate(events.timestamp)") >= 2
-
- def test_bounce_with_non_utc_timezone(self):
- self.team.timezone = "Europe/Berlin"
- self.team.save()
-
- sql = self._run_prefiltered_query(includeBounceRate=True)
-
- assert "toDate(events.timestamp)" in sql
- assert sql.count("toDate(events.timestamp)") >= 2
-
- def test_bounce_with_unmaterialized_property_filter(self):
- sql = self._run_prefiltered_query(
- includeBounceRate=True,
- properties=[
- EventPropertyFilter(
- key="customProperty",
- operator=PropertyOperator.EXACT,
- value=["1"],
- )
- ],
- )
-
- assert "toDate(events.timestamp)" in sql
- # properties blob must be in the subquery for JSONExtractRaw
- assert "events.properties" in sql
- assert "JSONExtractRaw(events.properties," in sql
-
- def test_bounce_with_materialized_event_property_filter(self):
- # Property resolution rewrites a materialized property read to a synthetic mat_* column the HogQL schema
- # doesn't know about; the prefilter subquery must still SELECT that column or the outer query fails with
- # UNKNOWN_IDENTIFIER. Executes against ClickHouse, so a missing column fails the query itself.
- with materialized("events", "customProperty"):
- sql = self._run_prefiltered_query(
- includeBounceRate=True,
- properties=[
- EventPropertyFilter(
- key="customProperty",
- operator=PropertyOperator.EXACT,
- value=["1"],
- )
- ],
- )
-
- assert "mat_customProperty" in sql
- assert sql.count("mat_customProperty") >= 2, (
- "subquery must SELECT the materialized column the outer query reads"
- )
-
- def test_deep_key_read_off_materialized_column_kept_in_subquery(self):
- # A deep read (properties.customProperty.bar) through a materialized column becomes a JSON extract over the
- # synthetic mat_* column; the transformer must keep that column in the prefilter subquery.
- with materialized("events", "customProperty"):
- context = HogQLContext(team_id=self.team.pk, enable_select_queries=True)
- node = parse_select("SELECT count() FROM events WHERE properties.customProperty.bar = 'x'")
- prepared = prepare_ast_for_printing(node, context=context, dialect="clickhouse", stack=[])
- assert prepared is not None
- transformer = EventsPrefilterTransformer(team_id=self.team.pk, date_from="2024-01-01", date_to="2024-01-02")
- try:
- transformer.visit(prepared)
- assert transformer.wraps_applied == 1
- sql = print_prepared_ast(prepared, context=context, dialect="clickhouse")
- finally:
- transformer.cleanup_temp_schema_fields()
-
- assert sql.count("mat_customProperty") >= 2, (
- "subquery must SELECT the materialized column the outer query reads"
- )
-
- @also_test_with_materialized_columns(
- person_properties=["email"],
- verify_no_jsonextract=False,
- )
- def test_bounce_with_person_property_filter(self):
- from posthog.schema import PersonsOnEventsMode
-
- self.team.modifiers = {"personsOnEventsMode": PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_ON_EVENTS}
- self.team.save()
-
- sql = self._run_prefiltered_query(
- includeBounceRate=True,
- properties=[
- PersonPropertyFilter(
- key="email",
- operator=PropertyOperator.IS_NOT,
- value=["[email protected]"],
- )
- ],
- )
-
- assert "toDate(events.timestamp)" in sql
- # When materialized with PoE, mat_pp_email must be in the prefilter subquery
- # SELECT — if missing, the query above would fail with UNKNOWN_IDENTIFIER.
- # Also verify it appears in the generated SQL for the materialized case.
- if "mat_pp_email" in sql:
- assert sql.count("mat_pp_email") >= 2, (
- "mat_pp_email should appear in both the subquery SELECT and outer WHERE"
- )
-
- def test_initial_page_breakdown_with_bounce(self):
- sql = self._run_prefiltered_query(
- includeBounceRate=True,
- breakdownBy=WebStatsBreakdown.INITIAL_PAGE,
- )
-
- assert "toDate(events.timestamp)" in sql
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_stats_table.py b/products/web_analytics/backend/hogql_queries/test/test_web_stats_table.py
index 7b36a18371a2..39ef8ae58742 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_stats_table.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_stats_table.py
@@ -12,7 +12,6 @@ from posthog.test.base import (
flush_persons_and_events,
snapshot_clickhouse_queries,
)
-from unittest.mock import patch
from django.test import override_settings
@@ -84,15 +83,6 @@ class FloatAwareTestCase(unittest.TestCase):
class TestWebStatsTableQueryRunner(ClickhouseTestMixin, APIBaseTest, FloatAwareTestCase):
QUERY_TIMESTAMP = "2025-01-29"
- def setUp(self):
- super().setUp()
- patcher = patch(
- "products.web_analytics.backend.hogql_queries.stats_table.is_web_analytics_events_prefilter_team",
- return_value=False,
- )
- patcher.start()
- self.addCleanup(patcher.stop)
-
def _calculate_pageview_statistics(self, groups_of_pageviews: list[list[PageViewProperties]]):
per_path_durations: defaultdict[Any, list] = defaultdict(list)
total_view_counts: defaultdict[Any, int] = defaultdict(int)
diff --git a/products/web_analytics/backend/hogql_queries/web_analytics_query_runner.py b/products/web_analytics/backend/hogql_queries/web_analytics_query_runner.py
index 923e6ba3903d..6d4e03d2c799 100644
--- a/products/web_analytics/backend/hogql_queries/web_analytics_query_runner.py
+++ b/products/web_analytics/backend/hogql_queries/web_analytics_query_runner.py
@@ -683,20 +683,6 @@ WHERE
original = super().get_cache_key()
return f"{original}_{self.team.path_cleaning_filters}"
- def _events_prefilter_date_bounds(self) -> tuple[str, str]:
- lower = self.query_date_range.date_from()
- upper = self.query_date_range.date_to()
-
- if self.query_compare_to_date_range:
- lower = min(lower, self.query_compare_to_date_range.date_from())
- upper = max(upper, self.query_compare_to_date_range.date_to())
-
- utc = ZoneInfo("UTC")
- date_from = (lower.astimezone(utc) - timedelta(days=1)).strftime("%Y-%m-%d")
- date_to = (upper.astimezone(utc) + timedelta(days=1)).strftime("%Y-%m-%d")
-
- return date_from, date_to
-
@cached_property
def events_session_property(self):
# we should delete this once SessionsV2JoinMode is always uuid, eventually we will always use $session_id_uuid