: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): rewrite drill-down filters to first-pageview (#76004)
Jordan Mryyan83d6cc09998e
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 9f7f0edef5e1..d22b63b58618 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -26917,6 +26917,10 @@},"useWebAnalyticsPreAggregatedTables": {"type": "boolean"+ },+ "webAnalyticsFirstPageviewFilters": {+ "description": "Serve filters on the stored session-entry attribution properties (`$channel_type`, `$entry_utm_*`, `$entry_referring_domain`) by recomputing the value from the session's first pageview. Resolved server-side; not intended to be set by clients.",+ "type": "boolean"}},"type": "object"diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 0a1b7df43b2f..aae24ad17475 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -495,6 +495,8 @@ export interface HogQLQueryModifiers {useMaterializedViews?: booleancustomChannelTypeRules?: CustomChannelRule[]useWebAnalyticsPreAggregatedTables?: boolean+ /** Serve filters on the stored session-entry attribution properties (`$channel_type`, `$entry_utm_*`, `$entry_referring_domain`) by recomputing the value from the session's first pageview. Resolved server-side; not intended to be set by clients. */+ webAnalyticsFirstPageviewFilters?: booleanformatCsvAllowDoubleQuotes?: booleanconvertToProjectTimezone?: boolean/** Try to automatically convert HogQL queries to use preaggregated tables at the AST level **/diff --git a/posthog/hogql_queries/insights/trends/calendar_heatmap_query_runner.py b/posthog/hogql_queries/insights/trends/calendar_heatmap_query_runner.pyindex 3f04ec654b0e..8a50832c4cc7 100644--- a/posthog/hogql_queries/insights/trends/calendar_heatmap_query_runner.py+++ b/posthog/hogql_queries/insights/trends/calendar_heatmap_query_runner.py@@ -44,6 +44,9 @@ from posthog.models.user import Userfrom products.actions.backend.models.action import Actionfrom products.event_definitions.backend.models.property_definition import PropertyDefinition+from products.web_analytics.backend.hogql_queries.first_pageview_attribution import (+ first_pageview_aware_properties_to_expr,+)SEPARATOR = "','"@@ -302,19 +305,29 @@ class CalendarHeatmapQueryRunner(AnalyticsQueryRunner[CalendarHeatmapResponse]):else:return ast.Constant(value=True)+ def _properties_to_expr(self, properties: Any) -> ast.Expr:+ # The Active Hours tiles pass the web analytics drill-down filter on the series.+ return first_pageview_aware_properties_to_expr(+ properties,+ team=self.team,+ modifiers=self.modifiers,+ date_range=self.query_date_range,+ timings=self.timings,+ )+def _all_properties(self) -> ast.Expr:# Collect all property expressionsproperty_exprs = []# Add top-level properties if they existif self.query.properties is not None and self.query.properties != []:- property_exprs.append(property_to_expr(self.query.properties, team=self.team))+ property_exprs.append(self._properties_to_expr(self.query.properties))# Add series-level properties if they exist (from the first series)if self.query.series and len(self.query.series) > 0:series = self.query.series[0]if hasattr(series, "properties") and series.properties is not None and series.properties != []:- property_exprs.append(property_to_expr(series.properties, team=self.team))+ property_exprs.append(self._properties_to_expr(series.properties))if len(property_exprs) == 0:return ast.Constant(value=True)diff --git a/posthog/hogql_queries/insights/trends/trends_actors_query_builder.py b/posthog/hogql_queries/insights/trends/trends_actors_query_builder.pyindex 32cc644b227d..30501eb07e06 100644--- a/posthog/hogql_queries/insights/trends/trends_actors_query_builder.py+++ b/posthog/hogql_queries/insights/trends/trends_actors_query_builder.py@@ -38,6 +38,9 @@ from posthog.hogql_queries.utils.query_previous_period_date_range import QueryPrfrom posthog.models import Teamfrom products.actions.backend.models.action import Action+from products.web_analytics.backend.hogql_queries.first_pageview_attribution import (+ first_pageview_aware_properties_to_expr,+)class TrendsActorsQueryBuilder:@@ -384,7 +387,18 @@ class TrendsActorsQueryBuilder:# Propertiesif self.trends_query.properties is not None and self.trends_query.properties != []:- conditions.append(property_to_expr(self.trends_query.properties, self.team))+ conditions.append(+ first_pageview_aware_properties_to_expr(+ self.trends_query.properties,+ team=self.team,+ modifiers=self.modifiers,+ # Mirrors `_date_where_expr`: on the previous-period side the+ # session's first pageview has to be looked for in that+ # period, or the modal drops actors the graph point counted.+ date_range=self.trends_previous_date_range if self.is_compare_previous else self.trends_date_range,+ timings=self.timings,+ )+ )return conditionsdiff --git a/posthog/hogql_queries/insights/trends/trends_query_builder.py b/posthog/hogql_queries/insights/trends/trends_query_builder.pyindex 2a28ddc409c7..9c27ad1c4ed6 100644--- a/posthog/hogql_queries/insights/trends/trends_query_builder.py+++ b/posthog/hogql_queries/insights/trends/trends_query_builder.py@@ -1,4 +1,4 @@-from typing import cast+from typing import Any, castfrom posthog.schema import (ActionsNode,@@ -29,6 +29,9 @@ from posthog.models.team.team import Teamfrom posthog.ph_client import feature_enabled_or_falsefrom products.actions.backend.models.action import Action+from products.web_analytics.backend.hogql_queries.first_pageview_attribution import (+ first_pageview_aware_properties_to_expr,+)class TrendsQueryBuilder(DataWarehouseInsightQueryMixin):@@ -834,11 +837,11 @@ class TrendsQueryBuilder(DataWarehouseInsightQueryMixin):# Propertiesif self.query.properties is not None and self.query.properties != []:- filters.append(property_to_expr(self.query.properties, self.team))+ filters.append(self._properties_to_expr(self.query.properties))# Series Filtersif series.properties is not None and series.properties != []:- filters.append(property_to_expr(series.properties, self.team))+ filters.append(self._properties_to_expr(series.properties))# Breakdownif not ignore_breakdowns and breakdown is not None:@@ -862,6 +865,16 @@ class TrendsQueryBuilder(DataWarehouseInsightQueryMixin):return ast.And(exprs=filters)+ def _properties_to_expr(self, properties: Any) -> ast.Expr:+ # Web analytics passes its drill-down filter at both query and series level.+ return first_pageview_aware_properties_to_expr(+ properties,+ team=self.team,+ modifiers=self.modifiers,+ date_range=self.query_date_range,+ timings=self.timings,+ )+def _event_or_action_where_expr(self) -> ast.Expr | None:if isinstance(self.series, EventsNode):return self._get_event_expr(self.series)diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.pyindex 67a311ae0dc9..79152ee03778 100644--- a/posthog/hogql_queries/query_runner.py+++ b/posthog/hogql_queries/query_runner.py@@ -151,6 +151,8 @@ from posthog.slo.types import SloArea, SloOperation, SloOutcomefrom posthog.synthetic_user import SyntheticUserfrom posthog.utils import generate_cache_key, get_from_dict_or_attr, to_json+from products.web_analytics.backend.hogql_queries.first_pageview_flag import resolve_first_pageview_filters_modifier+QUERY_EXECUTION_TOTAL = Counter("posthog_query_execution_total","Query executions by category",@@ -1410,6 +1412,9 @@ class QueryRunner(ABC, Generic[Q, R, CR]):_modifiers = modifiers or extract_modifiers(query)self.modifiers = create_default_modifiers_for_team(team, _modifiers)self.query = query+ self.modifiers.webAnalyticsFirstPageviewFilters = resolve_first_pageview_filters_modifier(+ query, team, self.modifiers.webAnalyticsFirstPageviewFilters+ )self.__post_init__()def __post_init__(self):diff --git a/posthog/schema.py b/posthog/schema.pyindex 5701ab39d452..a7ee2d665a98 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -5153,6 +5153,15 @@ class HogQLQueryModifiers(BaseModel):description=("Try to automatically convert HogQL queries to use preaggregated tables at the AST level *"),)useWebAnalyticsPreAggregatedTables: bool | None = None+ webAnalyticsFirstPageviewFilters: bool | None = Field(+ default=None,+ description=(+ "Serve filters on the stored session-entry attribution properties"+ " (`$channel_type`, `$entry_utm_*`, `$entry_referring_domain`) by"+ " recomputing the value from the session's first pageview. Resolved"+ " server-side; not intended to be set by clients."+ ),+ )class HogQuery(BaseModel):diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.tsindex 296b5b144d5f..8329438fbe56 100644--- a/products/dashboards/frontend/generated/api.schemas.ts+++ b/products/dashboards/frontend/generated/api.schemas.ts@@ -1230,6 +1230,8 @@ export interface HogQLQueryModifiersApi {/** Try to automatically convert HogQL queries to use preaggregated tables at the AST level * */usePreaggregatedTableTransforms?: boolean | nulluseWebAnalyticsPreAggregatedTables?: boolean | null+ /** Serve filters on the stored session-entry attribution properties (`$channel_type`, `$entry_utm_*`, `$entry_referring_domain`) by recomputing the value from the session's first pageview. Resolved server-side; not intended to be set by clients. */+ webAnalyticsFirstPageviewFilters?: boolean | null}export interface EventPropertyFilterApi {diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.tsindex 9f2bed9dbbf9..0aa4a34bfb00 100644--- a/products/product_analytics/frontend/generated/api.schemas.ts+++ b/products/product_analytics/frontend/generated/api.schemas.ts@@ -519,6 +519,8 @@ export interface HogQLQueryModifiersApi {/** Try to automatically convert HogQL queries to use preaggregated tables at the AST level * */usePreaggregatedTableTransforms?: boolean | nulluseWebAnalyticsPreAggregatedTables?: boolean | null+ /** Serve filters on the stored session-entry attribution properties (`$channel_type`, `$entry_utm_*`, `$entry_referring_domain`) by recomputing the value from the session's first pageview. Resolved server-side; not intended to be set by clients. */+ webAnalyticsFirstPageviewFilters?: boolean | null}export type PropertyOperatorApi = (typeof PropertyOperatorApi)[keyof typeof PropertyOperatorApi]diff --git a/products/web_analytics/backend/hogql_queries/external_clicks.py b/products/web_analytics/backend/hogql_queries/external_clicks.pyindex b396d0a0ec64..442461b2797b 100644--- a/products/web_analytics/backend/hogql_queries/external_clicks.py+++ b/products/web_analytics/backend/hogql_queries/external_clicks.py@@ -13,7 +13,6 @@ from posthog.schema import (from posthog.hogql import astfrom posthog.hogql.constants import LimitContextfrom posthog.hogql.parser import parse_select-from posthog.hogql.property import property_to_exprfrom posthog.hogql_queries.insights.paginators import HogQLHasMorePaginator@@ -72,7 +71,7 @@ GROUP BY "context.columns.url"timings=self.timings,placeholders={"url_expr": url_expr,- "all_properties": self._all_properties(),+ "all_properties": self.all_properties(),"current_period": self._current_period_expression(),"previous_period": self._previous_period_expression(),"inside_periods": self._periods_expression(),@@ -110,10 +109,6 @@ GROUP BY "context.columns.url"if expr is not None]- def _all_properties(self) -> ast.Expr:- properties = self.query.properties + self._test_account_filters- return property_to_expr(properties, team=self.team)-def _calculate(self):query = self.to_query()response = self.paginator.execute_hogql_query(diff --git a/products/web_analytics/backend/hogql_queries/first_pageview_attribution.py b/products/web_analytics/backend/hogql_queries/first_pageview_attribution.pynew file mode 100644index 000000000000..e3b736525645--- /dev/null+++ b/products/web_analytics/backend/hogql_queries/first_pageview_attribution.py@@ -0,0 +1,276 @@+from typing import TYPE_CHECKING, Any, Optional, cast++from posthog.schema import HogQLQueryModifiers, PropertyOperator, SessionPropertyFilter, WebStatsBreakdown++from posthog.hogql import ast+from posthog.hogql.database.schema.channel_type import ChannelTypeExprs, create_channel_type_expr+from posthog.hogql.parser import parse_expr, parse_select+from posthog.hogql.property import _expr_to_compare_op, property_to_expr+from posthog.hogql.timings import HogQLTimings++from posthog.models.property import Property, ValueT++from products.web_analytics.backend.hogql_queries.first_pageview_flag import (+ SESSION_PROPERTY_TO_FIRST_PAGEVIEW,+ rewritable_session_filters,+)++if TYPE_CHECKING:+ from posthog.hogql_queries.utils.query_date_range import QueryDateRange+ from posthog.models import Team++# Flag-on, these Initial* breakdowns transparently compute first-pageview+# attribution instead of session-entry values. Filters on the session properties+# those rows produce are rewritten to match; see SESSION_PROPERTY_TO_FIRST_PAGEVIEW.+# The coverage is deliberately partial: the INITIAL_REFERRING_URL /+# INITIAL_PAGE breakdowns, the weekly digest, and every surface outside web+# analytics (saved insights, experiments, replay filters) keep entry semantics.+# The durable cross-surface fix is the raw_sessions v3 rollout.+# Note the flag only gates the remap: the FirstPageview* enum values are+# permanently live API surface and can be requested directly at 0% rollout.+INITIAL_TO_FIRST_PAGEVIEW = {+ WebStatsBreakdown.INITIAL_UTM_SOURCE: WebStatsBreakdown.FIRST_PAGEVIEW_UTM_SOURCE,+ WebStatsBreakdown.INITIAL_UTM_CAMPAIGN: WebStatsBreakdown.FIRST_PAGEVIEW_UTM_CAMPAIGN,+ WebStatsBreakdown.INITIAL_UTM_MEDIUM: WebStatsBreakdown.FIRST_PAGEVIEW_UTM_MEDIUM,+ WebStatsBreakdown.INITIAL_UTM_TERM: WebStatsBreakdown.FIRST_PAGEVIEW_UTM_TERM,+ WebStatsBreakdown.INITIAL_UTM_CONTENT: WebStatsBreakdown.FIRST_PAGEVIEW_UTM_CONTENT,+ WebStatsBreakdown.INITIAL_REFERRING_DOMAIN: WebStatsBreakdown.FIRST_PAGEVIEW_REFERRING_DOMAIN,+ WebStatsBreakdown.INITIAL_UTM_SOURCE_MEDIUM_CAMPAIGN: WebStatsBreakdown.FIRST_PAGEVIEW_UTM_SOURCE_MEDIUM_CAMPAIGN,+ WebStatsBreakdown.INITIAL_CHANNEL_TYPE: WebStatsBreakdown.FIRST_PAGEVIEW_CHANNEL_TYPE,+}++# Ordered property keys each FirstPageview* breakdown reads from the session's+# first pageview; the order defines the tuple element indexes used by+# first_pageview_prop.+FIRST_PAGEVIEW_BREAKDOWN_PROPERTIES: dict[WebStatsBreakdown, tuple[str, ...]] = {+ WebStatsBreakdown.FIRST_PAGEVIEW_UTM_SOURCE: ("utm_source",),+ WebStatsBreakdown.FIRST_PAGEVIEW_UTM_CAMPAIGN: ("utm_campaign",),+ WebStatsBreakdown.FIRST_PAGEVIEW_UTM_MEDIUM: ("utm_medium",),+ WebStatsBreakdown.FIRST_PAGEVIEW_UTM_TERM: ("utm_term",),+ WebStatsBreakdown.FIRST_PAGEVIEW_UTM_CONTENT: ("utm_content",),+ WebStatsBreakdown.FIRST_PAGEVIEW_REFERRING_DOMAIN: ("$referring_domain",),+ WebStatsBreakdown.FIRST_PAGEVIEW_UTM_SOURCE_MEDIUM_CAMPAIGN: (+ "utm_source",+ "$referring_domain",+ "utm_medium",+ "utm_campaign",+ ),+ WebStatsBreakdown.FIRST_PAGEVIEW_CHANNEL_TYPE: (+ "utm_campaign",+ "utm_medium",+ "utm_source",+ "$current_url",+ "$referring_domain",+ "gclid",+ "fbclid",+ "gad_source",+ ),+}++FIRST_PAGEVIEW_BREAKDOWNS = frozenset(FIRST_PAGEVIEW_BREAKDOWN_PROPERTIES)++PAGEVIEW_EVENTS_EXPR = "events.event IN ('$pageview', '$screen')"+++def first_pageview_property_keys(breakdown: WebStatsBreakdown) -> tuple[str, ...]:+ return FIRST_PAGEVIEW_BREAKDOWN_PROPERTIES[breakdown]+++def first_pageview_properties_expr(breakdown: WebStatsBreakdown) -> ast.Expr:+ """One argMinIf over a tuple: every property comes from the session's+ earliest in-range $pageview/$screen. The event filter keeps+ conversion-goal events (which share the scan) from winning the argMin,+ and the single anchor event prevents per-property NULL-skip from+ stitching values of different pageviews together."""+ return ast.Call(+ name="argMinIf",+ args=[+ ast.Tuple(+ exprs=[+ ast.Field(chain=["events", "properties", key]) for key in first_pageview_property_keys(breakdown)+ ]+ ),+ ast.Field(chain=["events", "timestamp"]),+ parse_expr(PAGEVIEW_EVENTS_EXPR),+ ],+ )+++def first_pageview_prop(breakdown: WebStatsBreakdown, key: str) -> ast.Expr:+ index = first_pageview_property_keys(breakdown).index(key) + 1+ return ast.Call(+ name="nullIf",+ args=[+ ast.Call(+ name="tupleElement",+ args=[ast.Field(chain=["first_pageview_properties"]), ast.Constant(value=index)],+ ),+ ast.Constant(value=""),+ ],+ )+++def first_pageview_channel_type_expr(+ modifiers: Optional[HogQLQueryModifiers] = None,+ timings: Optional[HogQLTimings] = None,+) -> ast.Expr:+ breakdown = WebStatsBreakdown.FIRST_PAGEVIEW_CHANNEL_TYPE+ url = first_pageview_prop(breakdown, "$current_url")+ return create_channel_type_expr(+ modifiers.customChannelTypeRules if modifiers else None,+ ChannelTypeExprs(+ campaign=first_pageview_prop(breakdown, "utm_campaign"),+ medium=first_pageview_prop(breakdown, "utm_medium"),+ source=first_pageview_prop(breakdown, "utm_source"),+ url=url,+ hostname=ast.Call(name="domain", args=[url]),+ pathname=ast.Call(name="path", args=[url]),+ referring_domain=first_pageview_prop(breakdown, "$referring_domain"),+ has_gclid=ast.Call(name="isNotNull", args=[first_pageview_prop(breakdown, "gclid")]),+ has_fbclid=ast.Call(name="isNotNull", args=[first_pageview_prop(breakdown, "fbclid")]),+ gad_source=first_pageview_prop(breakdown, "gad_source"),+ ),+ timings=timings,+ )+++def first_pageview_filter_value_expr(+ breakdown: WebStatsBreakdown,+ modifiers: Optional[HogQLQueryModifiers] = None,+ timings: Optional[HogQLTimings] = None,+) -> ast.Expr:+ """Value expression a rewritten session-property filter compares against.++ Must stay identical to the breakdown's own value expression, because a filter+ built from a different expression silently selects a different set of sessions+ than the row the user clicked.+ """+ if breakdown == WebStatsBreakdown.FIRST_PAGEVIEW_CHANNEL_TYPE:+ return first_pageview_channel_type_expr(modifiers=modifiers, timings=timings)++ keys = first_pageview_property_keys(breakdown)+ if len(keys) != 1:+ raise ValueError(f"{breakdown} has no single-property filter equivalent")+ return first_pageview_prop(breakdown, keys[0])+++def first_pageview_session_filter_expr(+ prop: SessionPropertyFilter,+ *,+ team: "Team",+ inside_periods: ast.Expr,+ event_where: Optional[ast.Expr] = None,+ session_id_present: Optional[ast.Expr] = None,+ outer_session_id: Optional[ast.Expr] = None,+ modifiers: Optional[HogQLQueryModifiers] = None,+ timings: Optional[HogQLTimings] = None,+) -> ast.Expr:+ """Match sessions whose *first pageview* carries the filtered value.++ The stored `$entry_*` / `$channel_type` session fields come from raw_sessions+ v2, which attributes a session to its earliest event of any kind, so a+ non-pageview fired before the first pageview blanks them. A breakdown row+ computed from the first pageview therefore has no stored property that+ reproduces it, and every surface applying the row-click filter has to+ recompute the same value here.++ ClickHouse turns the plain `IN` into a `GLOBAL IN` under+ `distributed_product_mode=global`, so the id set is collected once on the+ initiator rather than re-derived per shard.+ """+ breakdown = SESSION_PROPERTY_TO_FIRST_PAGEVIEW[prop.key]+ matching_sessions = parse_select(+ """+SELECT session_id+FROM (+ SELECT+ events.$session_id AS session_id,+ {first_pageview_properties} AS first_pageview_properties+ FROM events+ WHERE and({inside_periods}, {event_where}, {session_id_present})+ GROUP BY session_id+)+WHERE {match}+ """,+ placeholders={+ "first_pageview_properties": first_pageview_properties_expr(breakdown),+ "inside_periods": inside_periods,+ "event_where": event_where if event_where is not None else parse_expr(PAGEVIEW_EVENTS_EXPR),+ # Sessionless events cannot hold a session's first pageview, and+ # letting them group under a NULL session id would build one bogus+ # bucket out of every unrelated event.+ "session_id_present": (+ session_id_present+ if session_id_present is not None+ else parse_expr("events.$session_id_uuid IS NOT NULL")+ ),+ "match": _expr_to_compare_op(+ expr=first_pageview_filter_value_expr(breakdown, modifiers=modifiers, timings=timings),+ value=cast(ValueT, prop.value),+ operator=prop.operator or PropertyOperator.EXACT,+ property=Property(+ key=prop.key,+ value=cast(ValueT, prop.value),+ operator=cast(Any, prop.operator),+ type="session",+ ),+ is_json_field=False,+ team=team,+ ),+ },+ )+ return ast.CompareOperation(+ op=ast.CompareOperationOp.In,+ # Unqualified by default because callers apply this against differently+ # aliased events tables (trends aliases it `e`), and the alias is not+ # knowable here. Callers whose scope has more than one table carrying a+ # session id must pass the qualified field.+ left=outer_session_id if outer_session_id is not None else ast.Field(chain=["$session_id"]),+ right=matching_sessions,+ )+++def first_pageview_aware_properties_to_expr(+ properties: Any,+ *,+ team: "Team",+ modifiers: Optional[HogQLQueryModifiers],+ date_range: "QueryDateRange",+ timings: Optional[HogQLTimings] = None,+) -> ast.Expr:+ """`property_to_expr`, with session-entry attribution filters rewritten.++ Trends-backed web analytics tiles (the visitors graph, the graph view of a+ breakdown tile, web vitals) share the scene's filter list with the tiles the+ web analytics runners serve. Without this they resolve `$channel_type` and+ friends against raw_sessions v2 and select a different population than the+ row that was clicked, so one drilled-down scene shows two different totals.++ Off unless the `webAnalyticsFirstPageviewFilters` modifier is set; see+ `resolve_first_pageview_filters_modifier`.+ """+ rewritable = rewritable_session_filters(properties)+ if not (modifiers and modifiers.webAnalyticsFirstPageviewFilters) or not rewritable:+ return property_to_expr(properties, team)++ inside_periods = parse_expr(+ "timestamp >= {date_from} AND timestamp <= {date_to}",+ placeholders={"date_from": date_range.date_from_as_hogql(), "date_to": date_range.date_to_as_hogql()},+ )+ # The rewritten filters are dropped from the list rather than swapped in place+ # because callers route filters by `get_property_type`, which a raw expression+ # has no answer for; leaving them in would also apply the stored entry+ # attribution.+ rewritten_ids = {id(p) for p in rewritable}+ return property_to_expr(+ [+ *(p for p in properties if id(p) not in rewritten_ids),+ *(+ first_pageview_session_filter_expr(+ p, team=team, inside_periods=inside_periods, modifiers=modifiers, timings=timings+ )+ for p in rewritable+ ),+ ],+ team,+ )diff --git a/products/web_analytics/backend/hogql_queries/first_pageview_flag.py b/products/web_analytics/backend/hogql_queries/first_pageview_flag.pynew file mode 100644index 000000000000..c7317d91c2ab--- /dev/null+++ b/products/web_analytics/backend/hogql_queries/first_pageview_flag.py@@ -0,0 +1,130 @@+from typing import TYPE_CHECKING, Any, Optional++import structlog+import posthoganalytics++from posthog.schema import ProductKey, SessionPropertyFilter, WebStatsBreakdown++if TYPE_CHECKING:+ from posthog.models import Team++logger = structlog.get_logger(__name__)++FIRST_PAGEVIEW_ATTRIBUTION_FEATURE_FLAG = "web-analytics-first-pageview-attribution"++# Stored session properties the row-click drill-downs filter on, mapped to the+# FirstPageview* breakdown whose value expression reproduces them. Flag-on, a+# filter on one of these is rewritten to match first-pageview attribution so a+# drilled-down tile reconciles with the breakdown row that produced it.+# $entry_utm_source_medium_campaign has no entry here on purpose: the compound+# breakdown is not filterable, the UI splits a click on it into separate+# source / medium / campaign filters, each of which is remapped individually.+SESSION_PROPERTY_TO_FIRST_PAGEVIEW: dict[str, WebStatsBreakdown] = {+ "$channel_type": WebStatsBreakdown.FIRST_PAGEVIEW_CHANNEL_TYPE,+ "$entry_utm_source": WebStatsBreakdown.FIRST_PAGEVIEW_UTM_SOURCE,+ "$entry_utm_campaign": WebStatsBreakdown.FIRST_PAGEVIEW_UTM_CAMPAIGN,+ "$entry_utm_medium": WebStatsBreakdown.FIRST_PAGEVIEW_UTM_MEDIUM,+ "$entry_utm_term": WebStatsBreakdown.FIRST_PAGEVIEW_UTM_TERM,+ "$entry_utm_content": WebStatsBreakdown.FIRST_PAGEVIEW_UTM_CONTENT,+ "$entry_referring_domain": WebStatsBreakdown.FIRST_PAGEVIEW_REFERRING_DOMAIN,+}+++def evaluate_team_rollout_flag(team: "Team", flag_key: str, failure_log_event: str) -> bool:+ """Evaluate a team-scoped rollout flag locally, failing closed on flag-service errors.++ A raised exception here must never fail the query: evaluation failure degrades+ to the flag-off path. For optimization flags that is merely the slower query+ shape; for result-changing flags (first-pageview attribution) it silently+ restores the old semantics, so both the exception and the None-return cases+ (local evaluation unavailable) are logged to keep a fleet-wide fallback+ visible during rollout.++ Conditions on this flag must be group conditions, never person or cohort+ ones: the distinct id passed here is a team uuid with no person behind it,+ so a person-scoped condition is unresolvable locally, returns None, and the+ flag silently evaluates to False for everyone.+ """+ try:+ enabled = posthoganalytics.feature_enabled(+ flag_key,+ str(team.uuid),+ groups={+ "organization": str(team.organization_id),+ "project": str(team.id),+ },+ group_properties={+ "organization": {"id": str(team.organization_id)},+ "project": {"id": str(team.id)},+ },+ only_evaluate_locally=True,+ send_feature_flag_events=False,+ )+ if enabled is None:+ logger.warning(failure_log_event, reason="feature_enabled_returned_none", team_id=team.pk)+ return False+ return bool(enabled)+ except Exception as e:+ logger.warning(failure_log_event, error=e, team_id=team.pk)+ return False+++def first_pageview_attribution_enabled(team: "Team") -> bool:+ return evaluate_team_rollout_flag(+ team, FIRST_PAGEVIEW_ATTRIBUTION_FEATURE_FLAG, "web_analytics_first_pageview_attribution_flag_failed"+ )+++def rewritable_session_filters(properties: Any) -> list[SessionPropertyFilter]:+ # `properties` is a flat list on every web analytics query, but the shared+ # insight schema also allows a nested PropertyGroupFilter, which is not+ # iterable. Anything that is not a plain list is left untouched rather than+ # walked, so an unexpected shape degrades to entry attribution instead of+ # raising while the query is being built.+ if not isinstance(properties, list):+ return []+ return [+ p for p in properties if isinstance(p, SessionPropertyFilter) and p.key in SESSION_PROPERTY_TO_FIRST_PAGEVIEW+ ]+++def is_web_analytics_query(query: Any) -> bool:+ """Read from the query's own tags rather than the ambient ClickHouse query+ tags because `get_cache_payload` strips `tags` before hashing, so the+ decision has to be reachable from the query object at cache-key time.+ """+ tags = getattr(query, "tags", None)+ return getattr(tags, "productKey", None) == ProductKey.WEB_ANALYTICS+++def query_has_rewritable_session_filters(query: Any) -> bool:+ """Web analytics puts the scene's filters at query level on most tiles but on+ the series for the Active Hours tiles, so both levels count.+ """+ if rewritable_session_filters(getattr(query, "properties", None)):+ return True+ return any(+ rewritable_session_filters(getattr(series, "properties", None))+ for series in (getattr(query, "series", None) or [])+ )+++def resolve_first_pageview_filters_modifier(query: Any, team: "Team", current: Optional[bool]) -> Optional[bool]:+ """Effective value of the `webAnalyticsFirstPageviewFilters` modifier.++ The decision has to live on the modifier because `get_cache_payload` hashes+ `hogql_modifiers`: entry-attributed and first-pageview runs of the same query+ must not share a cache entry.++ The guards run before the flag so no other query pays a flag-service call.+ """+ if current is not None:+ return current+ if not is_web_analytics_query(query):+ return None+ if not query_has_rewritable_session_filters(query):+ return None+ # None rather than False when the flag is off: `to_dict` drops None but keeps+ # False, so returning False would change the cache key of every drilled-down+ # web analytics query even when no rewrite is applied.+ return True if first_pageview_attribution_enabled(team) else Nonediff --git a/products/web_analytics/backend/hogql_queries/notable_changes.py b/products/web_analytics/backend/hogql_queries/notable_changes.pyindex 57f92defb035..f4bdf87e5f7a 100644--- a/products/web_analytics/backend/hogql_queries/notable_changes.py+++ b/products/web_analytics/backend/hogql_queries/notable_changes.py@@ -14,7 +14,6 @@ from posthog.schema import (from posthog.hogql import astfrom posthog.hogql.database.schema.channel_type import wrap_with_null_if_empty-from posthog.hogql.property import property_to_exprfrom posthog.hogql.query import execute_hogql_queryfrom products.web_analytics.backend.hogql_queries.pre_aggregated.properties import STATS_TABLE_SUPPORTED_FILTERS@@ -126,10 +125,7 @@ class WebNotableChangesQueryRunner(WebAnalyticsQueryRunner[WebNotableChangesQuerreturn Nonedef _raw_events_query(self) -> Union[ast.SelectQuery, ast.SelectSetQuery]:- all_properties = property_to_expr(- [*self.query.properties, *self._test_account_filters],- team=self.team,- )+ all_properties = self.all_properties()periods = self._periods_expression("timestamp")current_period = self._current_period_expression("start_timestamp")previous_period = self._previous_period_expression("start_timestamp")diff --git a/products/web_analytics/backend/hogql_queries/pre_aggregated/query_builder.py b/products/web_analytics/backend/hogql_queries/pre_aggregated/query_builder.pyindex ee737283f774..84e4714dc567 100644--- a/products/web_analytics/backend/hogql_queries/pre_aggregated/query_builder.py+++ b/products/web_analytics/backend/hogql_queries/pre_aggregated/query_builder.py@@ -31,6 +31,9 @@ class WebAnalyticsPreAggregatedQueryBuilder:def can_use_preaggregated_tables(self) -> bool:query = self.runner.query+ if self.runner.rewritten_first_pageview_filters:+ return False+for prop in query.properties:if hasattr(prop, "type") and prop.type == "cohort":return Falsediff --git a/products/web_analytics/backend/hogql_queries/stats_table.py b/products/web_analytics/backend/hogql_queries/stats_table.pyindex 21b3b1a14e83..bbfa918e01e1 100644--- a/products/web_analytics/backend/hogql_queries/stats_table.py+++ b/products/web_analytics/backend/hogql_queries/stats_table.py@@ -18,7 +18,6 @@ from posthog.schema import (from posthog.hogql import astfrom posthog.hogql.constants import LimitContext-from posthog.hogql.database.schema.channel_type import ChannelTypeExprs, create_channel_type_exprfrom posthog.hogql.parser import parse_expr, parse_selectfrom posthog.hogql.property import (get_property_key,@@ -33,6 +32,13 @@ from posthog.clickhouse.query_tagging import clear_tag, get_query_tag_valuefrom posthog.hogql_queries.insights.paginators import HogQLHasMorePaginatorfrom posthog.models.filters.mixins.utils import cached_property+from products.web_analytics.backend.hogql_queries.first_pageview_attribution import (+ FIRST_PAGEVIEW_BREAKDOWNS,+ INITIAL_TO_FIRST_PAGEVIEW,+ first_pageview_filter_value_expr,+ first_pageview_prop,+ first_pageview_properties_expr,+)from products.web_analytics.backend.hogql_queries.stats_table_pre_aggregated import StatsTablePreAggregatedQueryBuilderfrom products.web_analytics.backend.hogql_queries.stats_table_strategies import (ChannelTypeStrategy,@@ -66,56 +72,6 @@ from products.web_analytics.backend.hogql_queries.web_stats_paths_lazy_precomputBREAKDOWN_NULL_DISPLAY = "(none)"BREAKDOWN_REFERRER_PREFIX = "referrer:"-FIRST_PAGEVIEW_ATTRIBUTION_FEATURE_FLAG = "web-analytics-first-pageview-attribution"--# Flag-on, these Initial* breakdowns transparently compute first-pageview-# attribution instead of session-entry values. The remap is deliberately-# partial: INITIAL_REFERRING_URL / INITIAL_PAGE, the Sources drill-downs,-# row-click session filters, overview tiles, and the weekly digest keep entry-# semantics — the durable cross-surface fix is the raw_sessions v3 rollout.-# Note the flag only gates the remap: the FirstPageview* enum values are-# permanently live API surface and can be requested directly at 0% rollout.-INITIAL_TO_FIRST_PAGEVIEW = {- WebStatsBreakdown.INITIAL_UTM_SOURCE: WebStatsBreakdown.FIRST_PAGEVIEW_UTM_SOURCE,- WebStatsBreakdown.INITIAL_UTM_CAMPAIGN: WebStatsBreakdown.FIRST_PAGEVIEW_UTM_CAMPAIGN,- WebStatsBreakdown.INITIAL_UTM_MEDIUM: WebStatsBreakdown.FIRST_PAGEVIEW_UTM_MEDIUM,- WebStatsBreakdown.INITIAL_UTM_TERM: WebStatsBreakdown.FIRST_PAGEVIEW_UTM_TERM,- WebStatsBreakdown.INITIAL_UTM_CONTENT: WebStatsBreakdown.FIRST_PAGEVIEW_UTM_CONTENT,- WebStatsBreakdown.INITIAL_REFERRING_DOMAIN: WebStatsBreakdown.FIRST_PAGEVIEW_REFERRING_DOMAIN,- WebStatsBreakdown.INITIAL_UTM_SOURCE_MEDIUM_CAMPAIGN: WebStatsBreakdown.FIRST_PAGEVIEW_UTM_SOURCE_MEDIUM_CAMPAIGN,- WebStatsBreakdown.INITIAL_CHANNEL_TYPE: WebStatsBreakdown.FIRST_PAGEVIEW_CHANNEL_TYPE,-}--# Ordered property keys each FirstPageview* breakdown reads from the session's-# first pageview; the order defines the tuple element indexes used by-# _first_pageview_prop.-FIRST_PAGEVIEW_BREAKDOWN_PROPERTIES: dict[WebStatsBreakdown, tuple[str, ...]] = {- WebStatsBreakdown.FIRST_PAGEVIEW_UTM_SOURCE: ("utm_source",),- WebStatsBreakdown.FIRST_PAGEVIEW_UTM_CAMPAIGN: ("utm_campaign",),- WebStatsBreakdown.FIRST_PAGEVIEW_UTM_MEDIUM: ("utm_medium",),- WebStatsBreakdown.FIRST_PAGEVIEW_UTM_TERM: ("utm_term",),- WebStatsBreakdown.FIRST_PAGEVIEW_UTM_CONTENT: ("utm_content",),- WebStatsBreakdown.FIRST_PAGEVIEW_REFERRING_DOMAIN: ("$referring_domain",),- WebStatsBreakdown.FIRST_PAGEVIEW_UTM_SOURCE_MEDIUM_CAMPAIGN: (- "utm_source",- "$referring_domain",- "utm_medium",- "utm_campaign",- ),- WebStatsBreakdown.FIRST_PAGEVIEW_CHANNEL_TYPE: (- "utm_campaign",- "utm_medium",- "utm_source",- "$current_url",- "$referring_domain",- "gclid",- "fbclid",- "gad_source",- ),-}--FIRST_PAGEVIEW_BREAKDOWNS = frozenset(FIRST_PAGEVIEW_BREAKDOWN_PROPERTIES)-def _none_if_nan(value):"""avgMergeIf returns NaN for empty windows; replace with None so the@@ -239,12 +195,6 @@ class WebStatsTableQueryRunner(WebAnalyticsQueryRunner[WebStatsTableQueryResponsreturn "stats_table_simple_breakdown"- @cached_property- def _first_pageview_attribution_enabled(self) -> bool:- return self._evaluate_team_rollout_flag(- FIRST_PAGEVIEW_ATTRIBUTION_FEATURE_FLAG, "web_analytics_first_pageview_attribution_flag_failed"- )-def _effective_breakdown(self) -> WebStatsBreakdown:remapped = INITIAL_TO_FIRST_PAGEVIEW.get(self.query.breakdownBy)if remapped is not None and self._first_pageview_attribution_enabled:@@ -419,7 +369,7 @@ class WebStatsTableQueryRunner(WebAnalyticsQueryRunner[WebStatsTableQueryResponsvisitor = Visitor()visitor.visit(self._counts_breakdown_value())- visitor.visit(self._all_properties())+ visitor.visit(self.all_properties())return founddef _period_comparison_tuple(self, column, alias, function_name):@@ -456,12 +406,14 @@ class WebStatsTableQueryRunner(WebAnalyticsQueryRunner[WebStatsTableQueryRespons)def _event_properties(self) -> ast.Expr:- properties = [+ # Each path-bounce events scan gets its own WHERE, so the rewritten+ # predicates repeat across the bounce and scroll variants below.+ properties: list = [p- for p in self.query.properties + self._test_account_filters+ for p in self.effective_query_properties + self._test_account_filtersif get_property_type(p) in ["event", "person", "cohort"]]- return property_to_expr(properties, team=self.team, scope="event")+ return property_to_expr([*properties, *self.first_pageview_filter_exprs], team=self.team, scope="event")def _event_properties_for_scroll(self) -> ast.Expr:def map_scroll_property(property: Union[EventPropertyFilter, PersonPropertyFilter]):@@ -473,12 +425,12 @@ class WebStatsTableQueryRunner(WebAnalyticsQueryRunner[WebStatsTableQueryRespons)return property- properties = [+ properties: list = [map_scroll_property(p)- for p in self.query.properties + self._test_account_filters+ for p in self.effective_query_properties + self._test_account_filtersif get_property_type(p) in ["event", "person", "cohort"]]- return property_to_expr(properties, team=self.team, scope="event")+ return property_to_expr([*properties, *self.first_pageview_filter_exprs], team=self.team, scope="event")def _event_properties_for_bounce_rate(self) -> ast.Expr:# Exclude pathname filters for bounce rate calculation@@ -488,18 +440,12 @@ class WebStatsTableQueryRunner(WebAnalyticsQueryRunner[WebStatsTableQueryRespons# bounce rates calculations but since we group them by entry_pathname, the results could be misleading# as the events would be filtered by a IN(pathname) and the bounce shown would be for the first pathname# which users are not necessarily expecting to see.- properties = [+ properties: list = [p- for p in self.query.properties + self._test_account_filters+ for p in self.effective_query_properties + self._test_account_filtersif not (get_property_type(p) == "event" and get_property_key(p) == "$pathname")]- return property_to_expr(properties, team=self.team, scope="event")-- def _session_properties(self) -> ast.Expr:- properties = [- p for p in self.query.properties + self._test_account_filters if get_property_type(p) == "session"- ]- return property_to_expr(properties, team=self.team, scope="event")+ return property_to_expr([*properties, *self.first_pageview_filter_exprs], team=self.team, scope="event")@cached_propertydef should_use_session_id_set(self) -> bool:@@ -517,16 +463,21 @@ class WebStatsTableQueryRunner(WebAnalyticsQueryRunner[WebStatsTableQueryResponsreturn self._session_id_set_common_eligibility()@cached_property- def _session_id_set_bounce_properties(self) -> list[Union[EventPropertyFilter, PersonPropertyFilter, dict]]:+ def _session_id_set_bounce_properties(+ self,+ ) -> list[Union[EventPropertyFilter, PersonPropertyFilter, dict, ast.Expr]]:# The bounce side mirrors the join path's `_event_properties_for_bounce_rate`# semantics: pathname filters are excluded, because bounce is attributed to# the session's ENTRY path — restricting the id collection by the viewed# pathname would compute each entry path's bounce rate over the wrong# session population.return [- p- for p in self.query.properties + self._test_account_filters- if not (get_property_type(p) == "event" and get_property_key(p) == "$pathname")+ *(+ p+ for p in self.effective_query_properties + self._test_account_filters+ if not (get_property_type(p) == "event" and get_property_key(p) == "$pathname")+ ),+ *self.first_pageview_filter_exprs,]def _session_id_set_bounce_filter(self) -> ast.Expr:@@ -565,10 +516,6 @@ WHERE and(query_type="stats_table_session_id_set_preflight",)- def _all_properties(self) -> ast.Expr:- properties = self.query.properties + self._test_account_filters- return property_to_expr(properties, team=self.team)-def _lazy_precompute_stale(self) -> Optional[bool]:# The lazy modules mark serve-stale reads via tag_queries(precompute_stale=True)# before executing the read; surfacing it on the response lets clients (and the@@ -924,40 +871,11 @@ WHERE and(],)- def _first_pageview_property_keys(self) -> tuple[str, ...]:- return FIRST_PAGEVIEW_BREAKDOWN_PROPERTIES[self._effective_breakdown()]-def _first_pageview_properties_expr(self) -> ast.Expr:- """One argMinIf over a tuple: every property comes from the session's- earliest in-range $pageview/$screen. The event filter keeps- conversion-goal events (which share the scan) from winning the argMin,- and the single anchor event prevents per-property NULL-skip from- stitching values of different pageviews together."""- return ast.Call(- name="argMinIf",- args=[- ast.Tuple(- exprs=[- ast.Field(chain=["events", "properties", key]) for key in self._first_pageview_property_keys()- ]- ),- ast.Field(chain=["events", "timestamp"]),- parse_expr("events.event IN ('$pageview', '$screen')"),- ],- )+ return first_pageview_properties_expr(self._effective_breakdown())def _first_pageview_prop(self, key: str) -> ast.Expr:- index = self._first_pageview_property_keys().index(key) + 1- return ast.Call(- name="nullIf",- args=[- ast.Call(- name="tupleElement",- args=[ast.Field(chain=["first_pageview_properties"]), ast.Constant(value=index)],- ),- ast.Constant(value=""),- ],- )+ return first_pageview_prop(self._effective_breakdown(), key)def _first_pageview_utm_source_medium_campaign(self) -> ast.Expr:return self._source_medium_campaign_expr(@@ -967,25 +885,6 @@ WHERE and(campaign=self._first_pageview_prop("utm_campaign"),)- def _first_pageview_channel_type(self) -> ast.Expr:- url = self._first_pageview_prop("$current_url")- return create_channel_type_expr(- self.modifiers.customChannelTypeRules if self.modifiers else None,- ChannelTypeExprs(- campaign=self._first_pageview_prop("utm_campaign"),- medium=self._first_pageview_prop("utm_medium"),- source=self._first_pageview_prop("utm_source"),- url=url,- hostname=ast.Call(name="domain", args=[url]),- pathname=ast.Call(name="path", args=[url]),- referring_domain=self._first_pageview_prop("$referring_domain"),- has_gclid=ast.Call(name="isNotNull", args=[self._first_pageview_prop("gclid")]),- has_fbclid=ast.Call(name="isNotNull", args=[self._first_pageview_prop("fbclid")]),- gad_source=self._first_pageview_prop("gad_source"),- ),- timings=self.timings,- )-def _counts_breakdown_value(self):match self._effective_breakdown():case WebStatsBreakdown.PAGE:@@ -1060,22 +959,11 @@ WHERE and(medium=ast.Field(chain=["session", "$entry_utm_medium"]),campaign=ast.Field(chain=["session", "$entry_utm_campaign"]),)- case WebStatsBreakdown.FIRST_PAGEVIEW_UTM_SOURCE:- return self._first_pageview_prop("utm_source")- case WebStatsBreakdown.FIRST_PAGEVIEW_UTM_CAMPAIGN:- return self._first_pageview_prop("utm_campaign")- case WebStatsBreakdown.FIRST_PAGEVIEW_UTM_MEDIUM:- return self._first_pageview_prop("utm_medium")- case WebStatsBreakdown.FIRST_PAGEVIEW_UTM_TERM:- return self._first_pageview_prop("utm_term")- case WebStatsBreakdown.FIRST_PAGEVIEW_UTM_CONTENT:- return self._first_pageview_prop("utm_content")- case WebStatsBreakdown.FIRST_PAGEVIEW_REFERRING_DOMAIN:- return self._first_pageview_prop("$referring_domain")case WebStatsBreakdown.FIRST_PAGEVIEW_UTM_SOURCE_MEDIUM_CAMPAIGN:return self._first_pageview_utm_source_medium_campaign()- case WebStatsBreakdown.FIRST_PAGEVIEW_CHANNEL_TYPE:- return self._first_pageview_channel_type()+ case breakdown if breakdown in FIRST_PAGEVIEW_BREAKDOWNS:+ # Same expression the rewritten filter compares against, by construction.+ return first_pageview_filter_value_expr(breakdown, modifiers=self.modifiers, timings=self.timings)case WebStatsBreakdown.BROWSER:return ast.Field(chain=["properties", "$browser"])case WebStatsBreakdown.OS:diff --git a/products/web_analytics/backend/hogql_queries/stats_table_strategies.py b/products/web_analytics/backend/hogql_queries/stats_table_strategies.pyindex 669700175c12..3d0457ed0c50 100644--- a/products/web_analytics/backend/hogql_queries/stats_table_strategies.py+++ b/products/web_analytics/backend/hogql_queries/stats_table_strategies.py@@ -138,7 +138,7 @@ class SimpleBreakdownStrategy(StatsTableQueryStrategy):placeholders={"breakdown_value": breakdown,"event_where": self.runner.event_type_expr,- "all_properties": self.runner._all_properties(),+ "all_properties": self.runner.all_properties(),"inside_periods": self.runner._periods_expression(),},)@@ -174,7 +174,7 @@ class NoJoinSimpleBreakdownStrategy(SimpleBreakdownStrategy):placeholders={"breakdown_value": breakdown,"event_where": self.runner.event_type_expr,- "all_properties": self.runner._all_properties(),+ "all_properties": self.runner.all_properties(),"inside_periods": self.runner._periods_expression(),},)@@ -220,7 +220,7 @@ class FirstPageviewAttributionStrategy(SimpleBreakdownStrategy):"breakdown_value": breakdown,"first_pageview_properties": self.runner._first_pageview_properties_expr(),"event_where": self.runner.event_type_expr,- "all_properties": self.runner._all_properties(),+ "all_properties": self.runner.all_properties(),"inside_periods": self.runner._periods_expression(),"session_id_present": self.runner.events_session_id_present,},@@ -252,7 +252,7 @@ class PathBounceStrategy(StatsTableQueryStrategy):timings=self.runner.timings,placeholders={"breakdown_value": self.runner._counts_breakdown_value(),- "session_properties": self.runner._session_properties(),+ "session_properties": self.runner.session_properties(),"event_properties": self.runner._event_properties(),"bounce_event_properties": self.runner._event_properties_for_bounce_rate(),"bounce_breakdown_value": self.runner._bounce_entry_pathname_breakdown(),@@ -275,7 +275,7 @@ class PathBounceAvgTimeStrategy(StatsTableQueryStrategy):timings=self.runner.timings,placeholders={"breakdown_value": self.runner._counts_breakdown_value(),- "session_properties": self.runner._session_properties(),+ "session_properties": self.runner.session_properties(),"event_properties": self.runner._event_properties(),"time_on_page_event_properties": self.runner._event_properties_for_scroll(),"time_on_page_breakdown_value": self.runner._scroll_prev_pathname_breakdown(),@@ -429,7 +429,7 @@ class FrustrationMetricsStrategy(StatsTableQueryStrategy):"event_where": parse_expr("events.event IN ('$pageview', '$screen', '$rageclick', '$dead_click', '$exception')"),- "all_properties": self.runner._all_properties(),+ "all_properties": self.runner.all_properties(),"inside_periods": self.runner._periods_expression(),},)diff --git a/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_overview.ambr b/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_overview.ambrindex f040164df0d7..2dd569fdfb94 100644--- a/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_overview.ambr+++ b/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_overview.ambr@@ -861,6 +861,120 @@use_hive_partitioning=0'''# ---+# name: TestWebOverviewQueryRunner.test_first_pageview_attribution_rewrites_session_filters+ '''+ SELECT uniq(session_person_id) AS unique_users,+ NULL AS previous_unique_users,+ sum(filtered_pageview_count) AS total_filtered_pageview_count,+ NULL AS previous_total_filtered_pageview_count,+ uniq(session_id) AS unique_sessions,+ NULL AS previous_unique_sessions,+ avg(session_duration) AS avg_duration_s,+ NULL AS previous_avg_duration_s,+ avg(is_bounce) AS bounce_rate,+ NULL AS previous_bounce_rate+ FROM+ (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS session_person_id,+ events__session.session_id AS session_id,+ min(events__session.`$start_timestamp`) AS start_timestamp,+ any(events__session.`$session_duration`) AS session_duration,+ countIf(or(equals(events.event, '$pageview'), equals(events.event, '$screen'))) AS filtered_pageview_count,+ any(events__session.`$is_bounce`) AS is_bounce+ FROM events+ LEFT JOIN+ (SELECT toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id,+ min(toTimeZone(raw_sessions.min_timestamp, 'UTC')) AS `$start_timestamp`,+ dateDiff('second', min(toTimeZone(raw_sessions.min_timestamp, 'UTC')), max(toTimeZone(raw_sessions.max_timestamp, 'UTC'))) AS `$session_duration`,+ if(equals(uniqMerge(raw_sessions.pageview_uniq), 0), NULL, not(or(greater(uniqMerge(raw_sessions.pageview_uniq), 1), greater(uniqMerge(raw_sessions.autocapture_uniq), 0), greaterOrEquals(dateDiff('second', min(toTimeZone(raw_sessions.min_timestamp, 'UTC')), max(toTimeZone(raw_sessions.max_timestamp, 'UTC'))), 10)))) AS `$is_bounce`,+ raw_sessions.session_id_v7 AS session_id_v7+ FROM raw_sessions+ WHERE and(equals(raw_sessions.team_id, 99999), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(assumeNotNull(toDateTime('2024-06-01 00:00:00', 'UTC')), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime('2024-06-30 23:59:59', 'UTC')), toIntervalDay(3))))+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.`$session_id_uuid`, events__session.session_id_v7)+ 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(isNotNull(events.`$session_id`), or(equals(events.event, '$pageview'), equals(events.event, '$screen')), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-01 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-30 23:59:59', 'UTC')))), 0), in(events.`$session_id`,+ (SELECT session_id AS session_id+ FROM+ (SELECT events.`$session_id` AS session_id, argMinIf(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'utm_campaign'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'utm_medium'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'utm_source'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$referring_domain'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'gclid'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'fbclid'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'gad_source'), ''), 'null'), '^"|"$', '')), toTimeZone(events.timestamp, 'UTC'), in(events.event, tuple('$pageview', '$screen'))) AS first_pageview_properties+ FROM events+ WHERE and(equals(events.team_id, 99999), and(or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-01 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-30 23:59:59', 'UTC')))), 0), or(equals(events.event, '$pageview'), equals(events.event, '$screen')), isNotNull(events.`$session_id_uuid`)))+ GROUP BY session_id)+ WHERE ifNull(equals(multiIf(match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 1), ''), ''), 'null')), 'cross-network'), 'Cross Network', or(in(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null')), tuple('cpc', 'cpm', 'cpv', 'cpa', 'ppc', 'retargeting')), startsWith(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null')), 'paid'), isNotNull(nullIf(tupleElement(first_pageview_properties, 6), '')), isNotNull(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 8), ''), ''), 'null'))), coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null')), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null')), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 1), ''), ''), 'null')), '^(.*(([^a-df-z]|^)shop|shopping).*)$'), 'Paid Shopping', NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null')), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(nullIf(tupleElement(first_pageview_properties, 5), ''), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(nullIf(tupleElement(first_pageview_properties, 5), ''), '')), 'source'))), multiIf(ifNull(equals(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 8), ''), ''), 'null'), '1'), 0), 'Paid Search', match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 1), ''), ''), 'null')), '^(.*video.*)$'), 'Paid Video', isNotNull(nullIf(tupleElement(first_pageview_properties, 7), '')), 'Paid Social', 'Paid Unknown')), and(ifNull(equals(nullIf(tupleElement(first_pageview_properties, 5), ''), '$direct'), 0), isNull(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null'))), or(isNull(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null'))), in(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null')), tuple('(direct)', 'direct', '$direct'))), not(isNotNull(nullIf(tupleElement(first_pageview_properties, 7), '')))), 'Direct', coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null')), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null')), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 1), ''), ''), 'null')), '^(.*(([^a-df-z]|^)shop|shopping).*)$'), 'Organic Shopping', NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null')), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(nullIf(tupleElement(first_pageview_properties, 5), ''), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(nullIf(tupleElement(first_pageview_properties, 5), ''), '')), 'source'))), multiIf(match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 1), ''), ''), 'null')), '^(.*video.*)$'), 'Organic Video', match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null')), 'push$'), 'Push', isNotNull(nullIf(tupleElement(first_pageview_properties, 7), '')), 'Organic Social', ifNull(equals(nullIf(tupleElement(first_pageview_properties, 5), ''), '$direct'), 0), 'Direct', isNotNull(nullIf(tupleElement(first_pageview_properties, 5), '')), 'Referral', 'Unknown'))), 'Paid Search'), 0)))))+ GROUP BY session_id+ HAVING or(and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-06-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-06-30 23:59:59', 'UTC')))), 0))+ 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: TestWebOverviewQueryRunner.test_first_pageview_attribution_rewrites_session_filters.1+ '''+ SELECT uniq(session_person_id) AS unique_users,+ NULL AS previous_unique_users,+ sum(filtered_pageview_count) AS total_filtered_pageview_count,+ NULL AS previous_total_filtered_pageview_count,+ uniq(session_id) AS unique_sessions,+ NULL AS previous_unique_sessions,+ avg(session_duration) AS avg_duration_s,+ NULL AS previous_avg_duration_s,+ avg(is_bounce) AS bounce_rate,+ NULL AS previous_bounce_rate+ FROM+ (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS session_person_id,+ events__session.session_id AS session_id,+ min(events__session.`$start_timestamp`) AS start_timestamp,+ any(events__session.`$session_duration`) AS session_duration,+ countIf(or(equals(events.event, '$pageview'), equals(events.event, '$screen'))) AS filtered_pageview_count,+ any(events__session.`$is_bounce`) AS is_bounce+ FROM events+ LEFT JOIN+ (SELECT toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id,+ min(toTimeZone(raw_sessions.min_timestamp, 'UTC')) AS `$start_timestamp`,+ dateDiff('second', min(toTimeZone(raw_sessions.min_timestamp, 'UTC')), max(toTimeZone(raw_sessions.max_timestamp, 'UTC'))) AS `$session_duration`,+ if(equals(uniqMerge(raw_sessions.pageview_uniq), 0), NULL, not(or(greater(uniqMerge(raw_sessions.pageview_uniq), 1), greater(uniqMerge(raw_sessions.autocapture_uniq), 0), greaterOrEquals(dateDiff('second', min(toTimeZone(raw_sessions.min_timestamp, 'UTC')), max(toTimeZone(raw_sessions.max_timestamp, 'UTC'))), 10)))) AS `$is_bounce`,+ multiIf(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), 'null'), ''), ''), 'null')), 'cross-network'), 'Cross Network', or(in(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), 'null'), ''), ''), 'null')), tuple('cpc', 'cpm', 'cpv', 'cpa', 'ppc', 'retargeting')), startsWith(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), 'null'), ''), ''), 'null')), 'paid'), isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_gclid), 'null'), '')), isNotNull(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_gad_source), 'null'), ''), ''), 'null'))), coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), 'null'), ''), ''), 'null')), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), 'null'), ''), ''), 'null')), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), 'null'), ''), ''), 'null')), '^(.*(([^a-df-z]|^)shop|shopping).*)$'), 'Paid Shopping', NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), 'null'), ''), ''), 'null')), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), ''), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), ''), '')), 'source'))), multiIf(ifNull(equals(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_gad_source), 'null'), ''), ''), 'null'), '1'), 0), 'Paid Search', match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), 'null'), ''), ''), 'null')), '^(.*video.*)$'), 'Paid Video', isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), 'null'), '')), 'Paid Social', 'Paid Unknown')), and(ifNull(equals(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), ''), '$direct'), 0), isNull(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), 'null'), ''), ''), 'null'))), or(isNull(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), 'null'), ''), ''), 'null'))), in(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), 'null'), ''), ''), 'null')), tuple('(direct)', 'direct', '$direct'))), not(isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), 'null'), '')))), 'Direct', coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), 'null'), ''), ''), 'null')), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), 'null'), ''), ''), 'null')), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), 'null'), ''), ''), 'null')), '^(.*(([^a-df-z]|^)shop|shopping).*)$'), 'Organic Shopping', NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), 'null'), ''), ''), 'null')), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), ''), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), ''), '')), 'source'))), multiIf(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), 'null'), ''), ''), 'null')), '^(.*video.*)$'), 'Organic Video', match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), 'null'), ''), ''), 'null')), 'push$'), 'Push', isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), 'null'), '')), 'Organic Social', ifNull(equals(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), ''), '$direct'), 0), 'Direct', isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), '')), 'Referral', 'Unknown'))) AS `$channel_type`,+ raw_sessions.session_id_v7 AS session_id_v7+ FROM raw_sessions+ WHERE and(equals(raw_sessions.team_id, 99999), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(assumeNotNull(toDateTime('2024-06-01 00:00:00', 'UTC')), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime('2024-06-30 23:59:59', 'UTC')), toIntervalDay(3))))+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.`$session_id_uuid`, events__session.session_id_v7)+ 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(isNotNull(events.`$session_id`), or(equals(events.event, '$pageview'), equals(events.event, '$screen')), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-01 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-30 23:59:59', 'UTC')))), 0), ifNull(equals(events__session.`$channel_type`, 'Paid Search'), 0)))+ GROUP BY session_id+ HAVING or(and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-06-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-06-30 23:59:59', 'UTC')))), 0))+ 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: TestWebOverviewQueryRunner.test_increase_in_users'''SELECT uniqIf(session_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS unique_users,diff --git a/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_stats_table.ambr b/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_stats_table.ambrindex 1cf39610fcd3..26c0ef987f7f 100644--- a/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_stats_table.ambr+++ b/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_stats_table.ambr@@ -2733,6 +2733,841 @@use_hive_partitioning=0'''# ---+# name: TestWebStatsTableQueryRunner.test_first_pageview_attribution_rewrites_drill_down_filters_0_channel_type+ '''+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp+ FROM events+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC+ LIMIT 1 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: TestWebStatsTableQueryRunner.test_first_pageview_attribution_rewrites_drill_down_filters_0_channel_type.1+ '''+ SELECT breakdown_value AS `context.columns.breakdown_value`,+ tuple(uniq(filtered_person_id), NULL) AS `context.columns.visitors`,+ tuple(sum(filtered_pageview_count), NULL) AS `context.columns.views`,+ divide(`context.columns.visitors`.1, sum(`context.columns.visitors`.1) OVER ()) AS `context.columns.ui_fill_fraction`+ FROM+ (SELECT filtered_person_id AS filtered_person_id,+ filtered_pageview_count AS filtered_pageview_count,+ multiIf(match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 1), ''), ''), 'null')), 'cross-network'), 'Cross Network', or(in(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null')), tuple('cpc', 'cpm', 'cpv', 'cpa', 'ppc', 'retargeting')), startsWith(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null')), 'paid'), isNotNull(nullIf(tupleElement(first_pageview_properties, 6), '')), isNotNull(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 8), ''), ''), 'null'))), coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null')), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null')), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 1), ''), ''), 'null')), '^(.*(([^a-df-z]|^)shop|shopping).*)$'), 'Paid Shopping', NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null')), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(nullIf(tupleElement(first_pageview_properties, 5), ''), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(nullIf(tupleElement(first_pageview_properties, 5), ''), '')), 'source'))), multiIf(ifNull(equals(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 8), ''), ''), 'null'), '1'), 0), 'Paid Search', match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 1), ''), ''), 'null')), '^(.*video.*)$'), 'Paid Video', isNotNull(nullIf(tupleElement(first_pageview_properties, 7), '')), 'Paid Social', 'Paid Unknown')), and(ifNull(equals(nullIf(tupleElement(first_pageview_properties, 5), ''), '$direct'), 0), isNull(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null'))), or(isNull(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null'))), in(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null')), tuple('(direct)', 'direct', '$direct'))), not(isNotNull(nullIf(tupleElement(first_pageview_properties, 7), '')))), 'Direct', coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null')), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null')), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 1), ''), ''), 'null')), '^(.*(([^a-df-z]|^)shop|shopping).*)$'), 'Organic Shopping', NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null')), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(nullIf(tupleElement(first_pageview_properties, 5), ''), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(nullIf(tupleElement(first_pageview_properties, 5), ''), '')), 'source'))), multiIf(match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 1), ''), ''), 'null')), '^(.*video.*)$'), 'Organic Video', match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null')), 'push$'), 'Push', isNotNull(nullIf(tupleElement(first_pageview_properties, 7), '')), 'Organic Social', ifNull(equals(nullIf(tupleElement(first_pageview_properties, 5), ''), '$direct'), 0), 'Direct', isNotNull(nullIf(tupleElement(first_pageview_properties, 5), '')), 'Referral', 'Unknown'))) AS breakdown_value,+ session_id AS session_id,+ is_bounce AS is_bounce,+ start_timestamp AS start_timestamp+ FROM+ (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,+ count() AS filtered_pageview_count,+ argMinIf(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'utm_campaign'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'utm_medium'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'utm_source'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$referring_domain'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'gclid'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'fbclid'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'gad_source'), ''), 'null'), '^"|"$', '')), toTimeZone(events.timestamp, 'UTC'), in(events.event, tuple('$pageview', '$screen'))) AS first_pageview_properties,+ events__session.session_id AS session_id,+ any(events__session.`$is_bounce`) AS is_bounce,+ min(events__session.`$start_timestamp`) AS start_timestamp+ FROM events+ LEFT JOIN+ (SELECT toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id,+ if(equals(uniqMerge(raw_sessions.pageview_uniq), 0), NULL, not(or(greater(uniqMerge(raw_sessions.pageview_uniq), 1), greater(uniqMerge(raw_sessions.autocapture_uniq), 0), greaterOrEquals(dateDiff('second', min(toTimeZone(raw_sessions.min_timestamp, 'UTC')), max(toTimeZone(raw_sessions.max_timestamp, 'UTC'))), 10)))) AS `$is_bounce`,+ min(toTimeZone(raw_sessions.min_timestamp, 'UTC')) AS `$start_timestamp`,+ raw_sessions.session_id_v7 AS session_id_v7+ FROM raw_sessions+ WHERE and(equals(raw_sessions.team_id, 99999), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC')), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC')), toIntervalDay(3))))+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.`$session_id_uuid`, events__session.session_id_v7)+ 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(or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC')))), 0), or(equals(events.event, '$pageview'), equals(events.event, '$screen')), in(events.`$session_id`,+ (SELECT session_id AS session_id+ FROM+ (SELECT events.`$session_id` AS session_id, argMinIf(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'utm_campaign'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'utm_medium'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'utm_source'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$referring_domain'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'gclid'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'fbclid'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'gad_source'), ''), 'null'), '^"|"$', '')), toTimeZone(events.timestamp, 'UTC'), in(events.event, tuple('$pageview', '$screen'))) AS first_pageview_properties+ FROM events+ WHERE and(equals(events.team_id, 99999), and(or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC')))), 0), or(equals(events.event, '$pageview'), equals(events.event, '$screen')), isNotNull(events.`$session_id_uuid`)))+ GROUP BY session_id)+ WHERE ifNull(equals(multiIf(match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 1), ''), ''), 'null')), 'cross-network'), 'Cross Network', or(in(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null')), tuple('cpc', 'cpm', 'cpv', 'cpa', 'ppc', 'retargeting')), startsWith(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null')), 'paid'), isNotNull(nullIf(tupleElement(first_pageview_properties, 6), '')), isNotNull(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 8), ''), ''), 'null'))), coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null')), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null')), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 1), ''), ''), 'null')), '^(.*(([^a-df-z]|^)shop|shopping).*)$'), 'Paid Shopping', NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null')), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(nullIf(tupleElement(first_pageview_properties, 5), ''), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(nullIf(tupleElement(first_pageview_properties, 5), ''), '')), 'source'))), multiIf(ifNull(equals(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 8), ''), ''), 'null'), '1'), 0), 'Paid Search', match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 1), ''), ''), 'null')), '^(.*video.*)$'), 'Paid Video', isNotNull(nullIf(tupleElement(first_pageview_properties, 7), '')), 'Paid Social', 'Paid Unknown')), and(ifNull(equals(nullIf(tupleElement(first_pageview_properties, 5), ''), '$direct'), 0), isNull(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null'))), or(isNull(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null'))), in(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null')), tuple('(direct)', 'direct', '$direct'))), not(isNotNull(nullIf(tupleElement(first_pageview_properties, 7), '')))), 'Direct', coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null')), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null')), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 1), ''), ''), 'null')), '^(.*(([^a-df-z]|^)shop|shopping).*)$'), 'Organic Shopping', NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null')), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(nullIf(tupleElement(first_pageview_properties, 5), ''), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(nullIf(tupleElement(first_pageview_properties, 5), ''), '')), 'source'))), multiIf(match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 1), ''), ''), 'null')), '^(.*video.*)$'), 'Organic Video', match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null')), 'push$'), 'Push', isNotNull(nullIf(tupleElement(first_pageview_properties, 7), '')), 'Organic Social', ifNull(equals(nullIf(tupleElement(first_pageview_properties, 5), ''), '$direct'), 0), 'Direct', isNotNull(nullIf(tupleElement(first_pageview_properties, 5), '')), 'Referral', 'Unknown'))), 'Paid Search'), 0))), isNotNull(events.`$session_id_uuid`)))+ GROUP BY session_id))+ GROUP BY `context.columns.breakdown_value`+ HAVING and(isNotNull(`context.columns.breakdown_value`), ifNull(notEquals(`context.columns.breakdown_value`, ''), 1))+ ORDER BY `context.columns.visitors` DESC,+ `context.columns.views` DESC,+ `context.columns.breakdown_value` ASC+ LIMIT 101+ OFFSET 0 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: TestWebStatsTableQueryRunner.test_first_pageview_attribution_rewrites_drill_down_filters_0_channel_type.2+ '''+ SELECT breakdown_value AS `context.columns.breakdown_value`,+ tuple(uniq(filtered_person_id), NULL) AS `context.columns.visitors`,+ tuple(sum(filtered_pageview_count), NULL) AS `context.columns.views`,+ divide(`context.columns.visitors`.1, sum(`context.columns.visitors`.1) OVER ()) AS `context.columns.ui_fill_fraction`+ FROM+ (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,+ count() AS filtered_pageview_count,+ events__session.`$channel_type` AS breakdown_value,+ events__session.session_id AS session_id,+ any(events__session.`$is_bounce`) AS is_bounce,+ min(events__session.`$start_timestamp`) AS start_timestamp+ FROM events+ LEFT JOIN+ (SELECT multiIf(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), 'null'), ''), ''), 'null')), 'cross-network'), 'Cross Network', or(in(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), 'null'), ''), ''), 'null')), tuple('cpc', 'cpm', 'cpv', 'cpa', 'ppc', 'retargeting')), startsWith(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), 'null'), ''), ''), 'null')), 'paid'), isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_gclid), 'null'), '')), isNotNull(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_gad_source), 'null'), ''), ''), 'null'))), coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), 'null'), ''), ''), 'null')), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), 'null'), ''), ''), 'null')), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), 'null'), ''), ''), 'null')), '^(.*(([^a-df-z]|^)shop|shopping).*)$'), 'Paid Shopping', NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), 'null'), ''), ''), 'null')), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), ''), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), ''), '')), 'source'))), multiIf(ifNull(equals(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_gad_source), 'null'), ''), ''), 'null'), '1'), 0), 'Paid Search', match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), 'null'), ''), ''), 'null')), '^(.*video.*)$'), 'Paid Video', isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), 'null'), '')), 'Paid Social', 'Paid Unknown')), and(ifNull(equals(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), ''), '$direct'), 0), isNull(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), 'null'), ''), ''), 'null'))), or(isNull(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), 'null'), ''), ''), 'null'))), in(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), 'null'), ''), ''), 'null')), tuple('(direct)', 'direct', '$direct'))), not(isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), 'null'), '')))), 'Direct', coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), 'null'), ''), ''), 'null')), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), 'null'), ''), ''), 'null')), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), 'null'), ''), ''), 'null')), '^(.*(([^a-df-z]|^)shop|shopping).*)$'), 'Organic Shopping', NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), 'null'), ''), ''), 'null')), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), ''), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), ''), '')), 'source'))), multiIf(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), 'null'), ''), ''), 'null')), '^(.*video.*)$'), 'Organic Video', match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), 'null'), ''), ''), 'null')), 'push$'), 'Push', isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), 'null'), '')), 'Organic Social', ifNull(equals(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), ''), '$direct'), 0), 'Direct', isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), '')), 'Referral', 'Unknown'))) AS `$channel_type`,+ toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id,+ if(equals(uniqMerge(raw_sessions.pageview_uniq), 0), NULL, not(or(greater(uniqMerge(raw_sessions.pageview_uniq), 1), greater(uniqMerge(raw_sessions.autocapture_uniq), 0), greaterOrEquals(dateDiff('second', min(toTimeZone(raw_sessions.min_timestamp, 'UTC')), max(toTimeZone(raw_sessions.max_timestamp, 'UTC'))), 10)))) AS `$is_bounce`,+ min(toTimeZone(raw_sessions.min_timestamp, 'UTC')) AS `$start_timestamp`,+ raw_sessions.session_id_v7 AS session_id_v7+ FROM raw_sessions+ WHERE and(equals(raw_sessions.team_id, 99999), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC')), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC')), toIntervalDay(3))))+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.`$session_id_uuid`, events__session.session_id_v7)+ 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(or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC')))), 0), or(equals(events.event, '$pageview'), equals(events.event, '$screen')), ifNull(equals(events__session.`$channel_type`, 'Paid Search'), 0)))+ GROUP BY session_id,+ breakdown_value)+ GROUP BY `context.columns.breakdown_value`+ HAVING and(isNotNull(`context.columns.breakdown_value`), ifNull(notEquals(`context.columns.breakdown_value`, ''), 1))+ ORDER BY `context.columns.visitors` DESC,+ `context.columns.views` DESC,+ `context.columns.breakdown_value` ASC+ LIMIT 101+ OFFSET 0 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: TestWebStatsTableQueryRunner.test_first_pageview_attribution_rewrites_drill_down_filters_1_utm_source+ '''+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp+ FROM events+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC+ LIMIT 1 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: TestWebStatsTableQueryRunner.test_first_pageview_attribution_rewrites_drill_down_filters_1_utm_source.1+ '''+ SELECT breakdown_value AS `context.columns.breakdown_value`,+ tuple(uniq(filtered_person_id), NULL) AS `context.columns.visitors`,+ tuple(sum(filtered_pageview_count), NULL) AS `context.columns.views`,+ divide(`context.columns.visitors`.1, sum(`context.columns.visitors`.1) OVER ()) AS `context.columns.ui_fill_fraction`+ FROM+ (SELECT filtered_person_id AS filtered_person_id,+ filtered_pageview_count AS filtered_pageview_count,+ nullIf(tupleElement(first_pageview_properties, 1), '') AS breakdown_value,+ session_id AS session_id,+ is_bounce AS is_bounce,+ start_timestamp AS start_timestamp+ FROM+ (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,+ count() AS filtered_pageview_count,+ argMinIf(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'utm_source'), ''), 'null'), '^"|"$', '')), toTimeZone(events.timestamp, 'UTC'), in(events.event, tuple('$pageview', '$screen'))) AS first_pageview_properties,+ events__session.session_id AS session_id,+ any(events__session.`$is_bounce`) AS is_bounce,+ min(events__session.`$start_timestamp`) AS start_timestamp+ FROM events+ LEFT JOIN+ (SELECT toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id,+ if(equals(uniqMerge(raw_sessions.pageview_uniq), 0), NULL, not(or(greater(uniqMerge(raw_sessions.pageview_uniq), 1), greater(uniqMerge(raw_sessions.autocapture_uniq), 0), greaterOrEquals(dateDiff('second', min(toTimeZone(raw_sessions.min_timestamp, 'UTC')), max(toTimeZone(raw_sessions.max_timestamp, 'UTC'))), 10)))) AS `$is_bounce`,+ min(toTimeZone(raw_sessions.min_timestamp, 'UTC')) AS `$start_timestamp`,+ raw_sessions.session_id_v7 AS session_id_v7+ FROM raw_sessions+ WHERE and(equals(raw_sessions.team_id, 99999), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC')), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC')), toIntervalDay(3))))+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.`$session_id_uuid`, events__session.session_id_v7)+ 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(or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC')))), 0), or(equals(events.event, '$pageview'), equals(events.event, '$screen')), in(events.`$session_id`,+ (SELECT session_id AS session_id+ FROM+ (SELECT events.`$session_id` AS session_id, argMinIf(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'utm_source'), ''), 'null'), '^"|"$', '')), toTimeZone(events.timestamp, 'UTC'), in(events.event, tuple('$pageview', '$screen'))) AS first_pageview_properties+ FROM events+ WHERE and(equals(events.team_id, 99999), and(or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC')))), 0), or(equals(events.event, '$pageview'), equals(events.event, '$screen')), isNotNull(events.`$session_id_uuid`)))+ GROUP BY session_id)+ WHERE ifNull(equals(nullIf(tupleElement(first_pageview_properties, 1), ''), 'google'), 0))), isNotNull(events.`$session_id_uuid`)))+ GROUP BY session_id))+ GROUP BY `context.columns.breakdown_value`+ ORDER BY `context.columns.visitors` DESC,+ `context.columns.views` DESC,+ `context.columns.breakdown_value` ASC+ LIMIT 101+ OFFSET 0 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: TestWebStatsTableQueryRunner.test_first_pageview_attribution_rewrites_drill_down_filters_1_utm_source.2+ '''+ SELECT breakdown_value AS `context.columns.breakdown_value`,+ tuple(uniq(filtered_person_id), NULL) AS `context.columns.visitors`,+ tuple(sum(filtered_pageview_count), NULL) AS `context.columns.views`,+ divide(`context.columns.visitors`.1, sum(`context.columns.visitors`.1) OVER ()) AS `context.columns.ui_fill_fraction`+ FROM+ (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,+ count() AS filtered_pageview_count,+ events__session.`$entry_utm_source` AS breakdown_value,+ events__session.session_id AS session_id,+ any(events__session.`$is_bounce`) AS is_bounce,+ min(events__session.`$start_timestamp`) AS start_timestamp+ FROM events+ LEFT JOIN+ (SELECT nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), 'null'), '') AS `$entry_utm_source`,+ toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id,+ if(equals(uniqMerge(raw_sessions.pageview_uniq), 0), NULL, not(or(greater(uniqMerge(raw_sessions.pageview_uniq), 1), greater(uniqMerge(raw_sessions.autocapture_uniq), 0), greaterOrEquals(dateDiff('second', min(toTimeZone(raw_sessions.min_timestamp, 'UTC')), max(toTimeZone(raw_sessions.max_timestamp, 'UTC'))), 10)))) AS `$is_bounce`,+ min(toTimeZone(raw_sessions.min_timestamp, 'UTC')) AS `$start_timestamp`,+ raw_sessions.session_id_v7 AS session_id_v7+ FROM raw_sessions+ WHERE and(equals(raw_sessions.team_id, 99999), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC')), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC')), toIntervalDay(3))))+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.`$session_id_uuid`, events__session.session_id_v7)+ 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(or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC')))), 0), or(equals(events.event, '$pageview'), equals(events.event, '$screen')), ifNull(equals(events__session.`$entry_utm_source`, 'google'), 0)))+ GROUP BY session_id,+ breakdown_value)+ GROUP BY `context.columns.breakdown_value`+ ORDER BY `context.columns.visitors` DESC,+ `context.columns.views` DESC,+ `context.columns.breakdown_value` ASC+ LIMIT 101+ OFFSET 0 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: TestWebStatsTableQueryRunner.test_first_pageview_attribution_rewrites_drill_down_filters_2_referring_domain+ '''+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp+ FROM events+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC+ LIMIT 1 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: TestWebStatsTableQueryRunner.test_first_pageview_attribution_rewrites_drill_down_filters_2_referring_domain.1+ '''+ SELECT breakdown_value AS `context.columns.breakdown_value`,+ tuple(uniq(filtered_person_id), NULL) AS `context.columns.visitors`,+ tuple(sum(filtered_pageview_count), NULL) AS `context.columns.views`,+ divide(`context.columns.visitors`.1, sum(`context.columns.visitors`.1) OVER ()) AS `context.columns.ui_fill_fraction`+ FROM+ (SELECT filtered_person_id AS filtered_person_id,+ filtered_pageview_count AS filtered_pageview_count,+ nullIf(tupleElement(first_pageview_properties, 1), '') AS breakdown_value,+ session_id AS session_id,+ is_bounce AS is_bounce,+ start_timestamp AS start_timestamp+ FROM+ (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,+ count() AS filtered_pageview_count,+ argMinIf(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$referring_domain'), ''), 'null'), '^"|"$', '')), toTimeZone(events.timestamp, 'UTC'), in(events.event, tuple('$pageview', '$screen'))) AS first_pageview_properties,+ events__session.session_id AS session_id,+ any(events__session.`$is_bounce`) AS is_bounce,+ min(events__session.`$start_timestamp`) AS start_timestamp+ FROM events+ LEFT JOIN+ (SELECT toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id,+ if(equals(uniqMerge(raw_sessions.pageview_uniq), 0), NULL, not(or(greater(uniqMerge(raw_sessions.pageview_uniq), 1), greater(uniqMerge(raw_sessions.autocapture_uniq), 0), greaterOrEquals(dateDiff('second', min(toTimeZone(raw_sessions.min_timestamp, 'UTC')), max(toTimeZone(raw_sessions.max_timestamp, 'UTC'))), 10)))) AS `$is_bounce`,+ min(toTimeZone(raw_sessions.min_timestamp, 'UTC')) AS `$start_timestamp`,+ raw_sessions.session_id_v7 AS session_id_v7+ FROM raw_sessions+ WHERE and(equals(raw_sessions.team_id, 99999), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC')), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC')), toIntervalDay(3))))+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.`$session_id_uuid`, events__session.session_id_v7)+ 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(or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC')))), 0), or(equals(events.event, '$pageview'), equals(events.event, '$screen')), in(events.`$session_id`,+ (SELECT session_id AS session_id+ FROM+ (SELECT events.`$session_id` AS session_id, argMinIf(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$referring_domain'), ''), 'null'), '^"|"$', '')), toTimeZone(events.timestamp, 'UTC'), in(events.event, tuple('$pageview', '$screen'))) AS first_pageview_properties+ FROM events+ WHERE and(equals(events.team_id, 99999), and(or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC')))), 0), or(equals(events.event, '$pageview'), equals(events.event, '$screen')), isNotNull(events.`$session_id_uuid`)))+ GROUP BY session_id)+ WHERE ifNull(equals(nullIf(tupleElement(first_pageview_properties, 1), ''), 'google.com'), 0))), isNotNull(events.`$session_id_uuid`)))+ GROUP BY session_id))+ GROUP BY `context.columns.breakdown_value`+ ORDER BY `context.columns.visitors` DESC,+ `context.columns.views` DESC,+ `context.columns.breakdown_value` ASC+ LIMIT 101+ OFFSET 0 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: TestWebStatsTableQueryRunner.test_first_pageview_attribution_rewrites_drill_down_filters_2_referring_domain.2+ '''+ SELECT breakdown_value AS `context.columns.breakdown_value`,+ tuple(uniq(filtered_person_id), NULL) AS `context.columns.visitors`,+ tuple(sum(filtered_pageview_count), NULL) AS `context.columns.views`,+ divide(`context.columns.visitors`.1, sum(`context.columns.visitors`.1) OVER ()) AS `context.columns.ui_fill_fraction`+ FROM+ (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,+ count() AS filtered_pageview_count,+ events__session.`$entry_referring_domain` AS breakdown_value,+ events__session.session_id AS session_id,+ any(events__session.`$is_bounce`) AS is_bounce,+ min(events__session.`$start_timestamp`) AS start_timestamp+ FROM events+ LEFT JOIN+ (SELECT nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), '') AS `$entry_referring_domain`,+ toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id,+ if(equals(uniqMerge(raw_sessions.pageview_uniq), 0), NULL, not(or(greater(uniqMerge(raw_sessions.pageview_uniq), 1), greater(uniqMerge(raw_sessions.autocapture_uniq), 0), greaterOrEquals(dateDiff('second', min(toTimeZone(raw_sessions.min_timestamp, 'UTC')), max(toTimeZone(raw_sessions.max_timestamp, 'UTC'))), 10)))) AS `$is_bounce`,+ min(toTimeZone(raw_sessions.min_timestamp, 'UTC')) AS `$start_timestamp`,+ raw_sessions.session_id_v7 AS session_id_v7+ FROM raw_sessions+ WHERE and(equals(raw_sessions.team_id, 99999), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC')), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC')), toIntervalDay(3))))+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.`$session_id_uuid`, events__session.session_id_v7)+ 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(or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC')))), 0), or(equals(events.event, '$pageview'), equals(events.event, '$screen')), ifNull(equals(events__session.`$entry_referring_domain`, 'google.com'), 0)))+ GROUP BY session_id,+ breakdown_value)+ GROUP BY `context.columns.breakdown_value`+ ORDER BY `context.columns.visitors` DESC,+ `context.columns.views` DESC,+ `context.columns.breakdown_value` ASC+ LIMIT 101+ OFFSET 0 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: TestWebStatsTableQueryRunner.test_first_pageview_attribution_rewrites_drill_down_on_paths_tile_0_bounce_rate+ '''+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp+ FROM events+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC+ LIMIT 1 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: TestWebStatsTableQueryRunner.test_first_pageview_attribution_rewrites_drill_down_on_paths_tile_0_bounce_rate.1+ '''+ SELECT counts.breakdown_value AS `context.columns.breakdown_value`,+ tuple(counts.visitors, counts.previous_visitors) AS `context.columns.visitors`,+ tuple(counts.views, counts.previous_views) AS `context.columns.views`,+ tuple(bounce.bounce_rate, bounce.previous_bounce_rate) AS `context.columns.bounce_rate`,+ divide(`context.columns.visitors`.1, sum(`context.columns.visitors`.1) OVER ()) AS `context.columns.ui_fill_fraction`+ FROM+ (SELECT breakdown_value AS breakdown_value,+ uniqIf(filtered_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC'))))) AS visitors,+ uniqIf(filtered_person_id, 0) AS previous_visitors,+ sumIf(filtered_pageview_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC'))))) AS views,+ sumIf(filtered_pageview_count, 0) AS previous_views+ FROM+ (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,+ count() AS filtered_pageview_count,+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$pathname'), ''), 'null'), '^"|"$', '') AS breakdown_value,+ events__session.session_id AS session_id,+ min(events__session.`$start_timestamp`) AS start_timestamp+ FROM events+ LEFT JOIN+ (SELECT toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id,+ min(toTimeZone(raw_sessions.min_timestamp, 'UTC')) AS `$start_timestamp`,+ raw_sessions.session_id_v7 AS session_id_v7+ FROM raw_sessions+ WHERE and(equals(raw_sessions.team_id, 99999), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC')), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC')), toIntervalDay(3))))+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.`$session_id_uuid`, events__session.session_id_v7)+ 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(or(equals(events.event, '$pageview'), equals(events.event, '$screen')), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC')))), 0), in(events.`$session_id`,+ (SELECT session_id AS session_id+ FROM+ (SELECT events.`$session_id` AS session_id, argMinIf(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'utm_campaign'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'utm_medium'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'utm_source'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$referring_domain'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'gclid'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'fbclid'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'gad_source'), ''), 'null'), '^"|"$', '')), toTimeZone(events.timestamp, 'UTC'), in(events.event, tuple('$pageview', '$screen'))) AS first_pageview_properties+ FROM events+ WHERE and(equals(events.team_id, 99999), and(or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC')))), 0), or(equals(events.event, '$pageview'), equals(events.event, '$screen')), isNotNull(events.`$session_id_uuid`)))+ GROUP BY session_id)+ WHERE ifNull(equals(multiIf(match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 1), ''), ''), 'null')), 'cross-network'), 'Cross Network', or(in(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null')), tuple('cpc', 'cpm', 'cpv', 'cpa', 'ppc', 'retargeting')), startsWith(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null')), 'paid'), isNotNull(nullIf(tupleElement(first_pageview_properties, 6), '')), isNotNull(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 8), ''), ''), 'null'))), coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null')), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null')), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 1), ''), ''), 'null')), '^(.*(([^a-df-z]|^)shop|shopping).*)$'), 'Paid Shopping', NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null')), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(nullIf(tupleElement(first_pageview_properties, 5), ''), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(nullIf(tupleElement(first_pageview_properties, 5), ''), '')), 'source'))), multiIf(ifNull(equals(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 8), ''), ''), 'null'), '1'), 0), 'Paid Search', match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 1), ''), ''), 'null')), '^(.*video.*)$'), 'Paid Video', isNotNull(nullIf(tupleElement(first_pageview_properties, 7), '')), 'Paid Social', 'Paid Unknown')), and(ifNull(equals(nullIf(tupleElement(first_pageview_properties, 5), ''), '$direct'), 0), isNull(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null'))), or(isNull(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null'))), in(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null')), tuple('(direct)', 'direct', '$direct'))), not(isNotNull(nullIf(tupleElement(first_pageview_properties, 7), '')))), 'Direct', coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null')), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null')), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 1), ''), ''), 'null')), '^(.*(([^a-df-z]|^)shop|shopping).*)$'), 'Organic Shopping', NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null')), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(nullIf(tupleElement(first_pageview_properties, 5), ''), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(nullIf(tupleElement(first_pageview_properties, 5), ''), '')), 'source'))), multiIf(match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 1), ''), ''), 'null')), '^(.*video.*)$'), 'Organic Video', match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null')), 'push$'), 'Push', isNotNull(nullIf(tupleElement(first_pageview_properties, 7), '')), 'Organic Social', ifNull(equals(nullIf(tupleElement(first_pageview_properties, 5), ''), '$direct'), 0), 'Direct', isNotNull(nullIf(tupleElement(first_pageview_properties, 5), '')), 'Referral', 'Unknown'))), 'Paid Search'), 0))), 1))+ GROUP BY session_id,+ breakdown_value)+ GROUP BY breakdown_value) AS counts+ LEFT JOIN+ (SELECT breakdown_value AS breakdown_value,+ avgIf(is_bounce, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC'))))) AS bounce_rate,+ avgIf(is_bounce, 0) AS previous_bounce_rate+ FROM+ (SELECT events__session.`$entry_pathname` AS breakdown_value,+ any(events__session.`$is_bounce`) AS is_bounce,+ events__session.session_id AS session_id,+ min(events__session.`$start_timestamp`) AS start_timestamp+ FROM events+ LEFT JOIN+ (SELECT path(nullIf(nullIf(argMinMerge(raw_sessions.entry_url), 'null'), '')) AS `$entry_pathname`,+ if(equals(uniqMerge(raw_sessions.pageview_uniq), 0), NULL, not(or(greater(uniqMerge(raw_sessions.pageview_uniq), 1), greater(uniqMerge(raw_sessions.autocapture_uniq), 0), greaterOrEquals(dateDiff('second', min(toTimeZone(raw_sessions.min_timestamp, 'UTC')), max(toTimeZone(raw_sessions.max_timestamp, 'UTC'))), 10)))) AS `$is_bounce`,+ toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id,+ min(toTimeZone(raw_sessions.min_timestamp, 'UTC')) AS `$start_timestamp`,+ raw_sessions.session_id_v7 AS session_id_v7+ FROM raw_sessions+ WHERE and(equals(raw_sessions.team_id, 99999), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC')), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC')), toIntervalDay(3))))+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.`$session_id_uuid`, events__session.session_id_v7)+ WHERE and(equals(events.team_id, 99999), and(or(equals(events.event, '$pageview'), equals(events.event, '$screen')), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC')))), 0), in(events.`$session_id`,+ (SELECT session_id AS session_id+ FROM+ (SELECT events.`$session_id` AS session_id, argMinIf(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'utm_campaign'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'utm_medium'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'utm_source'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$referring_domain'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'gclid'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'fbclid'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'gad_source'), ''), 'null'), '^"|"$', '')), toTimeZone(events.timestamp, 'UTC'), in(events.event, tuple('$pageview', '$screen'))) AS first_pageview_properties+ FROM events+ WHERE and(equals(events.team_id, 99999), and(or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC')))), 0), or(equals(events.event, '$pageview'), equals(events.event, '$screen')), isNotNull(events.`$session_id_uuid`)))+ GROUP BY session_id)+ WHERE ifNull(equals(multiIf(match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 1), ''), ''), 'null')), 'cross-network'), 'Cross Network', or(in(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null')), tuple('cpc', 'cpm', 'cpv', 'cpa', 'ppc', 'retargeting')), startsWith(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null')), 'paid'), isNotNull(nullIf(tupleElement(first_pageview_properties, 6), '')), isNotNull(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 8), ''), ''), 'null'))), coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null')), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null')), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 1), ''), ''), 'null')), '^(.*(([^a-df-z]|^)shop|shopping).*)$'), 'Paid Shopping', NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null')), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(nullIf(tupleElement(first_pageview_properties, 5), ''), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(nullIf(tupleElement(first_pageview_properties, 5), ''), '')), 'source'))), multiIf(ifNull(equals(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 8), ''), ''), 'null'), '1'), 0), 'Paid Search', match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 1), ''), ''), 'null')), '^(.*video.*)$'), 'Paid Video', isNotNull(nullIf(tupleElement(first_pageview_properties, 7), '')), 'Paid Social', 'Paid Unknown')), and(ifNull(equals(nullIf(tupleElement(first_pageview_properties, 5), ''), '$direct'), 0), isNull(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null'))), or(isNull(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null'))), in(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null')), tuple('(direct)', 'direct', '$direct'))), not(isNotNull(nullIf(tupleElement(first_pageview_properties, 7), '')))), 'Direct', coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null')), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null')), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 1), ''), ''), 'null')), '^(.*(([^a-df-z]|^)shop|shopping).*)$'), 'Organic Shopping', NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null')), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(nullIf(tupleElement(first_pageview_properties, 5), ''), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(nullIf(tupleElement(first_pageview_properties, 5), ''), '')), 'source'))), multiIf(match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 1), ''), ''), 'null')), '^(.*video.*)$'), 'Organic Video', match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null')), 'push$'), 'Push', isNotNull(nullIf(tupleElement(first_pageview_properties, 7), '')), 'Organic Social', ifNull(equals(nullIf(tupleElement(first_pageview_properties, 5), ''), '$direct'), 0), 'Direct', isNotNull(nullIf(tupleElement(first_pageview_properties, 5), '')), 'Referral', 'Unknown'))), 'Paid Search'), 0))), 1))+ GROUP BY session_id,+ breakdown_value)+ GROUP BY breakdown_value) AS bounce ON equals(counts.breakdown_value, bounce.breakdown_value)+ WHERE isNotNull(counts.breakdown_value)+ ORDER BY `context.columns.visitors` DESC,+ `context.columns.views` DESC,+ `context.columns.breakdown_value` ASC+ LIMIT 101+ OFFSET 0 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: TestWebStatsTableQueryRunner.test_first_pageview_attribution_rewrites_drill_down_on_paths_tile_0_bounce_rate.2+ '''+ SELECT counts.breakdown_value AS `context.columns.breakdown_value`,+ tuple(counts.visitors, counts.previous_visitors) AS `context.columns.visitors`,+ tuple(counts.views, counts.previous_views) AS `context.columns.views`,+ tuple(bounce.bounce_rate, bounce.previous_bounce_rate) AS `context.columns.bounce_rate`,+ divide(`context.columns.visitors`.1, sum(`context.columns.visitors`.1) OVER ()) AS `context.columns.ui_fill_fraction`+ FROM+ (SELECT breakdown_value AS breakdown_value,+ uniqIf(filtered_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC'))))) AS visitors,+ uniqIf(filtered_person_id, 0) AS previous_visitors,+ sumIf(filtered_pageview_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC'))))) AS views,+ sumIf(filtered_pageview_count, 0) AS previous_views+ FROM+ (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,+ count() AS filtered_pageview_count,+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$pathname'), ''), 'null'), '^"|"$', '') AS breakdown_value,+ events__session.session_id AS session_id,+ min(events__session.`$start_timestamp`) AS start_timestamp+ FROM events+ LEFT JOIN+ (SELECT toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id,+ min(toTimeZone(raw_sessions.min_timestamp, 'UTC')) AS `$start_timestamp`,+ multiIf(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), 'null'), ''), ''), 'null')), 'cross-network'), 'Cross Network', or(in(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), 'null'), ''), ''), 'null')), tuple('cpc', 'cpm', 'cpv', 'cpa', 'ppc', 'retargeting')), startsWith(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), 'null'), ''), ''), 'null')), 'paid'), isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_gclid), 'null'), '')), isNotNull(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_gad_source), 'null'), ''), ''), 'null'))), coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), 'null'), ''), ''), 'null')), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), 'null'), ''), ''), 'null')), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), 'null'), ''), ''), 'null')), '^(.*(([^a-df-z]|^)shop|shopping).*)$'), 'Paid Shopping', NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), 'null'), ''), ''), 'null')), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), ''), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), ''), '')), 'source'))), multiIf(ifNull(equals(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_gad_source), 'null'), ''), ''), 'null'), '1'), 0), 'Paid Search', match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), 'null'), ''), ''), 'null')), '^(.*video.*)$'), 'Paid Video', isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), 'null'), '')), 'Paid Social', 'Paid Unknown')), and(ifNull(equals(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), ''), '$direct'), 0), isNull(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), 'null'), ''), ''), 'null'))), or(isNull(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), 'null'), ''), ''), 'null'))), in(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), 'null'), ''), ''), 'null')), tuple('(direct)', 'direct', '$direct'))), not(isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), 'null'), '')))), 'Direct', coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), 'null'), ''), ''), 'null')), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), 'null'), ''), ''), 'null')), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), 'null'), ''), ''), 'null')), '^(.*(([^a-df-z]|^)shop|shopping).*)$'), 'Organic Shopping', NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), 'null'), ''), ''), 'null')), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), ''), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), ''), '')), 'source'))), multiIf(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), 'null'), ''), ''), 'null')), '^(.*video.*)$'), 'Organic Video', match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), 'null'), ''), ''), 'null')), 'push$'), 'Push', isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), 'null'), '')), 'Organic Social', ifNull(equals(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), ''), '$direct'), 0), 'Direct', isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), '')), 'Referral', 'Unknown'))) AS `$channel_type`,+ raw_sessions.session_id_v7 AS session_id_v7+ FROM raw_sessions+ WHERE and(equals(raw_sessions.team_id, 99999), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC')), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC')), toIntervalDay(3))))+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.`$session_id_uuid`, events__session.session_id_v7)+ 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(or(equals(events.event, '$pageview'), equals(events.event, '$screen')), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC')))), 0), 1, ifNull(equals(events__session.`$channel_type`, 'Paid Search'), 0)))+ GROUP BY session_id,+ breakdown_value)+ GROUP BY breakdown_value) AS counts+ LEFT JOIN+ (SELECT breakdown_value AS breakdown_value,+ avgIf(is_bounce, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC'))))) AS bounce_rate,+ avgIf(is_bounce, 0) AS previous_bounce_rate+ FROM+ (SELECT events__session.`$entry_pathname` AS breakdown_value,+ any(events__session.`$is_bounce`) AS is_bounce,+ events__session.session_id AS session_id,+ min(events__session.`$start_timestamp`) AS start_timestamp+ FROM events+ LEFT JOIN+ (SELECT path(nullIf(nullIf(argMinMerge(raw_sessions.entry_url), 'null'), '')) AS `$entry_pathname`,+ if(equals(uniqMerge(raw_sessions.pageview_uniq), 0), NULL, not(or(greater(uniqMerge(raw_sessions.pageview_uniq), 1), greater(uniqMerge(raw_sessions.autocapture_uniq), 0), greaterOrEquals(dateDiff('second', min(toTimeZone(raw_sessions.min_timestamp, 'UTC')), max(toTimeZone(raw_sessions.max_timestamp, 'UTC'))), 10)))) AS `$is_bounce`,+ toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id,+ min(toTimeZone(raw_sessions.min_timestamp, 'UTC')) AS `$start_timestamp`,+ multiIf(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), 'null'), ''), ''), 'null')), 'cross-network'), 'Cross Network', or(in(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), 'null'), ''), ''), 'null')), tuple('cpc', 'cpm', 'cpv', 'cpa', 'ppc', 'retargeting')), startsWith(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), 'null'), ''), ''), 'null')), 'paid'), isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_gclid), 'null'), '')), isNotNull(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_gad_source), 'null'), ''), ''), 'null'))), coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), 'null'), ''), ''), 'null')), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), 'null'), ''), ''), 'null')), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), 'null'), ''), ''), 'null')), '^(.*(([^a-df-z]|^)shop|shopping).*)$'), 'Paid Shopping', NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), 'null'), ''), ''), 'null')), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), ''), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), ''), '')), 'source'))), multiIf(ifNull(equals(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_gad_source), 'null'), ''), ''), 'null'), '1'), 0), 'Paid Search', match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), 'null'), ''), ''), 'null')), '^(.*video.*)$'), 'Paid Video', isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), 'null'), '')), 'Paid Social', 'Paid Unknown')), and(ifNull(equals(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), ''), '$direct'), 0), isNull(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), 'null'), ''), ''), 'null'))), or(isNull(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), 'null'), ''), ''), 'null'))), in(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), 'null'), ''), ''), 'null')), tuple('(direct)', 'direct', '$direct'))), not(isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), 'null'), '')))), 'Direct', coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), 'null'), ''), ''), 'null')), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), 'null'), ''), ''), 'null')), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), 'null'), ''), ''), 'null')), '^(.*(([^a-df-z]|^)shop|shopping).*)$'), 'Organic Shopping', NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), 'null'), ''), ''), 'null')), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), ''), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), ''), '')), 'source'))), multiIf(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), 'null'), ''), ''), 'null')), '^(.*video.*)$'), 'Organic Video', match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), 'null'), ''), ''), 'null')), 'push$'), 'Push', isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), 'null'), '')), 'Organic Social', ifNull(equals(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), ''), '$direct'), 0), 'Direct', isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), '')), 'Referral', 'Unknown'))) AS `$channel_type`,+ raw_sessions.session_id_v7 AS session_id_v7+ FROM raw_sessions+ WHERE and(equals(raw_sessions.team_id, 99999), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC')), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC')), toIntervalDay(3))))+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.`$session_id_uuid`, events__session.session_id_v7)+ WHERE and(equals(events.team_id, 99999), and(or(equals(events.event, '$pageview'), equals(events.event, '$screen')), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC')))), 0), ifNull(equals(events__session.`$channel_type`, 'Paid Search'), 0), ifNull(equals(events__session.`$channel_type`, 'Paid Search'), 0)))+ GROUP BY session_id,+ breakdown_value)+ GROUP BY breakdown_value) AS bounce ON equals(counts.breakdown_value, bounce.breakdown_value)+ WHERE isNotNull(counts.breakdown_value)+ ORDER BY `context.columns.visitors` DESC,+ `context.columns.views` DESC,+ `context.columns.breakdown_value` ASC+ LIMIT 101+ OFFSET 0 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: TestWebStatsTableQueryRunner.test_first_pageview_attribution_rewrites_drill_down_on_paths_tile_1_bounce_rate_and_avg_time+ '''+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp+ FROM events+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC+ LIMIT 1 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: TestWebStatsTableQueryRunner.test_first_pageview_attribution_rewrites_drill_down_on_paths_tile_1_bounce_rate_and_avg_time.1+ '''+ SELECT counts.breakdown_value AS `context.columns.breakdown_value`,+ tuple(counts.visitors, counts.previous_visitors) AS `context.columns.visitors`,+ tuple(counts.views, counts.previous_views) AS `context.columns.views`,+ tuple(coalesce(time_on_page.avg_time_on_page, 0), coalesce(time_on_page.previous_avg_time_on_page, 0)) AS `context.columns.avg_time_on_page`,+ tuple(coalesce(bounce.bounce_rate, 0), coalesce(bounce.previous_bounce_rate, 0)) AS `context.columns.bounce_rate`,+ divide(`context.columns.visitors`.1, sum(`context.columns.visitors`.1) OVER ()) AS `context.columns.ui_fill_fraction`+ FROM+ (SELECT breakdown_value AS breakdown_value,+ uniqIf(filtered_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC'))))) AS visitors,+ uniqIf(filtered_person_id, 0) AS previous_visitors,+ sumIf(filtered_pageview_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC'))))) AS views,+ sumIf(filtered_pageview_count, 0) AS previous_views+ FROM+ (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,+ count() AS filtered_pageview_count,+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$pathname'), ''), 'null'), '^"|"$', '') AS breakdown_value,+ events__session.session_id AS session_id,+ min(events__session.`$start_timestamp`) AS start_timestamp+ FROM events+ LEFT JOIN+ (SELECT toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id,+ min(toTimeZone(raw_sessions.min_timestamp, 'UTC')) AS `$start_timestamp`,+ raw_sessions.session_id_v7 AS session_id_v7+ FROM raw_sessions+ WHERE and(equals(raw_sessions.team_id, 99999), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC')), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC')), toIntervalDay(3))))+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.`$session_id_uuid`, events__session.session_id_v7)+ 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(or(equals(events.event, '$pageview'), equals(events.event, '$screen')), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC')))), 0), in(events.`$session_id`,+ (SELECT session_id AS session_id+ FROM+ (SELECT events.`$session_id` AS session_id, argMinIf(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'utm_campaign'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'utm_medium'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'utm_source'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$referring_domain'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'gclid'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'fbclid'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'gad_source'), ''), 'null'), '^"|"$', '')), toTimeZone(events.timestamp, 'UTC'), in(events.event, tuple('$pageview', '$screen'))) AS first_pageview_properties+ FROM events+ WHERE and(equals(events.team_id, 99999), and(or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC')))), 0), or(equals(events.event, '$pageview'), equals(events.event, '$screen')), isNotNull(events.`$session_id_uuid`)))+ GROUP BY session_id)+ WHERE ifNull(equals(multiIf(match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 1), ''), ''), 'null')), 'cross-network'), 'Cross Network', or(in(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null')), tuple('cpc', 'cpm', 'cpv', 'cpa', 'ppc', 'retargeting')), startsWith(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null')), 'paid'), isNotNull(nullIf(tupleElement(first_pageview_properties, 6), '')), isNotNull(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 8), ''), ''), 'null'))), coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null')), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null')), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 1), ''), ''), 'null')), '^(.*(([^a-df-z]|^)shop|shopping).*)$'), 'Paid Shopping', NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null')), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(nullIf(tupleElement(first_pageview_properties, 5), ''), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(nullIf(tupleElement(first_pageview_properties, 5), ''), '')), 'source'))), multiIf(ifNull(equals(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 8), ''), ''), 'null'), '1'), 0), 'Paid Search', match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 1), ''), ''), 'null')), '^(.*video.*)$'), 'Paid Video', isNotNull(nullIf(tupleElement(first_pageview_properties, 7), '')), 'Paid Social', 'Paid Unknown')), and(ifNull(equals(nullIf(tupleElement(first_pageview_properties, 5), ''), '$direct'), 0), isNull(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null'))), or(isNull(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null'))), in(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null')), tuple('(direct)', 'direct', '$direct'))), not(isNotNull(nullIf(tupleElement(first_pageview_properties, 7), '')))), 'Direct', coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null')), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null')), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 1), ''), ''), 'null')), '^(.*(([^a-df-z]|^)shop|shopping).*)$'), 'Organic Shopping', NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null')), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(nullIf(tupleElement(first_pageview_properties, 5), ''), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(nullIf(tupleElement(first_pageview_properties, 5), ''), '')), 'source'))), multiIf(match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 1), ''), ''), 'null')), '^(.*video.*)$'), 'Organic Video', match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null')), 'push$'), 'Push', isNotNull(nullIf(tupleElement(first_pageview_properties, 7), '')), 'Organic Social', ifNull(equals(nullIf(tupleElement(first_pageview_properties, 5), ''), '$direct'), 0), 'Direct', isNotNull(nullIf(tupleElement(first_pageview_properties, 5), '')), 'Referral', 'Unknown'))), 'Paid Search'), 0))), 1))+ GROUP BY session_id,+ breakdown_value)+ GROUP BY breakdown_value) AS counts+ LEFT JOIN+ (SELECT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$prev_pageview_pathname'), ''), 'null'), '^"|"$', '') AS breakdown_value,+ quantileIf(0.9)(least(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$prev_pageview_duration'), ''), 'null'), '^"|"$', ''), 'Float64'), 86400),+ and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC'))))) AS avg_time_on_page,+ quantileIf(0.9)(least(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$prev_pageview_duration'), ''), 'null'), '^"|"$', ''), 'Float64'), 86400),+ 0) AS previous_avg_time_on_page+ FROM events+ WHERE and(equals(events.team_id, 99999), and(or(equals(events.event, '$pageview'), equals(events.event, '$pageleave'), equals(events.event, '$screen')), isNotNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$prev_pageview_pathname'), ''), 'null'), '^"|"$', '')), isNotNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$prev_pageview_duration'), ''), 'null'), '^"|"$', '')), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC')))), 0), in(events.`$session_id`,+ (SELECT session_id AS session_id+ FROM+ (SELECT events.`$session_id` AS session_id, argMinIf(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'utm_campaign'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'utm_medium'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'utm_source'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$referring_domain'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'gclid'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'fbclid'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'gad_source'), ''), 'null'), '^"|"$', '')), toTimeZone(events.timestamp, 'UTC'), in(events.event, tuple('$pageview', '$screen'))) AS first_pageview_properties+ FROM events+ WHERE and(equals(events.team_id, 99999), and(or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC')))), 0), or(equals(events.event, '$pageview'), equals(events.event, '$screen')), isNotNull(events.`$session_id_uuid`)))+ GROUP BY session_id)+ WHERE ifNull(equals(multiIf(match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 1), ''), ''), 'null')), 'cross-network'), 'Cross Network', or(in(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null')), tuple('cpc', 'cpm', 'cpv', 'cpa', 'ppc', 'retargeting')), startsWith(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null')), 'paid'), isNotNull(nullIf(tupleElement(first_pageview_properties, 6), '')), isNotNull(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 8), ''), ''), 'null'))), coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null')), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null')), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 1), ''), ''), 'null')), '^(.*(([^a-df-z]|^)shop|shopping).*)$'), 'Paid Shopping', NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null')), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(nullIf(tupleElement(first_pageview_properties, 5), ''), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(nullIf(tupleElement(first_pageview_properties, 5), ''), '')), 'source'))), multiIf(ifNull(equals(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 8), ''), ''), 'null'), '1'), 0), 'Paid Search', match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 1), ''), ''), 'null')), '^(.*video.*)$'), 'Paid Video', isNotNull(nullIf(tupleElement(first_pageview_properties, 7), '')), 'Paid Social', 'Paid Unknown')), and(ifNull(equals(nullIf(tupleElement(first_pageview_properties, 5), ''), '$direct'), 0), isNull(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null'))), or(isNull(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null'))), in(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null')), tuple('(direct)', 'direct', '$direct'))), not(isNotNull(nullIf(tupleElement(first_pageview_properties, 7), '')))), 'Direct', coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null')), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null')), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 1), ''), ''), 'null')), '^(.*(([^a-df-z]|^)shop|shopping).*)$'), 'Organic Shopping', NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null')), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(nullIf(tupleElement(first_pageview_properties, 5), ''), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(nullIf(tupleElement(first_pageview_properties, 5), ''), '')), 'source'))), multiIf(match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 1), ''), ''), 'null')), '^(.*video.*)$'), 'Organic Video', match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null')), 'push$'), 'Push', isNotNull(nullIf(tupleElement(first_pageview_properties, 7), '')), 'Organic Social', ifNull(equals(nullIf(tupleElement(first_pageview_properties, 5), ''), '$direct'), 0), 'Direct', isNotNull(nullIf(tupleElement(first_pageview_properties, 5), '')), 'Referral', 'Unknown'))), 'Paid Search'), 0))), 1))+ GROUP BY breakdown_value) AS time_on_page ON equals(counts.breakdown_value, time_on_page.breakdown_value)+ LEFT JOIN+ (SELECT breakdown_value AS breakdown_value,+ avgIf(is_bounce, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC'))))) AS bounce_rate,+ avgIf(is_bounce, 0) AS previous_bounce_rate+ FROM+ (SELECT events__session.`$entry_pathname` AS breakdown_value,+ any(events__session.`$is_bounce`) AS is_bounce,+ events__session.session_id AS session_id,+ min(events__session.`$start_timestamp`) AS start_timestamp+ FROM events+ LEFT JOIN+ (SELECT path(nullIf(nullIf(argMinMerge(raw_sessions.entry_url), 'null'), '')) AS `$entry_pathname`,+ if(equals(uniqMerge(raw_sessions.pageview_uniq), 0), NULL, not(or(greater(uniqMerge(raw_sessions.pageview_uniq), 1), greater(uniqMerge(raw_sessions.autocapture_uniq), 0), greaterOrEquals(dateDiff('second', min(toTimeZone(raw_sessions.min_timestamp, 'UTC')), max(toTimeZone(raw_sessions.max_timestamp, 'UTC'))), 10)))) AS `$is_bounce`,+ toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id,+ min(toTimeZone(raw_sessions.min_timestamp, 'UTC')) AS `$start_timestamp`,+ raw_sessions.session_id_v7 AS session_id_v7+ FROM raw_sessions+ WHERE and(equals(raw_sessions.team_id, 99999), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC')), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC')), toIntervalDay(3))))+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.`$session_id_uuid`, events__session.session_id_v7)+ WHERE and(equals(events.team_id, 99999), and(or(equals(events.event, '$pageview'), equals(events.event, '$screen')), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC')))), 0), in(events.`$session_id`,+ (SELECT session_id AS session_id+ FROM+ (SELECT events.`$session_id` AS session_id, argMinIf(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'utm_campaign'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'utm_medium'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'utm_source'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$referring_domain'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'gclid'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'fbclid'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'gad_source'), ''), 'null'), '^"|"$', '')), toTimeZone(events.timestamp, 'UTC'), in(events.event, tuple('$pageview', '$screen'))) AS first_pageview_properties+ FROM events+ WHERE and(equals(events.team_id, 99999), and(or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC')))), 0), or(equals(events.event, '$pageview'), equals(events.event, '$screen')), isNotNull(events.`$session_id_uuid`)))+ GROUP BY session_id)+ WHERE ifNull(equals(multiIf(match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 1), ''), ''), 'null')), 'cross-network'), 'Cross Network', or(in(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null')), tuple('cpc', 'cpm', 'cpv', 'cpa', 'ppc', 'retargeting')), startsWith(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null')), 'paid'), isNotNull(nullIf(tupleElement(first_pageview_properties, 6), '')), isNotNull(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 8), ''), ''), 'null'))), coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null')), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null')), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 1), ''), ''), 'null')), '^(.*(([^a-df-z]|^)shop|shopping).*)$'), 'Paid Shopping', NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null')), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(nullIf(tupleElement(first_pageview_properties, 5), ''), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(nullIf(tupleElement(first_pageview_properties, 5), ''), '')), 'source'))), multiIf(ifNull(equals(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 8), ''), ''), 'null'), '1'), 0), 'Paid Search', match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 1), ''), ''), 'null')), '^(.*video.*)$'), 'Paid Video', isNotNull(nullIf(tupleElement(first_pageview_properties, 7), '')), 'Paid Social', 'Paid Unknown')), and(ifNull(equals(nullIf(tupleElement(first_pageview_properties, 5), ''), '$direct'), 0), isNull(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null'))), or(isNull(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null'))), in(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null')), tuple('(direct)', 'direct', '$direct'))), not(isNotNull(nullIf(tupleElement(first_pageview_properties, 7), '')))), 'Direct', coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null')), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 3), ''), ''), 'null')), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 1), ''), ''), 'null')), '^(.*(([^a-df-z]|^)shop|shopping).*)$'), 'Organic Shopping', NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null')), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(nullIf(tupleElement(first_pageview_properties, 5), ''), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(nullIf(tupleElement(first_pageview_properties, 5), ''), '')), 'source'))), multiIf(match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 1), ''), ''), 'null')), '^(.*video.*)$'), 'Organic Video', match(lower(nullIf(nullIf(nullIf(tupleElement(first_pageview_properties, 2), ''), ''), 'null')), 'push$'), 'Push', isNotNull(nullIf(tupleElement(first_pageview_properties, 7), '')), 'Organic Social', ifNull(equals(nullIf(tupleElement(first_pageview_properties, 5), ''), '$direct'), 0), 'Direct', isNotNull(nullIf(tupleElement(first_pageview_properties, 5), '')), 'Referral', 'Unknown'))), 'Paid Search'), 0))), 1))+ GROUP BY session_id,+ breakdown_value)+ GROUP BY breakdown_value) AS bounce ON equals(counts.breakdown_value, bounce.breakdown_value)+ WHERE isNotNull(counts.breakdown_value)+ ORDER BY `context.columns.visitors` DESC,+ `context.columns.views` DESC,+ `context.columns.breakdown_value` ASC+ LIMIT 101+ OFFSET 0 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: TestWebStatsTableQueryRunner.test_first_pageview_attribution_rewrites_drill_down_on_paths_tile_1_bounce_rate_and_avg_time.2+ '''+ SELECT counts.breakdown_value AS `context.columns.breakdown_value`,+ tuple(counts.visitors, counts.previous_visitors) AS `context.columns.visitors`,+ tuple(counts.views, counts.previous_views) AS `context.columns.views`,+ tuple(coalesce(time_on_page.avg_time_on_page, 0), coalesce(time_on_page.previous_avg_time_on_page, 0)) AS `context.columns.avg_time_on_page`,+ tuple(coalesce(bounce.bounce_rate, 0), coalesce(bounce.previous_bounce_rate, 0)) AS `context.columns.bounce_rate`,+ divide(`context.columns.visitors`.1, sum(`context.columns.visitors`.1) OVER ()) AS `context.columns.ui_fill_fraction`+ FROM+ (SELECT breakdown_value AS breakdown_value,+ uniqIf(filtered_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC'))))) AS visitors,+ uniqIf(filtered_person_id, 0) AS previous_visitors,+ sumIf(filtered_pageview_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC'))))) AS views,+ sumIf(filtered_pageview_count, 0) AS previous_views+ FROM+ (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,+ count() AS filtered_pageview_count,+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$pathname'), ''), 'null'), '^"|"$', '') AS breakdown_value,+ events__session.session_id AS session_id,+ min(events__session.`$start_timestamp`) AS start_timestamp+ FROM events+ LEFT JOIN+ (SELECT toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id,+ min(toTimeZone(raw_sessions.min_timestamp, 'UTC')) AS `$start_timestamp`,+ multiIf(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), 'null'), ''), ''), 'null')), 'cross-network'), 'Cross Network', or(in(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), 'null'), ''), ''), 'null')), tuple('cpc', 'cpm', 'cpv', 'cpa', 'ppc', 'retargeting')), startsWith(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), 'null'), ''), ''), 'null')), 'paid'), isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_gclid), 'null'), '')), isNotNull(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_gad_source), 'null'), ''), ''), 'null'))), coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), 'null'), ''), ''), 'null')), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), 'null'), ''), ''), 'null')), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), 'null'), ''), ''), 'null')), '^(.*(([^a-df-z]|^)shop|shopping).*)$'), 'Paid Shopping', NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), 'null'), ''), ''), 'null')), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), ''), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), ''), '')), 'source'))), multiIf(ifNull(equals(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_gad_source), 'null'), ''), ''), 'null'), '1'), 0), 'Paid Search', match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), 'null'), ''), ''), 'null')), '^(.*video.*)$'), 'Paid Video', isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), 'null'), '')), 'Paid Social', 'Paid Unknown')), and(ifNull(equals(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), ''), '$direct'), 0), isNull(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), 'null'), ''), ''), 'null'))), or(isNull(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), 'null'), ''), ''), 'null'))), in(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), 'null'), ''), ''), 'null')), tuple('(direct)', 'direct', '$direct'))), not(isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), 'null'), '')))), 'Direct', coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), 'null'), ''), ''), 'null')), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), 'null'), ''), ''), 'null')), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), 'null'), ''), ''), 'null')), '^(.*(([^a-df-z]|^)shop|shopping).*)$'), 'Organic Shopping', NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), 'null'), ''), ''), 'null')), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), ''), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), ''), '')), 'source'))), multiIf(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), 'null'), ''), ''), 'null')), '^(.*video.*)$'), 'Organic Video', match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), 'null'), ''), ''), 'null')), 'push$'), 'Push', isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), 'null'), '')), 'Organic Social', ifNull(equals(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), ''), '$direct'), 0), 'Direct', isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), '')), 'Referral', 'Unknown'))) AS `$channel_type`,+ raw_sessions.session_id_v7 AS session_id_v7+ FROM raw_sessions+ WHERE and(equals(raw_sessions.team_id, 99999), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC')), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC')), toIntervalDay(3))))+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.`$session_id_uuid`, events__session.session_id_v7)+ 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(or(equals(events.event, '$pageview'), equals(events.event, '$screen')), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC')))), 0), 1, ifNull(equals(events__session.`$channel_type`, 'Paid Search'), 0)))+ GROUP BY session_id,+ breakdown_value)+ GROUP BY breakdown_value) AS counts+ LEFT JOIN+ (SELECT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$prev_pageview_pathname'), ''), 'null'), '^"|"$', '') AS breakdown_value,+ quantileIf(0.9)(least(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$prev_pageview_duration'), ''), 'null'), '^"|"$', ''), 'Float64'), 86400),+ and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC'))))) AS avg_time_on_page,+ quantileIf(0.9)(least(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$prev_pageview_duration'), ''), 'null'), '^"|"$', ''), 'Float64'), 86400),+ 0) AS previous_avg_time_on_page+ FROM events+ LEFT JOIN+ (SELECT multiIf(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), 'null'), ''), ''), 'null')), 'cross-network'), 'Cross Network', or(in(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), 'null'), ''), ''), 'null')), tuple('cpc', 'cpm', 'cpv', 'cpa', 'ppc', 'retargeting')), startsWith(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), 'null'), ''), ''), 'null')), 'paid'), isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_gclid), 'null'), '')), isNotNull(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_gad_source), 'null'), ''), ''), 'null'))), coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), 'null'), ''), ''), 'null')), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), 'null'), ''), ''), 'null')), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), 'null'), ''), ''), 'null')), '^(.*(([^a-df-z]|^)shop|shopping).*)$'), 'Paid Shopping', NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), 'null'), ''), ''), 'null')), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), ''), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), ''), '')), 'source'))), multiIf(ifNull(equals(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_gad_source), 'null'), ''), ''), 'null'), '1'), 0), 'Paid Search', match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), 'null'), ''), ''), 'null')), '^(.*video.*)$'), 'Paid Video', isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), 'null'), '')), 'Paid Social', 'Paid Unknown')), and(ifNull(equals(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), ''), '$direct'), 0), isNull(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), 'null'), ''), ''), 'null'))), or(isNull(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), 'null'), ''), ''), 'null'))), in(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), 'null'), ''), ''), 'null')), tuple('(direct)', 'direct', '$direct'))), not(isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), 'null'), '')))), 'Direct', coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), 'null'), ''), ''), 'null')), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), 'null'), ''), ''), 'null')), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), 'null'), ''), ''), 'null')), '^(.*(([^a-df-z]|^)shop|shopping).*)$'), 'Organic Shopping', NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), 'null'), ''), ''), 'null')), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), ''), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), ''), '')), 'source'))), multiIf(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), 'null'), ''), ''), 'null')), '^(.*video.*)$'), 'Organic Video', match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), 'null'), ''), ''), 'null')), 'push$'), 'Push', isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), 'null'), '')), 'Organic Social', ifNull(equals(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), ''), '$direct'), 0), 'Direct', isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), '')), 'Referral', 'Unknown'))) AS `$channel_type`,+ raw_sessions.session_id_v7 AS session_id_v7+ FROM raw_sessions+ WHERE and(equals(raw_sessions.team_id, 99999), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC')), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC')), toIntervalDay(3))))+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.`$session_id_uuid`, events__session.session_id_v7)+ WHERE and(equals(events.team_id, 99999), and(or(equals(events.event, '$pageview'), equals(events.event, '$pageleave'), equals(events.event, '$screen')), isNotNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$prev_pageview_pathname'), ''), 'null'), '^"|"$', '')), isNotNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$prev_pageview_duration'), ''), 'null'), '^"|"$', '')), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC')))), 0), 1, ifNull(equals(events__session.`$channel_type`, 'Paid Search'), 0)))+ GROUP BY breakdown_value) AS time_on_page ON equals(counts.breakdown_value, time_on_page.breakdown_value)+ LEFT JOIN+ (SELECT breakdown_value AS breakdown_value,+ avgIf(is_bounce, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC'))))) AS bounce_rate,+ avgIf(is_bounce, 0) AS previous_bounce_rate+ FROM+ (SELECT events__session.`$entry_pathname` AS breakdown_value,+ any(events__session.`$is_bounce`) AS is_bounce,+ events__session.session_id AS session_id,+ min(events__session.`$start_timestamp`) AS start_timestamp+ FROM events+ LEFT JOIN+ (SELECT path(nullIf(nullIf(argMinMerge(raw_sessions.entry_url), 'null'), '')) AS `$entry_pathname`,+ if(equals(uniqMerge(raw_sessions.pageview_uniq), 0), NULL, not(or(greater(uniqMerge(raw_sessions.pageview_uniq), 1), greater(uniqMerge(raw_sessions.autocapture_uniq), 0), greaterOrEquals(dateDiff('second', min(toTimeZone(raw_sessions.min_timestamp, 'UTC')), max(toTimeZone(raw_sessions.max_timestamp, 'UTC'))), 10)))) AS `$is_bounce`,+ toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id,+ min(toTimeZone(raw_sessions.min_timestamp, 'UTC')) AS `$start_timestamp`,+ multiIf(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), 'null'), ''), ''), 'null')), 'cross-network'), 'Cross Network', or(in(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), 'null'), ''), ''), 'null')), tuple('cpc', 'cpm', 'cpv', 'cpa', 'ppc', 'retargeting')), startsWith(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), 'null'), ''), ''), 'null')), 'paid'), isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_gclid), 'null'), '')), isNotNull(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_gad_source), 'null'), ''), ''), 'null'))), coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), 'null'), ''), ''), 'null')), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), 'null'), ''), ''), 'null')), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), 'null'), ''), ''), 'null')), '^(.*(([^a-df-z]|^)shop|shopping).*)$'), 'Paid Shopping', NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), 'null'), ''), ''), 'null')), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), ''), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), ''), '')), 'source'))), multiIf(ifNull(equals(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_gad_source), 'null'), ''), ''), 'null'), '1'), 0), 'Paid Search', match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), 'null'), ''), ''), 'null')), '^(.*video.*)$'), 'Paid Video', isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), 'null'), '')), 'Paid Social', 'Paid Unknown')), and(ifNull(equals(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), ''), '$direct'), 0), isNull(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), 'null'), ''), ''), 'null'))), or(isNull(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), 'null'), ''), ''), 'null'))), in(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), 'null'), ''), ''), 'null')), tuple('(direct)', 'direct', '$direct'))), not(isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), 'null'), '')))), 'Direct', coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), 'null'), ''), ''), 'null')), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), 'null'), ''), ''), 'null')), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), 'null'), ''), ''), 'null')), '^(.*(([^a-df-z]|^)shop|shopping).*)$'), 'Organic Shopping', NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), 'null'), ''), ''), 'null')), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), ''), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), ''), '')), 'source'))), multiIf(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), 'null'), ''), ''), 'null')), '^(.*video.*)$'), 'Organic Video', match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), 'null'), ''), ''), 'null')), 'push$'), 'Push', isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), 'null'), '')), 'Organic Social', ifNull(equals(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), ''), '$direct'), 0), 'Direct', isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), 'null'), '')), 'Referral', 'Unknown'))) AS `$channel_type`,+ raw_sessions.session_id_v7 AS session_id_v7+ FROM raw_sessions+ WHERE and(equals(raw_sessions.team_id, 99999), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC')), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC')), toIntervalDay(3))))+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.`$session_id_uuid`, events__session.session_id_v7)+ WHERE and(equals(events.team_id, 99999), and(or(equals(events.event, '$pageview'), equals(events.event, '$screen')), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-26 10:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-06-27 23:59:59', 'UTC')))), 0), ifNull(equals(events__session.`$channel_type`, 'Paid Search'), 0), ifNull(equals(events__session.`$channel_type`, 'Paid Search'), 0)))+ GROUP BY session_id,+ breakdown_value)+ GROUP BY breakdown_value) AS bounce ON equals(counts.breakdown_value, bounce.breakdown_value)+ WHERE isNotNull(counts.breakdown_value)+ ORDER BY `context.columns.visitors` DESC,+ `context.columns.views` DESC,+ `context.columns.breakdown_value` ASC+ LIMIT 101+ OFFSET 0 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: TestWebStatsTableQueryRunner.test_first_pageview_channel_type_buckets_0_referral_unknown_domain'''SELECT toTimeZone(events.timestamp, 'UTC') AS timestampdiff --git a/products/web_analytics/backend/hogql_queries/test/first_pageview_attribution_test_base.py b/products/web_analytics/backend/hogql_queries/test/first_pageview_attribution_test_base.pynew file mode 100644index 000000000000..576271580316--- /dev/null+++ b/products/web_analytics/backend/hogql_queries/test/first_pageview_attribution_test_base.py@@ -0,0 +1,51 @@+from typing import TYPE_CHECKING++from posthog.test.base import _create_event, _create_person+from unittest.mock import patch++from posthog.models.utils import uuid7++from products.web_analytics.backend.hogql_queries.first_pageview_flag import FIRST_PAGEVIEW_ATTRIBUTION_FEATURE_FLAG++if TYPE_CHECKING:+ from posthog.models import Team+++class FirstPageviewAttributionTestMixin:+ team: "Team"++ def _seed_ssr_poisoned_session(self) -> None:+ # The $feature_flag_called fires before the first pageview, so raw_sessions+ # v2 attributes the session to it and blanks the entry UTMs. Both events+ # matter: this session reads as Direct under entry attribution and Paid+ # Search under first-pageview attribution.+ session_id = str(uuid7("2024-06-26"))+ _create_person(team_id=self.team.pk, distinct_ids=["d1"], properties={"name": "d1"})+ _create_event(+ team=self.team,+ event="$feature_flag_called",+ distinct_id="d1",+ timestamp="2024-06-26T10:00:00",+ properties={"$session_id": session_id, "$referring_domain": "$direct"},+ )+ _create_event(+ team=self.team,+ event="$pageview",+ distinct_id="d1",+ timestamp="2024-06-26T10:00:05",+ properties={+ "$session_id": session_id,+ "$current_url": "http://example.com/landing",+ "$pathname": "/landing",+ "$referring_domain": "google.com",+ "utm_source": "google",+ "utm_medium": "cpc",+ "gad_source": "1",+ },+ )++ def _patch_first_pageview_flag(self, enabled=True):+ return patch(+ "products.web_analytics.backend.hogql_queries.first_pageview_flag.posthoganalytics.feature_enabled",+ side_effect=lambda key, *args, **kwargs: enabled and key == FIRST_PAGEVIEW_ATTRIBUTION_FEATURE_FLAG,+ )diff --git a/products/web_analytics/backend/hogql_queries/test/test_first_pageview_attribution_trends.py b/products/web_analytics/backend/hogql_queries/test/test_first_pageview_attribution_trends.pynew file mode 100644index 000000000000..8d72a33575bd--- /dev/null+++ b/products/web_analytics/backend/hogql_queries/test/test_first_pageview_attribution_trends.py@@ -0,0 +1,111 @@+from freezegun import freeze_time+from posthog.test.base import APIBaseTest, ClickhouseTestMixin++from django.test import override_settings++from parameterized import parameterized++from posthog.schema import (+ BaseMathType,+ ChartDisplayType,+ DateRange,+ EventsNode,+ HogQLQueryModifiers,+ PropertyOperator,+ QueryLogTags,+ SessionPropertyFilter,+ SessionTableVersion,+ TrendsFilter,+ TrendsQuery,+)++from posthog.hogql_queries.insights.trends.trends_query_runner import TrendsQueryRunner+from posthog.hogql_queries.query_runner import get_query_runner++from products.web_analytics.backend.hogql_queries.test.first_pageview_attribution_test_base import (+ FirstPageviewAttributionTestMixin,+)+++@override_settings(IN_UNIT_TESTING=True)+class TestFirstPageviewAttributionTrends(FirstPageviewAttributionTestMixin, ClickhouseTestMixin, APIBaseTest):+ QUERY_TIMESTAMP = "2024-07-30"++ def _paid_search_visitors(self, flag_on, tagged):+ query = TrendsQuery(+ dateRange=DateRange(date_from="2024-06-01", date_to="2024-06-30"),+ series=[EventsNode(event="$pageview", math=BaseMathType.DAU)],+ properties=[+ SessionPropertyFilter(key="$channel_type", value="Paid Search", operator=PropertyOperator.EXACT)+ ],+ tags=QueryLogTags(productKey="web_analytics") if tagged else None,+ modifiers=HogQLQueryModifiers(sessionTableVersion=SessionTableVersion.V2),+ )+ with self._patch_first_pageview_flag(flag_on), freeze_time(self.QUERY_TIMESTAMP):+ response = TrendsQueryRunner(team=self.team, query=query).calculate()+ return response.results[0]["count"]++ @parameterized.expand(+ [+ ("web_analytics_flag_on", True, True, 1),+ ("web_analytics_flag_off", False, True, 0),+ ("other_product_flag_on", True, False, 0),+ ]+ )+ def test_trends_session_filter_rewrite(self, _name, flag_on, tagged, expected):+ # A query from any other product must keep entry attribution: `tags` are+ # stripped from the cache key, so a leak here would also let the two+ # share a cache entry.+ self._seed_ssr_poisoned_session()++ assert self._paid_search_visitors(flag_on=flag_on, tagged=tagged) == expected++ @parameterized.expand(+ [+ ("line_graph_flag_on", ChartDisplayType.ACTIONS_LINE_GRAPH, True, 1),+ ("line_graph_flag_off", ChartDisplayType.ACTIONS_LINE_GRAPH, False, 0),+ ("heatmap_flag_on", ChartDisplayType.CALENDAR_HEATMAP, True, 1),+ ("heatmap_flag_off", ChartDisplayType.CALENDAR_HEATMAP, False, 0),+ ]+ )+ def test_series_level_session_filter_rewrite(self, _name, display, flag_on, expected):+ # Active Hours puts the filter on the series, not the query, and renders+ # through the calendar heatmap runner: a different runner reading a+ # different property list.+ self._seed_ssr_poisoned_session()++ query = TrendsQuery(+ dateRange=DateRange(date_from="2024-06-01", date_to="2024-06-30"),+ series=[+ EventsNode(+ event="$pageview",+ math=BaseMathType.DAU,+ properties=[+ SessionPropertyFilter(key="$channel_type", value="Paid Search", operator=PropertyOperator.EXACT)+ ],+ )+ ],+ trendsFilter=TrendsFilter(display=display),+ tags=QueryLogTags(productKey="web_analytics"),+ modifiers=HogQLQueryModifiers(sessionTableVersion=SessionTableVersion.V2),+ )+ with self._patch_first_pageview_flag(flag_on), freeze_time(self.QUERY_TIMESTAMP):+ results = get_query_runner(query, team=self.team).calculate().results++ assert results[0]["count"] == expected++ def test_rewritten_filter_changes_trends_cache_key(self):+ query = TrendsQuery(+ dateRange=DateRange(date_from="2024-06-01", date_to="2024-06-30"),+ series=[EventsNode(event="$pageview", math=BaseMathType.DAU)],+ properties=[+ SessionPropertyFilter(key="$channel_type", value="Paid Search", operator=PropertyOperator.EXACT)+ ],+ tags=QueryLogTags(productKey="web_analytics"),+ )++ def cache_key(flag_on):+ with self._patch_first_pageview_flag(flag_on):+ return TrendsQueryRunner(team=self.team, query=query).get_cache_key()++ assert cache_key(flag_on=True) != cache_key(flag_on=False)diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_overview.py b/products/web_analytics/backend/hogql_queries/test/test_web_overview.pyindex 954e74e12b30..59f5e26e06b5 100644--- a/products/web_analytics/backend/hogql_queries/test/test_web_overview.py+++ b/products/web_analytics/backend/hogql_queries/test/test_web_overview.py@@ -47,6 +47,9 @@ from posthog.settings import HOGQL_INCREASED_MAX_EXECUTION_TIMEfrom products.actions.backend.models.action import Actionfrom products.cohorts.backend.models.cohort import Cohort+from products.web_analytics.backend.hogql_queries.test.first_pageview_attribution_test_base import (+ FirstPageviewAttributionTestMixin,+)from products.web_analytics.backend.hogql_queries.web_overview import WebOverviewQueryRunnerfrom products.web_analytics.backend.hogql_queries.web_overview_pre_aggregated import (WebOverviewPreAggregatedQueryBuilder,@@ -54,7 +57,7 @@ from products.web_analytics.backend.hogql_queries.web_overview_pre_aggregated im@snapshot_clickhouse_queries-class TestWebOverviewQueryRunner(ClickhouseTestMixin, APIBaseTest):+class TestWebOverviewQueryRunner(FirstPageviewAttributionTestMixin, ClickhouseTestMixin, APIBaseTest):QUERY_TIMESTAMP = "2025-01-29"def _create_events(self, data, event="$pageview"):@@ -138,6 +141,24 @@ class TestWebOverviewQueryRunner(ClickhouseTestMixin, APIBaseTest):WebOverviewQueryResponse.model_validate(response)return response+ def test_first_pageview_attribution_rewrites_session_filters(self):+ self._seed_ssr_poisoned_session()++ def visitors_for_paid_search(flag_on):+ with self._patch_first_pageview_flag(flag_on), freeze_time(self.QUERY_TIMESTAMP):+ query = WebOverviewQuery(+ dateRange=DateRange(date_from="2024-06-01", date_to="2024-06-30"),+ properties=[+ SessionPropertyFilter(key="$channel_type", value="Paid Search", operator=PropertyOperator.EXACT)+ ],+ modifiers=HogQLQueryModifiers(sessionTableVersion=SessionTableVersion.V2),+ )+ results = WebOverviewQueryRunner(team=self.team, query=query).calculate().results+ return next(item.value for item in results if item.key == "visitors")++ assert visitors_for_paid_search(flag_on=True) == 1+ assert not visitors_for_paid_search(flag_on=False)+def test_no_crash_when_no_data(self):results = self._run_web_overview_query("2023-12-08",@@ -1295,7 +1316,7 @@ class TestWebOverviewSessionIdSetFastPath(ClickhouseTestMixin, APIBaseTest):with (override_settings(WEB_ANALYTICS_SESSION_ID_SET_TEAM_IDS=allowlist),patch(- "products.web_analytics.backend.hogql_queries.web_analytics_query_runner.posthoganalytics.feature_enabled",+ "products.web_analytics.backend.hogql_queries.first_pageview_flag.posthoganalytics.feature_enabled",**flag_mock_kwargs,),):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.pyindex dad707a7b4af..a812008685ce 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@@ -46,9 +46,9 @@ from posthog.models.utils import uuid7from products.actions.backend.models.action import Actionfrom products.cohorts.backend.models.cohort import Cohort-from products.web_analytics.backend.hogql_queries.stats_table import (- FIRST_PAGEVIEW_ATTRIBUTION_FEATURE_FLAG,- WebStatsTableQueryRunner,+from products.web_analytics.backend.hogql_queries.stats_table import WebStatsTableQueryRunner+from products.web_analytics.backend.hogql_queries.test.first_pageview_attribution_test_base import (+ FirstPageviewAttributionTestMixin,)from products.web_analytics.backend.hogql_queries.web_stats_lazy_precompute import can_use_lazy_precompute@@ -89,7 +89,9 @@ class FloatAwareTestCase(unittest.TestCase):@snapshot_clickhouse_queries-class TestWebStatsTableQueryRunner(ClickhouseTestMixin, APIBaseTest, FloatAwareTestCase):+class TestWebStatsTableQueryRunner(+ FirstPageviewAttributionTestMixin, ClickhouseTestMixin, APIBaseTest, FloatAwareTestCase+):QUERY_TIMESTAMP = "2025-01-29"def _calculate_pageview_statistics(self, groups_of_pageviews: list[list[PageViewProperties]]):@@ -994,32 +996,6 @@ class TestWebStatsTableQueryRunner(ClickhouseTestMixin, APIBaseTest, FloatAwareTassert [["google", (1, None), (1, None), 1 / 2, ""], [None, (1, None), (1, None), 1 / 2, ""]] == results- def _seed_ssr_poisoned_session(self):- d1 = "d1"- s1 = str(uuid7("2024-06-26"))- _create_person(team_id=self.team.pk, distinct_ids=[d1], properties={"name": d1})- _create_event(- team=self.team,- event="$feature_flag_called",- distinct_id=d1,- timestamp="2024-06-26T10:00:00",- properties={"$session_id": s1, "$referring_domain": "$direct"},- )- _create_event(- team=self.team,- event="$pageview",- distinct_id=d1,- timestamp="2024-06-26T10:00:05",- properties={- "$session_id": s1,- "$current_url": "http://example.com/landing",- "$referring_domain": "google.com",- "utm_source": "google",- "utm_medium": "cpc",- "gad_source": "1",- },- )-def _seed_first_pageview_session(self, properties, distinct_id="d1", day="2024-06-26"):session_id = str(uuid7(day))_create_person(team_id=self.team.pk, distinct_ids=[distinct_id], properties={"name": distinct_id})@@ -1032,12 +1008,6 @@ class TestWebStatsTableQueryRunner(ClickhouseTestMixin, APIBaseTest, FloatAwareT)return session_id- def _patch_first_pageview_flag(self, enabled=True):- return patch(- "products.web_analytics.backend.hogql_queries.web_analytics_query_runner.posthoganalytics.feature_enabled",- side_effect=lambda key, *args, **kwargs: enabled and key == FIRST_PAGEVIEW_ATTRIBUTION_FEATURE_FLAG,- )-def _breakdown_values(self, breakdown):return [row[0] for row in self._run_web_stats_table_query("all", "2024-06-27", breakdown_by=breakdown).results]@@ -1184,6 +1154,96 @@ class TestWebStatsTableQueryRunner(ClickhouseTestMixin, APIBaseTest, FloatAwareTassert lazy_eligible(flag_on=False) is Trueassert lazy_eligible(flag_on=True) is False+ @parameterized.expand(+ [+ ("channel_type", "$channel_type", WebStatsBreakdown.INITIAL_CHANNEL_TYPE, "Paid Search"),+ ("utm_source", "$entry_utm_source", WebStatsBreakdown.INITIAL_UTM_SOURCE, "google"),+ ("referring_domain", "$entry_referring_domain", WebStatsBreakdown.INITIAL_REFERRING_DOMAIN, "google.com"),+ ]+ )+ def test_first_pageview_attribution_rewrites_drill_down_filters(self, _name, property_key, breakdown, row_value):+ # Clicking a breakdown row filters on the stored session property, which+ # still carries the poisoned entry attribution, so the tile only returns+ # the clicked row when the filter is rewritten too.+ self._seed_ssr_poisoned_session()++ def drilled_down_values(flag_on):+ with self._patch_first_pageview_flag(enabled=flag_on):+ return [+ row[0]+ for row in self._run_web_stats_table_query(+ "all",+ "2024-06-27",+ breakdown_by=breakdown,+ properties=[+ SessionPropertyFilter(key=property_key, value=row_value, operator=PropertyOperator.EXACT)+ ],+ ).results+ ]++ assert drilled_down_values(flag_on=True) == [row_value]+ assert drilled_down_values(flag_on=False) == []++ @parameterized.expand([("bounce_rate", False), ("bounce_rate_and_avg_time", True)])+ def test_first_pageview_attribution_rewrites_drill_down_on_paths_tile(self, _name, include_avg_time_on_page):+ # The Paths tile splits user filters across three separate events scans+ # instead of the single `all_properties` clause the Sources tiles use, so+ # it needs the rewrite wired into each of them.+ self._seed_ssr_poisoned_session()++ def drilled_down_paths(flag_on):+ with self._patch_first_pageview_flag(enabled=flag_on):+ return [+ row[0]+ for row in self._run_web_stats_table_query(+ "all",+ "2024-06-27",+ breakdown_by=WebStatsBreakdown.PAGE,+ include_bounce_rate=True,+ include_avg_time_on_page=include_avg_time_on_page,+ properties=[+ SessionPropertyFilter(+ key="$channel_type", value="Paid Search", operator=PropertyOperator.EXACT+ )+ ],+ ).results+ ]++ assert drilled_down_paths(flag_on=True) == ["/landing"]+ assert drilled_down_paths(flag_on=False) == []++ def test_first_pageview_attribution_filter_changes_cache_key(self):+ query = WebStatsTableQuery(+ dateRange=DateRange(date_from="2024-06-01", date_to="2024-06-30"),+ properties=[+ SessionPropertyFilter(key="$channel_type", value="Paid Search", operator=PropertyOperator.EXACT)+ ],+ breakdownBy=WebStatsBreakdown.PAGE,+ )++ def cache_key(flag_on):+ with self._patch_first_pageview_flag(enabled=flag_on):+ return WebStatsTableQueryRunner(team=self.team, query=query).get_cache_key()++ assert cache_key(flag_on=False) != cache_key(flag_on=True)++ def test_first_pageview_attribution_filter_bypasses_preaggregated_tables(self):+ query = WebStatsTableQuery(+ dateRange=DateRange(date_from="2024-06-01", date_to="2024-06-30"),+ properties=[+ SessionPropertyFilter(key="$channel_type", value="Paid Search", operator=PropertyOperator.EXACT)+ ],+ breakdownBy=WebStatsBreakdown.PAGE,+ )++ def preagg_eligible(flag_on):+ with self._patch_first_pageview_flag(enabled=flag_on):+ runner = WebStatsTableQueryRunner(team=self.team, query=query)+ return runner.preaggregated_query_builder.can_use_preaggregated_tables()++ assert preagg_eligible(flag_on=False) is True+ assert preagg_eligible(flag_on=True) is False+def test_is_not_set_filter(self):d1 = "d1"s1 = str(uuid7("2024-06-26"))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.pyindex 55cb58dbc407..df78bb05faca 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@@ -9,7 +9,6 @@ from zoneinfo import ZoneInfofrom django.conf import settingsimport structlog-import posthoganalyticsfrom prometheus_client import Counterfrom structlog.contextvars import bound_contextvars@@ -33,7 +32,7 @@ from posthog.schema import (from posthog.hogql import astfrom posthog.hogql.errors import QueryErrorfrom posthog.hogql.parser import parse_expr, parse_select-from posthog.hogql.property import action_to_expr, apply_path_cleaning, property_to_expr+from posthog.hogql.property import action_to_expr, apply_path_cleaning, get_property_type, property_to_exprfrom posthog.hogql.query import execute_hogql_queryfrom posthog.caching.insights_api import BASE_MINIMUM_INSIGHT_REFRESH_INTERVAL, REDUCED_MINIMUM_INSIGHT_REFRESH_INTERVAL@@ -47,6 +46,12 @@ from posthog.models.filters.mixins.utils import cached_propertyfrom posthog.rbac.user_access_control import UserAccessControlfrom products.actions.backend.models.action import Action+from products.web_analytics.backend.hogql_queries.first_pageview_attribution import first_pageview_session_filter_expr+from products.web_analytics.backend.hogql_queries.first_pageview_flag import (+ evaluate_team_rollout_flag,+ first_pageview_attribution_enabled,+ rewritable_session_filters,+)from products.web_analytics.backend.hogql_queries.metrics import (WEB_ANALYTICS_QUERY_COUNTER,WEB_ANALYTICS_QUERY_DURATION,@@ -260,43 +265,10 @@ class WebAnalyticsQueryRunner(AnalyticsQueryRunner[WAR], ABC):# path for everyone on a team, so the rollout unit is the team, not the user.return percent > 0 and self.team.pk % 100 < percent- def _evaluate_team_rollout_flag(self, flag_key: str, failure_log_event: str) -> bool:- """Evaluate a team-scoped rollout flag locally — fails closed on flag-service errors.-- A raised exception here must never fail the query: evaluation failure degrades- to the flag-off path. For optimization flags that is merely the slower query- shape; for result-changing flags (first-pageview attribution) it silently- restores the old semantics, so both the exception and the None-return cases- (local evaluation unavailable) are logged to keep a fleet-wide fallback- visible during rollout.- """- try:- enabled = posthoganalytics.feature_enabled(- flag_key,- str(self.team.uuid),- groups={- "organization": str(self.team.organization_id),- "project": str(self.team.id),- },- group_properties={- "organization": {"id": str(self.team.organization_id)},- "project": {"id": str(self.team.id)},- },- only_evaluate_locally=True,- send_feature_flag_events=False,- )- if enabled is None:- logger.warning(failure_log_event, reason="feature_enabled_returned_none", team_id=self.team.pk)- return False- return bool(enabled)- except Exception as e:- logger.warning(failure_log_event, error=e, team_id=self.team.pk)- return False-@cached_propertydef _session_id_set_flag_enabled(self) -> bool:- return self._evaluate_team_rollout_flag(- SESSION_ID_SET_FEATURE_FLAG_KEY, "web_analytics_session_id_set_flag_evaluation_failed"+ return evaluate_team_rollout_flag(+ self.team, SESSION_ID_SET_FEATURE_FLAG_KEY, "web_analytics_session_id_set_flag_evaluation_failed")def _session_id_set_common_eligibility(self) -> bool:@@ -471,12 +443,74 @@ WHERE and(return preturn None+ @cached_property+ def _first_pageview_attribution_enabled(self) -> bool:+ return first_pageview_attribution_enabled(self.team)++ @cached_property+ def rewritten_first_pageview_filters(self) -> list[SessionPropertyFilter]:+ """Session-property filters this query serves with first-pageview semantics.++ Empty unless the flag is on, so every gate keyed on this is a no-op while+ it is off. The list scan runs before the flag so a query carrying no+ drill-down filter never reaches the flag service.+ """+ rewritable = rewritable_session_filters(getattr(self.query, "properties", None))+ if not rewritable or not self._first_pageview_attribution_enabled:+ return []+ return rewritable++ @cached_property+ def effective_query_properties(+ self,+ ) -> list[Union[EventPropertyFilter, PersonPropertyFilter, SessionPropertyFilter, CohortPropertyFilter]]:+ """Rewritten session filters are dropped here because+ `first_pageview_filter_exprs` carries them instead.+ """+ rewritten = {id(p) for p in self.rewritten_first_pageview_filters}+ return [p for p in (getattr(self.query, "properties", None) or []) if id(p) not in rewritten]+@cached_propertydef property_filters_without_pathname(self,) -> list[Union[EventPropertyFilter, PersonPropertyFilter, SessionPropertyFilter, CohortPropertyFilter]]:return [p for p in self.query.properties if p.key != "$pathname"]+ @cached_property+ def first_pageview_filter_exprs(self) -> list[ast.Expr]:+ """Events-side predicates replacing the rewritten session filters.++ Every events scan that turns user filters into a WHERE clause must+ include these alongside `effective_query_properties`, or that scan+ silently ignores the drill-down filter the rest of the scene is applying+ and its tile disagrees with the row the user clicked.+ """+ return [+ first_pageview_session_filter_expr(+ p,+ team=self.team,+ inside_periods=self._periods_expression(),+ event_where=self.event_type_expr,+ session_id_present=self.events_session_id_present,+ outer_session_id=ast.Field(chain=["events", "$session_id"]),+ modifiers=self.modifiers,+ timings=self.timings,+ )+ for p in self.rewritten_first_pageview_filters+ ]++ def all_properties(self) -> ast.Expr:+ return property_to_expr(+ [*self.effective_query_properties, *self.first_pageview_filter_exprs, *self._test_account_filters],+ team=self.team,+ )++ def session_properties(self) -> ast.Expr:+ properties = [+ p for p in self.effective_query_properties + self._test_account_filters if get_property_type(p) == "session"+ ]+ return property_to_expr(properties, team=self.team, scope="event")+@cached_propertydef conversion_goal_expr(self) -> Optional[ast.Expr]:if isinstance(self.query.conversionGoal, ActionConversionGoal):@@ -645,7 +679,12 @@ WHERE and()def events_where(self):- properties = [self.events_where_data_range(), self.query.properties, self._test_account_filters]+ properties = [+ self.events_where_data_range(),+ self.effective_query_properties,+ self.first_pageview_filter_exprs,+ self._test_account_filters,+ ]return property_to_expr(properties,@@ -722,7 +761,12 @@ WHERE and(# (the kill switch) must not keep serving cached precompute-produced# responses until they stale out.precompute = is_precompute_enabled_for_team(self.team)- return f"{original}_{self.team.path_cleaning_filters}_pc{int(precompute)}"+ key = f"{original}_{self.team.path_cleaning_filters}_pc{int(precompute)}"+ # A rewritten filter selects a different population for the same query, so+ # rewritten and entry-attributed runs must not share cache entries.+ if self.rewritten_first_pageview_filters:+ key = f"{key}_fpfilters"+ return key@cached_propertydef events_session_property(self):diff --git a/products/web_analytics/backend/hogql_queries/web_goals.py b/products/web_analytics/backend/hogql_queries/web_goals.pyindex a672949cd287..fda88da53395 100644--- a/products/web_analytics/backend/hogql_queries/web_goals.py+++ b/products/web_analytics/backend/hogql_queries/web_goals.py@@ -347,13 +347,10 @@ WHERE {periods_expression})def 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"]- ]- return property_to_expr(properties, team=self.team, scope="event")-- def session_properties(self) -> ast.Expr:- properties = [- p for p in self.query.properties + self._test_account_filters if get_property_type(p) == "session"+ properties: list = [+ p+ for p in self.effective_query_properties + self._test_account_filters+ if get_property_type(p) in ["event", "person"]]+ properties.extend(self.first_pageview_filter_exprs)return property_to_expr(properties, team=self.team, scope="event")diff --git a/products/web_analytics/backend/hogql_queries/web_overview.py b/products/web_analytics/backend/hogql_queries/web_overview.pyindex f4294f704296..edd395eebb54 100644--- a/products/web_analytics/backend/hogql_queries/web_overview.py+++ b/products/web_analytics/backend/hogql_queries/web_overview.py@@ -409,10 +409,6 @@ CROSS JOIN {sessions_agg} AS sessions_agg),)- def all_properties(self) -> ast.Expr:- properties = self.query.properties + self._test_account_filters- return property_to_expr(properties, team=self.team)-@cached_propertydef pageview_count_expression(self) -> ast.Expr:return ast.Call(diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 55634d46f19d..1ff666b82672 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -691,6 +691,8 @@ export namespace Schemas {/** Try to automatically convert HogQL queries to use preaggregated tables at the AST level * */usePreaggregatedTableTransforms?: boolean | null;useWebAnalyticsPreAggregatedTables?: boolean | null;+ /** Serve filters on the stored session-entry attribution properties (`$channel_type`, `$entry_utm_*`, `$entry_referring_domain`) by recomputing the value from the session's first pageview. Resolved server-side; not intended to be set by clients. */+ webAnalyticsFirstPageviewFilters?: boolean | null;}export interface ClickhouseQueryProgress {