:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(web-analytics): Add first-pageview attribution for entry breakdowns (#73570)
Jordan Mryyan59674813f052
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 0ea7018963f1..80e4d3ae5caf 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -50615,6 +50615,14 @@"InitialUTMTerm","InitialUTMContent","InitialUTMSourceMediumCampaign",+ "FirstPageviewChannelType",+ "FirstPageviewReferringDomain",+ "FirstPageviewUTMSource",+ "FirstPageviewUTMCampaign",+ "FirstPageviewUTMMedium",+ "FirstPageviewUTMTerm",+ "FirstPageviewUTMContent",+ "FirstPageviewUTMSourceMediumCampaign","Browser","OS","Viewport",diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 0bbb72079d50..4f63fdd4a55d 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -3004,6 +3004,14 @@ export enum WebStatsBreakdown {InitialUTMTerm = 'InitialUTMTerm',InitialUTMContent = 'InitialUTMContent',InitialUTMSourceMediumCampaign = 'InitialUTMSourceMediumCampaign',+ FirstPageviewChannelType = 'FirstPageviewChannelType',+ FirstPageviewReferringDomain = 'FirstPageviewReferringDomain',+ FirstPageviewUTMSource = 'FirstPageviewUTMSource',+ FirstPageviewUTMCampaign = 'FirstPageviewUTMCampaign',+ FirstPageviewUTMMedium = 'FirstPageviewUTMMedium',+ FirstPageviewUTMTerm = 'FirstPageviewUTMTerm',+ FirstPageviewUTMContent = 'FirstPageviewUTMContent',+ FirstPageviewUTMSourceMediumCampaign = 'FirstPageviewUTMSourceMediumCampaign',Browser = 'Browser',OS = 'OS',Viewport = 'Viewport',diff --git a/frontend/src/scenes/web-analytics/common.ts b/frontend/src/scenes/web-analytics/common.tsindex 9cdbd6f09de1..ae33f6464de0 100644--- a/frontend/src/scenes/web-analytics/common.ts+++ b/frontend/src/scenes/web-analytics/common.ts@@ -457,6 +457,17 @@ export const webStatsBreakdownToPropertyName = (return { key: '$pathname', type: PropertyFilterType.Event }case WebStatsBreakdown.InitialUTMSourceMediumCampaign:return undefined+ case WebStatsBreakdown.FirstPageviewChannelType:+ case WebStatsBreakdown.FirstPageviewReferringDomain:+ case WebStatsBreakdown.FirstPageviewUTMSource:+ case WebStatsBreakdown.FirstPageviewUTMCampaign:+ case WebStatsBreakdown.FirstPageviewUTMMedium:+ case WebStatsBreakdown.FirstPageviewUTMTerm:+ case WebStatsBreakdown.FirstPageviewUTMContent:+ case WebStatsBreakdown.FirstPageviewUTMSourceMediumCampaign:+ // Computed per-session from the first pageview at query time — there is+ // no stored property to filter sessions by.+ return undefineddefault:throw new UnexpectedNeverError(breakdownBy)}@@ -604,6 +615,22 @@ export const getDisplayColumnName = (column: string, breakdownBy?: WebStatsBreakreturn 'URL'case WebStatsBreakdown.InitialUTMSourceMediumCampaign:return 'Source / Medium / Campaign'+ case WebStatsBreakdown.FirstPageviewChannelType:+ return 'Channel Type (First Pageview)'+ case WebStatsBreakdown.FirstPageviewReferringDomain:+ return 'Referring Domain (First Pageview)'+ case WebStatsBreakdown.FirstPageviewUTMSource:+ return 'UTM Source (First Pageview)'+ case WebStatsBreakdown.FirstPageviewUTMCampaign:+ return 'UTM Campaign (First Pageview)'+ case WebStatsBreakdown.FirstPageviewUTMMedium:+ return 'UTM Medium (First Pageview)'+ case WebStatsBreakdown.FirstPageviewUTMTerm:+ return 'UTM Term (First Pageview)'+ case WebStatsBreakdown.FirstPageviewUTMContent:+ return 'UTM Content (First Pageview)'+ case WebStatsBreakdown.FirstPageviewUTMSourceMediumCampaign:+ return 'Source / Medium / Campaign (First Pageview)'}}diff --git a/frontend/src/scenes/web-analytics/tiles/WebAnalyticsTile.tsx b/frontend/src/scenes/web-analytics/tiles/WebAnalyticsTile.tsxindex cc989f2eb73a..573d20bc811a 100644--- a/frontend/src/scenes/web-analytics/tiles/WebAnalyticsTile.tsx+++ b/frontend/src/scenes/web-analytics/tiles/WebAnalyticsTile.tsx@@ -321,6 +321,22 @@ const BreakdownValueTitle: QueryContextColumnTitleComponent = (props) => {return <>URL</>case WebStatsBreakdown.InitialUTMSourceMediumCampaign:return <>Source / Medium / Campaign</>+ case WebStatsBreakdown.FirstPageviewChannelType:+ return <>Channel Type (First Pageview)</>+ case WebStatsBreakdown.FirstPageviewReferringDomain:+ return <>Referring Domain (First Pageview)</>+ case WebStatsBreakdown.FirstPageviewUTMSource:+ return <>UTM Source (First Pageview)</>+ case WebStatsBreakdown.FirstPageviewUTMCampaign:+ return <>UTM Campaign (First Pageview)</>+ case WebStatsBreakdown.FirstPageviewUTMMedium:+ return <>UTM Medium (First Pageview)</>+ case WebStatsBreakdown.FirstPageviewUTMTerm:+ return <>UTM Term (First Pageview)</>+ case WebStatsBreakdown.FirstPageviewUTMContent:+ return <>UTM Content (First Pageview)</>+ case WebStatsBreakdown.FirstPageviewUTMSourceMediumCampaign:+ return <>Source / Medium / Campaign (First Pageview)</>default:throw new UnexpectedNeverError(breakdownBy)}@@ -445,6 +461,7 @@ const BreakdownValueCell: QueryContextColumnComponent = (props) => {}return <NotSetBreakdownLabel />case WebStatsBreakdown.InitialReferringDomain:+ case WebStatsBreakdown.FirstPageviewReferringDomain:// NULL referrer is canonically "Direct" in PostHog (matches the channel-type// bucketing in sessions_v2). Keep that wording to stay consistent across tiles.if (value == null) {@@ -468,6 +485,7 @@ const BreakdownValueCell: QueryContextColumnComponent = (props) => {}breakcase WebStatsBreakdown.InitialUTMSourceMediumCampaign:+ case WebStatsBreakdown.FirstPageviewUTMSourceMediumCampaign:if (typeof value === 'string') {return <>{value.replace(BREAKDOWN_REFERRER_PREFIX, '')}</>}@@ -477,6 +495,11 @@ const BreakdownValueCell: QueryContextColumnComponent = (props) => {case WebStatsBreakdown.InitialUTMCampaign:case WebStatsBreakdown.InitialUTMTerm:case WebStatsBreakdown.InitialUTMContent:+ case WebStatsBreakdown.FirstPageviewUTMSource:+ case WebStatsBreakdown.FirstPageviewUTMMedium:+ case WebStatsBreakdown.FirstPageviewUTMCampaign:+ case WebStatsBreakdown.FirstPageviewUTMTerm:+ case WebStatsBreakdown.FirstPageviewUTMContent:return typeof value === 'string' ? <>{value}</> : <NotSetBreakdownLabel />}diff --git a/posthog/schema_enums.py b/posthog/schema_enums.pyindex 8757c853b125..cb16e913ec1f 100644--- a/posthog/schema_enums.py+++ b/posthog/schema_enums.py@@ -4003,6 +4003,14 @@ class WebStatsBreakdown(StrEnum):INITIAL_UTM_TERM = "InitialUTMTerm"INITIAL_UTM_CONTENT = "InitialUTMContent"INITIAL_UTM_SOURCE_MEDIUM_CAMPAIGN = "InitialUTMSourceMediumCampaign"+ FIRST_PAGEVIEW_CHANNEL_TYPE = "FirstPageviewChannelType"+ FIRST_PAGEVIEW_REFERRING_DOMAIN = "FirstPageviewReferringDomain"+ FIRST_PAGEVIEW_UTM_SOURCE = "FirstPageviewUTMSource"+ FIRST_PAGEVIEW_UTM_CAMPAIGN = "FirstPageviewUTMCampaign"+ FIRST_PAGEVIEW_UTM_MEDIUM = "FirstPageviewUTMMedium"+ FIRST_PAGEVIEW_UTM_TERM = "FirstPageviewUTMTerm"+ FIRST_PAGEVIEW_UTM_CONTENT = "FirstPageviewUTMContent"+ FIRST_PAGEVIEW_UTM_SOURCE_MEDIUM_CAMPAIGN = "FirstPageviewUTMSourceMediumCampaign"BROWSER = "Browser"OS = "OS"VIEWPORT = "Viewport"diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.tsindex 2639a6ea8d84..7678b2f300bf 100644--- a/products/dashboards/frontend/generated/api.schemas.ts+++ b/products/dashboards/frontend/generated/api.schemas.ts@@ -3675,6 +3675,14 @@ export const WebStatsBreakdownApi = {InitialUTMTerm: 'InitialUTMTerm',InitialUTMContent: 'InitialUTMContent',InitialUTMSourceMediumCampaign: 'InitialUTMSourceMediumCampaign',+ FirstPageviewChannelType: 'FirstPageviewChannelType',+ FirstPageviewReferringDomain: 'FirstPageviewReferringDomain',+ FirstPageviewUTMSource: 'FirstPageviewUTMSource',+ FirstPageviewUTMCampaign: 'FirstPageviewUTMCampaign',+ FirstPageviewUTMMedium: 'FirstPageviewUTMMedium',+ FirstPageviewUTMTerm: 'FirstPageviewUTMTerm',+ FirstPageviewUTMContent: 'FirstPageviewUTMContent',+ FirstPageviewUTMSourceMediumCampaign: 'FirstPageviewUTMSourceMediumCampaign',Browser: 'Browser',Os: 'OS',Viewport: 'Viewport',diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.tsindex 3c14d3969305..3e80e6c21362 100644--- a/products/product_analytics/frontend/generated/api.schemas.ts+++ b/products/product_analytics/frontend/generated/api.schemas.ts@@ -3007,6 +3007,14 @@ export const WebStatsBreakdownApi = {InitialUTMTerm: 'InitialUTMTerm',InitialUTMContent: 'InitialUTMContent',InitialUTMSourceMediumCampaign: 'InitialUTMSourceMediumCampaign',+ FirstPageviewChannelType: 'FirstPageviewChannelType',+ FirstPageviewReferringDomain: 'FirstPageviewReferringDomain',+ FirstPageviewUTMSource: 'FirstPageviewUTMSource',+ FirstPageviewUTMCampaign: 'FirstPageviewUTMCampaign',+ FirstPageviewUTMMedium: 'FirstPageviewUTMMedium',+ FirstPageviewUTMTerm: 'FirstPageviewUTMTerm',+ FirstPageviewUTMContent: 'FirstPageviewUTMContent',+ FirstPageviewUTMSourceMediumCampaign: 'FirstPageviewUTMSourceMediumCampaign',Browser: 'Browser',Os: 'OS',Viewport: 'Viewport',diff --git a/products/web_analytics/backend/hogql_queries/query_constants/stats_table_queries.py b/products/web_analytics/backend/hogql_queries/query_constants/stats_table_queries.pyindex cc2fec473c4b..9dedeab616e9 100644--- a/products/web_analytics/backend/hogql_queries/query_constants/stats_table_queries.py+++ b/products/web_analytics/backend/hogql_queries/query_constants/stats_table_queries.py@@ -182,6 +182,43 @@ WHERE and({inside_periods}, {event_where}, {all_properties})GROUP BY session_id, breakdown_value"""+# Inner scan for the FirstPageview* breakdowns: one row per session, with the+# breakdown value computed from the session's earliest in-range $pageview/$screen.+# Two levels on purpose — the argMinIf aggregate must sit behind an alias so the+# breakdown expression compares plain subquery fields: a comparison whose subtree+# contains events.timestamp is treated as non-nullable by the printer's timestamp+# index optimization (see visit_compare_operation in posthog/hogql/printer/clickhouse.py),+# which turns the channel-type template's IS [NOT] NULL checks into dead+# `equals(x, NULL)` SQL. {first_pageview_properties} is a single argMinIf over a+# tuple, so every property comes from the same anchor event rather than each+# property independently skipping NULLs across different pageviews.+# Events without a usable session id are excluded ({session_id_present}): they+# can't be attributed to a session's first pageview, and GROUP BY session_id+# would otherwise merge them all into one arbitrary group. argMinIf only sees+# in-range events, so a session straddling date_from is attributed to its first+# *in-range* pageview — accepted drift vs the session-entry breakdowns at range edges.+FIRST_PAGEVIEW_INNER_QUERY = """+SELECT+ filtered_person_id,+ filtered_pageview_count,+ {breakdown_value} AS breakdown_value,+ session_id,+ is_bounce,+ start_timestamp+FROM (+ SELECT+ any(person_id) AS filtered_person_id,+ count() AS filtered_pageview_count,+ {first_pageview_properties} AS first_pageview_properties,+ session.session_id AS session_id,+ any(session.$is_bounce) AS is_bounce,+ min(session.$start_timestamp) AS start_timestamp+ FROM events+ WHERE and({inside_periods}, {event_where}, {all_properties}, {session_id_present})+ GROUP BY session_id+)+"""+# No-join variant of MAIN_INNER_QUERY for simple breakdowns that display no# session-derived column (no bounce, no conversion goal, event-property# breakdown value). The sessions join above contributes only `session_id`diff --git a/products/web_analytics/backend/hogql_queries/stats_table.py b/products/web_analytics/backend/hogql_queries/stats_table.pyindex 240e809988f1..21b3b1a14e83 100644--- a/products/web_analytics/backend/hogql_queries/stats_table.py+++ b/products/web_analytics/backend/hogql_queries/stats_table.py@@ -18,6 +18,7 @@ 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,@@ -35,6 +36,7 @@ from posthog.models.filters.mixins.utils import cached_propertyfrom products.web_analytics.backend.hogql_queries.stats_table_pre_aggregated import StatsTablePreAggregatedQueryBuilderfrom products.web_analytics.backend.hogql_queries.stats_table_strategies import (ChannelTypeStrategy,+ FirstPageviewAttributionStrategy,FrustrationMetricsStrategy,NoJoinPathBounceAvgTimeStrategy,NoJoinPathBounceStrategy,@@ -64,6 +66,56 @@ 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@@ -172,6 +224,8 @@ class WebStatsTableQueryRunner(WebAnalyticsQueryRunner[WebStatsTableQueryRespons# ChannelTypeStrategy must be checked before SimpleBreakdownStrategy since it's a subclass.if isinstance(strategy, ChannelTypeStrategy):return "stats_table_channel_type"+ if isinstance(strategy, FirstPageviewAttributionStrategy):+ return "stats_table_first_pageview_attribution"# NoJoinSimpleBreakdownStrategy is also a SimpleBreakdownStrategy subclass.if isinstance(strategy, NoJoinSimpleBreakdownStrategy):return "stats_table_no_join_simple_breakdown"@@ -185,11 +239,35 @@ 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:+ return remapped+ return self.query.breakdownBy++ def get_cache_key(self) -> str:+ # The remap changes results for the same query, so remapped and+ # entry-attributed runs must not share cache entries — and rolling the+ # flag back to 0% must instantly serve the old key again.+ original = super().get_cache_key()+ effective_breakdown = self._effective_breakdown()+ if effective_breakdown != self.query.breakdownBy:+ return f"{original}_{effective_breakdown.value}"+ return original+def _get_strategy(self) -> StatsTableQueryStrategy:- if self.query.breakdownBy == WebStatsBreakdown.FRUSTRATION_METRICS:+ breakdown = self._effective_breakdown()++ if breakdown == WebStatsBreakdown.FRUSTRATION_METRICS:return FrustrationMetricsStrategy(self)- if self.query.breakdownBy == WebStatsBreakdown.PAGE:+ if breakdown == WebStatsBreakdown.PAGE:if self.query.conversionGoal:return SimpleBreakdownStrategy(self)if self.query.includeAvgTimeOnPage:@@ -205,12 +283,15 @@ class WebStatsTableQueryRunner(WebAnalyticsQueryRunner[WebStatsTableQueryResponsreturn SessionIdSetPathBounceStrategy(self)return PathBounceStrategy(self)- if self.query.breakdownBy == WebStatsBreakdown.INITIAL_PAGE and self.query.includeBounceRate:+ if breakdown == WebStatsBreakdown.INITIAL_PAGE and self.query.includeBounceRate:return SimpleBreakdownStrategy(self, breakdown_override=self._bounce_entry_pathname_breakdown())- if self.query.breakdownBy == WebStatsBreakdown.INITIAL_CHANNEL_TYPE:+ if breakdown == WebStatsBreakdown.INITIAL_CHANNEL_TYPE:return ChannelTypeStrategy(self)+ if breakdown in FIRST_PAGEVIEW_BREAKDOWNS:+ return FirstPageviewAttributionStrategy(self)+# Simple breakdowns whose displayed columns are all event-derived don't# need the events↔sessions join at all — the join only supplies the# session grouping key and start timestamp, both recoverable from the@@ -813,8 +894,100 @@ WHERE and(],)+ def _source_medium_campaign_expr(+ self, source: ast.Expr, referring_domain: ast.Expr, medium: ast.Expr, campaign: ast.Expr+ ) -> ast.Expr:+ # The source part uses a prefix so the frontend can distinguish+ # whether the value came from utm_source or the referring domain.+ source_expr = ast.Call(+ name="if",+ args=[+ ast.Call(name="isNotNull", args=[source]),+ source,+ ast.Call(+ name="if",+ args=[+ ast.Call(name="isNotNull", args=[referring_domain]),+ ast.Call(name="concat", args=[ast.Constant(value=BREAKDOWN_REFERRER_PREFIX), referring_domain]),+ ast.Constant(value=BREAKDOWN_NULL_DISPLAY),+ ],+ ),+ ],+ )+ return ast.Call(+ name="concatWithSeparator",+ args=[+ ast.Constant(value=" / "),+ source_expr,+ coalesce_with_null_display(medium),+ coalesce_with_null_display(campaign),+ ],+ )++ 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')"),+ ],+ )++ 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=""),+ ],+ )++ def _first_pageview_utm_source_medium_campaign(self) -> ast.Expr:+ return self._source_medium_campaign_expr(+ source=self._first_pageview_prop("utm_source"),+ referring_domain=self._first_pageview_prop("$referring_domain"),+ medium=self._first_pageview_prop("utm_medium"),+ 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.query.breakdownBy:+ match self._effective_breakdown():case WebStatsBreakdown.PAGE:path = self._apply_path_cleaning(ast.Field(chain=["events", "properties", "$pathname"]))if self.query.includeHost:@@ -881,44 +1054,28 @@ WHERE and(case WebStatsBreakdown.INITIAL_CHANNEL_TYPE:return ast.Field(chain=["session", "$channel_type"])case WebStatsBreakdown.INITIAL_UTM_SOURCE_MEDIUM_CAMPAIGN:- # The source part uses a prefix so the frontend can distinguish- # whether the value came from $entry_utm_source or $entry_referring_domain- source_expr = ast.Call(- name="if",- args=[- ast.Call(- name="isNotNull",- args=[ast.Field(chain=["session", "$entry_utm_source"])],- ),- ast.Field(chain=["session", "$entry_utm_source"]),- ast.Call(- name="if",- args=[- ast.Call(- name="isNotNull",- args=[ast.Field(chain=["session", "$entry_referring_domain"])],- ),- ast.Call(- name="concat",- args=[- ast.Constant(value=BREAKDOWN_REFERRER_PREFIX),- ast.Field(chain=["session", "$entry_referring_domain"]),- ],- ),- ast.Constant(value=BREAKDOWN_NULL_DISPLAY),- ],- ),- ],- )- return ast.Call(- name="concatWithSeparator",- args=[- ast.Constant(value=" / "),- source_expr,- coalesce_with_null_display(ast.Field(chain=["session", "$entry_utm_medium"])),- coalesce_with_null_display(ast.Field(chain=["session", "$entry_utm_campaign"])),- ],+ return self._source_medium_campaign_expr(+ source=ast.Field(chain=["session", "$entry_utm_source"]),+ referring_domain=ast.Field(chain=["session", "$entry_referring_domain"]),+ 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 WebStatsBreakdown.BROWSER:return ast.Field(chain=["properties", "$browser"])case WebStatsBreakdown.OS:@@ -972,7 +1129,7 @@ WHERE and(raise NotImplementedError("Aggregation value not exists")def outer_where_breakdown(self) -> ast.Expr | None:- match self.query.breakdownBy:+ match self._effective_breakdown():case WebStatsBreakdown.REGION | WebStatsBreakdown.CITY:# Country (element 1) must be present; region/city (element 2) may be NULL when# GeoIP can't resolve the subdivision/city — those rows surface in the UI as@@ -1000,9 +1157,15 @@ WHERE and(| WebStatsBreakdown.INITIAL_UTM_MEDIUM| WebStatsBreakdown.INITIAL_UTM_TERM| WebStatsBreakdown.INITIAL_UTM_CONTENT+ | WebStatsBreakdown.FIRST_PAGEVIEW_REFERRING_DOMAIN+ | WebStatsBreakdown.FIRST_PAGEVIEW_UTM_SOURCE+ | WebStatsBreakdown.FIRST_PAGEVIEW_UTM_CAMPAIGN+ | WebStatsBreakdown.FIRST_PAGEVIEW_UTM_MEDIUM+ | WebStatsBreakdown.FIRST_PAGEVIEW_UTM_TERM+ | WebStatsBreakdown.FIRST_PAGEVIEW_UTM_CONTENT):return None- case WebStatsBreakdown.INITIAL_CHANNEL_TYPE:+ case WebStatsBreakdown.INITIAL_CHANNEL_TYPE | WebStatsBreakdown.FIRST_PAGEVIEW_CHANNEL_TYPE:return parse_expr("`context.columns.breakdown_value` IS NOT NULL AND `context.columns.breakdown_value` != ''") # we need to check for empty strings as well due to how the left join worksdiff --git a/products/web_analytics/backend/hogql_queries/stats_table_pre_aggregated.py b/products/web_analytics/backend/hogql_queries/stats_table_pre_aggregated.pyindex cc46e8056a91..4d295d0ef31b 100644--- a/products/web_analytics/backend/hogql_queries/stats_table_pre_aggregated.py+++ b/products/web_analytics/backend/hogql_queries/stats_table_pre_aggregated.py@@ -61,7 +61,7 @@ class StatsTablePreAggregatedQueryBuilder(WebAnalyticsPreAggregatedQueryBuilder)if not super().can_use_preaggregated_tables():return False- return self.runner.query.breakdownBy in WEB_ANALYTICS_STATS_TABLE_PRE_AGGREGATED_SUPPORTED_BREAKDOWNS+ return self.runner._effective_breakdown() in WEB_ANALYTICS_STATS_TABLE_PRE_AGGREGATED_SUPPORTED_BREAKDOWNSdef _get_channel_type_expr(self) -> ast.Expr:"""Create a channel type expression using the available fields in pre-aggregated tables."""diff --git a/products/web_analytics/backend/hogql_queries/stats_table_strategies.py b/products/web_analytics/backend/hogql_queries/stats_table_strategies.pyindex 31a57501c3c8..669700175c12 100644--- a/products/web_analytics/backend/hogql_queries/stats_table_strategies.py+++ b/products/web_analytics/backend/hogql_queries/stats_table_strategies.py@@ -7,6 +7,7 @@ from posthog.hogql import astfrom posthog.hogql.parser import parse_expr, parse_selectfrom products.web_analytics.backend.hogql_queries.query_constants.stats_table_queries import (+ FIRST_PAGEVIEW_INNER_QUERY,FRUSTRATION_METRICS_INNER_QUERY,MAIN_INNER_QUERY,NO_JOIN_MAIN_INNER_QUERY,@@ -56,6 +57,9 @@ class SimpleBreakdownStrategy(StatsTableQueryStrategy):is identical."""+ # Inner scan template; subclasses swap it to change only the events aggregation.+ INNER_QUERY = MAIN_INNER_QUERY+def __init__(self,runner: WebStatsTableQueryRunner,@@ -129,7 +133,7 @@ class SimpleBreakdownStrategy(StatsTableQueryStrategy):def _inner_query(self, breakdown: ast.Expr) -> ast.SelectQuery:query = parse_select(- MAIN_INNER_QUERY,+ self.INNER_QUERY,timings=self.runner.timings,placeholders={"breakdown_value": breakdown,@@ -194,6 +198,50 @@ class ChannelTypeStrategy(SimpleBreakdownStrategy):SQL is the same template."""+class FirstPageviewAttributionStrategy(SimpleBreakdownStrategy):+ """Breakdowns attributed to the session's first ``$pageview``/``$screen``.++ Same outer query as ``SimpleBreakdownStrategy``, but the inner scan is two+ levels: a per-session aggregate (``GROUP BY session_id`` with a single+ ``argMinIf`` tuple anchoring every property to the earliest in-range+ pageview) wrapped in a projection that computes the breakdown value from+ the aliased tuple. See ``FIRST_PAGEVIEW_INNER_QUERY`` for why the aggregate+ must be aliased. Conversion aggregates go into the per-session level, with+ pass-through columns added to the projection.+ """++ INNER_QUERY = FIRST_PAGEVIEW_INNER_QUERY++ def _inner_query(self, breakdown: ast.Expr) -> ast.SelectQuery:+ query = parse_select(+ self.INNER_QUERY,+ timings=self.runner.timings,+ placeholders={+ "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(),+ "inside_periods": self.runner._periods_expression(),+ "session_id_present": self.runner.events_session_id_present,+ },+ )++ assert isinstance(query, ast.SelectQuery)++ if self.runner.conversion_count_expr and self.runner.conversion_person_id_expr:+ assert query.select_from is not None+ per_session_query = query.select_from.table+ assert isinstance(per_session_query, ast.SelectQuery)+ per_session_query.select.append(ast.Alias(alias="conversion_count", expr=self.runner.conversion_count_expr))+ per_session_query.select.append(+ ast.Alias(alias="conversion_person_id", expr=self.runner.conversion_person_id_expr)+ )+ query.select.append(ast.Field(chain=["conversion_count"]))+ query.select.append(ast.Field(chain=["conversion_person_id"]))++ return query++class PathBounceStrategy(StatsTableQueryStrategy):"""PAGE breakdown with bounce rate (no scroll depth or avg time)."""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 6b5d08a7346d..1cf39610fcd3 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@@ -1957,6 +1957,1016 @@use_hive_partitioning=0'''# ---+# name: TestWebStatsTableQueryRunner.test_first_pageview_attribution_anchors_all_properties_to_one_event+ '''+ 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_anchors_all_properties_to_one_event.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')), 1, 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_anchors_all_properties_to_one_event.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 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')), 1, 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_excludes_sessionless_events+ '''+ 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_excludes_sessionless_events.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')), 1, 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_flag_flips_initial_breakdowns+ '''+ 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_flag_flips_initial_breakdowns.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 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')), 1))+ 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_flag_flips_initial_breakdowns.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')), 1))+ 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_flag_flips_initial_breakdowns.3+ '''+ 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')), 1, 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_flag_flips_initial_breakdowns.4+ '''+ 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')), 1, 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_ignores_conversion_goal_events+ '''+ 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_ignores_conversion_goal_events.1+ '''+ SELECT breakdown_value AS `context.columns.breakdown_value`,+ tuple(uniq(filtered_person_id), NULL) AS `context.columns.visitors`,+ tuple(sum(conversion_count), NULL) AS `context.columns.total_conversions`,+ tuple(uniq(conversion_person_id), NULL) AS `context.columns.unique_conversions`,+ tuple(if(equals(`context.columns.visitors`.1, 0), NULL, divide(`context.columns.unique_conversions`.1, `context.columns.visitors`.1)), if(ifNull(equals(`context.columns.visitors`.2, 0), 0), NULL, divide(`context.columns.unique_conversions`.2, `context.columns.visitors`.2))) AS `context.columns.conversion_rate`,+ divide(`context.columns.unique_conversions`.1, sum(`context.columns.unique_conversions`.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,+ conversion_count AS conversion_count,+ conversion_person_id AS conversion_person_id+ 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,+ countIf(equals(events.event, 'custom_event')) AS conversion_count,+ any(if(equals(events.event, 'custom_event'), if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), NULL)) AS conversion_person_id+ 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'), equals(events.event, 'custom_event')), 1, isNotNull(events.`$session_id_uuid`)))+ GROUP BY session_id))+ GROUP BY `context.columns.breakdown_value`+ ORDER BY `context.columns.unique_conversions` DESC,+ `context.columns.total_conversions` DESC,+ `context.columns.visitors` 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_ignores_non_pageview_first_event+ '''+ 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_ignores_non_pageview_first_event.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 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')), 1))+ 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_ignores_non_pageview_first_event.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')), 1))+ 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_ignores_non_pageview_first_event.3+ '''+ 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')), 1, 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_ignores_non_pageview_first_event.4+ '''+ 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')), 1, 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_channel_type_buckets_0_referral_unknown_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_channel_type_buckets_0_referral_unknown_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,+ 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')), 1, 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_channel_type_buckets_1_gad_source_only+ '''+ 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_channel_type_buckets_1_gad_source_only.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')), 1, 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_channel_type_buckets_2_bare_direct+ '''+ 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_channel_type_buckets_2_bare_direct.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')), 1, 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_include_host_concatenates_host_and_path_0_Page'''SELECT toTimeZone(events.timestamp, 'UTC') AS timestampdiff --git a/products/web_analytics/backend/hogql_queries/test/test_web_stats_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_stats_lazy_precompute.pyindex 546bc3491931..3c71ec0083e3 100644--- a/products/web_analytics/backend/hogql_queries/test/test_web_stats_lazy_precompute.py+++ b/products/web_analytics/backend/hogql_queries/test/test_web_stats_lazy_precompute.py@@ -28,6 +28,8 @@ from posthog.models.utils import uuid7from products.analytics_platform.backend.models.preaggregation_job import PreaggregationJobfrom products.web_analytics.backend.hogql_queries.stats_table import WebStatsTableQueryRunner+from products.web_analytics.backend.hogql_queries.web_analytics_query_runner import SESSION_ID_SET_FEATURE_FLAG_KEY+from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import ORG_FEATURE_FLAG_KEYfrom products.web_analytics.backend.hogql_queries.web_stats_lazy_precompute import _breakdown_having_expr# Low-cardinality breakdowns with a generic seed that have data and are cheap to@@ -60,12 +62,13 @@ class TestWebStatsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):sync_execute("SYSTEM STOP TTL MERGES sharded_web_stats_preaggregated")def _enable_lazy(self):- # Mock the org-level feature flag check to True. Outside this context- # manager the default `posthoganalytics.feature_enabled` returns False- # (no API key in tests), which models a flag-disabled org.+ # Mock the precompute feature flag checks to True. Outside this context manager+ # the default `posthoganalytics.feature_enabled` returns False (no API key in+ # tests), which models a flag-disabled org. The patch target is the shared+ # `posthoganalytics` module, so an unscoped True would enable other rollouts too.return patch("products.web_analytics.backend.hogql_queries.web_lazy_precompute_common.posthoganalytics.feature_enabled",- return_value=True,+ side_effect=lambda key, *args, **kwargs: key in (ORG_FEATURE_FLAG_KEY, SESSION_ID_SET_FEATURE_FLAG_KEY),)def _props(self, **overrides) -> dict: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 517ab594d317..dad707a7b4af 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,7 +46,11 @@ 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 WebStatsTableQueryRunner+from products.web_analytics.backend.hogql_queries.stats_table import (+ FIRST_PAGEVIEW_ATTRIBUTION_FEATURE_FLAG,+ WebStatsTableQueryRunner,+)+from products.web_analytics.backend.hogql_queries.web_stats_lazy_precompute import can_use_lazy_precomputenan_value = float("nan")@@ -990,6 +994,196 @@ 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})+ _create_event(+ team=self.team,+ event="$pageview",+ distinct_id=distinct_id,+ timestamp=f"{day}T10:00:00",+ properties={"$session_id": session_id, **properties},+ )+ 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]++ def test_first_pageview_attribution_ignores_non_pageview_first_event(self):+ self._seed_ssr_poisoned_session()++ assert self._breakdown_values(WebStatsBreakdown.INITIAL_UTM_SOURCE) == [None]+ assert self._breakdown_values(WebStatsBreakdown.INITIAL_CHANNEL_TYPE) == ["Direct"]++ assert self._breakdown_values(WebStatsBreakdown.FIRST_PAGEVIEW_UTM_SOURCE) == ["google"]+ assert self._breakdown_values(WebStatsBreakdown.FIRST_PAGEVIEW_CHANNEL_TYPE) == ["Paid Search"]++ @parameterized.expand(+ [+ ("referral_unknown_domain", {"$referring_domain": "someblog.example"}, "Referral"),+ ("gad_source_only", {"$referring_domain": "$direct", "gad_source": "1"}, "Paid Search"),+ ("bare_direct", {"$referring_domain": "$direct"}, "Direct"),+ ]+ )+ def test_first_pageview_channel_type_buckets(self, _name, properties, expected):+ # These buckets all depend on the IS [NOT] NULL branches of the channel+ # type expression, which silently die (print as comparisons against a+ # NULL literal) if the argMin aggregate leaks into the comparisons.+ self._seed_first_pageview_session(properties)++ assert self._breakdown_values(WebStatsBreakdown.FIRST_PAGEVIEW_CHANNEL_TYPE) == [expected]++ def test_first_pageview_attribution_ignores_conversion_goal_events(self):+ d1, day = "d1", "2024-06-26"+ s1 = str(uuid7(day))+ _create_person(team_id=self.team.pk, distinct_ids=[d1], properties={"name": d1})+ _create_event(+ team=self.team,+ event="custom_event",+ distinct_id=d1,+ timestamp=f"{day}T10:00:00",+ properties={"$session_id": s1, "$referring_domain": "$direct"},+ )+ _create_event(+ team=self.team,+ event="$pageview",+ distinct_id=d1,+ timestamp=f"{day}T10:00:05",+ properties={"$session_id": s1, "utm_source": "google"},+ )++ response = self._run_web_stats_table_query(+ "all",+ "2024-06-27",+ breakdown_by=WebStatsBreakdown.FIRST_PAGEVIEW_UTM_SOURCE,+ custom_event="custom_event",+ )++ # The conversion event precedes the first pageview (the SSR pattern this+ # feature fixes) but must not win the attribution argMin — while still+ # being counted as a conversion.+ assert [["google", (1, None), (1, None), (1, None), (1, None), 1, ""]] == response.results++ def test_first_pageview_attribution_excludes_sessionless_events(self):+ self._seed_first_pageview_session({"utm_source": "google"})+ _create_person(team_id=self.team.pk, distinct_ids=["d2"], properties={"name": "d2"})+ for second in range(2):+ _create_event(+ team=self.team,+ event="$pageview",+ distinct_id="d2",+ timestamp=f"2024-06-26T11:00:0{second}",+ properties={"utm_source": "facebook"},+ )++ # Events without a session id can't be attributed to a session's first+ # pageview and must not collapse into a merged catch-all group.+ assert self._breakdown_values(WebStatsBreakdown.FIRST_PAGEVIEW_UTM_SOURCE) == ["google"]++ def test_first_pageview_attribution_anchors_all_properties_to_one_event(self):+ d1, day = "d1", "2024-06-26"+ s1 = str(uuid7(day))+ _create_person(team_id=self.team.pk, distinct_ids=[d1], properties={"name": d1})+ _create_event(+ team=self.team,+ event="$pageview",+ distinct_id=d1,+ timestamp=f"{day}T10:00:00",+ properties={"$session_id": s1, "$referring_domain": "someblog.example"},+ )+ _create_event(+ team=self.team,+ event="$pageview",+ distinct_id=d1,+ timestamp=f"{day}T10:00:10",+ properties={+ "$session_id": s1,+ "$referring_domain": "someblog.example",+ "gclid": "abc",+ "utm_source": "google",+ },+ )++ # Every property must come from the first pageview alone: the later+ # gclid/utm_source must not stitch a paid channel onto referral traffic.+ assert self._breakdown_values(WebStatsBreakdown.FIRST_PAGEVIEW_CHANNEL_TYPE) == ["Referral"]+ assert self._breakdown_values(WebStatsBreakdown.FIRST_PAGEVIEW_UTM_SOURCE) == [None]++ def test_first_pageview_attribution_flag_flips_initial_breakdowns(self):+ self._seed_ssr_poisoned_session()++ assert self._breakdown_values(WebStatsBreakdown.INITIAL_UTM_SOURCE) == [None]+ assert self._breakdown_values(WebStatsBreakdown.INITIAL_CHANNEL_TYPE) == ["Direct"]++ with self._patch_first_pageview_flag():+ assert self._breakdown_values(WebStatsBreakdown.INITIAL_UTM_SOURCE) == ["google"]+ assert self._breakdown_values(WebStatsBreakdown.INITIAL_CHANNEL_TYPE) == ["Paid Search"]++ def test_first_pageview_attribution_flag_changes_cache_key(self):+ query = WebStatsTableQuery(+ dateRange=DateRange(date_from="2024-06-01", date_to="2024-06-30"),+ properties=[],+ breakdownBy=WebStatsBreakdown.INITIAL_CHANNEL_TYPE,+ )++ 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_bypasses_lazy_precompute(self):+ query = WebStatsTableQuery(+ dateRange=DateRange(date_from="2024-06-01", date_to="2024-06-30"),+ properties=[],+ breakdownBy=WebStatsBreakdown.INITIAL_CHANNEL_TYPE,+ )++ def lazy_eligible(flag_on):+ with (+ patch(+ "products.web_analytics.backend.hogql_queries.web_stats_lazy_precompute._can_use_lazy_precompute_shared",+ return_value=True,+ ),+ self._patch_first_pageview_flag(enabled=flag_on),+ ):+ return can_use_lazy_precompute(WebStatsTableQueryRunner(team=self.team, query=query))++ assert lazy_eligible(flag_on=False) is True+ assert lazy_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 37aecba11467..6fd766ac342c 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@@ -258,34 +258,45 @@ 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- @cached_property- def _session_id_set_flag_enabled(self) -> bool:- """Evaluate the rollout flag locally — fails closed on flag-service errors.-- A raised exception here must never fail the query: the fast path is an- optimization, so any flag-evaluation failure degrades to the join path.+ 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:- return bool(- posthoganalytics.feature_enabled(- SESSION_ID_SET_FEATURE_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,- )+ 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("web_analytics_session_id_set_flag_evaluation_failed", error=e, team_id=self.team.pk)+ logger.warning(failure_log_event, error=e, team_id=self.team.pk)return False+ @cached_property+ def _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"+ )+def _session_id_set_common_eligibility(self) -> bool:"""Shared gates for the session-id-set fast paths (filtered two-scan shape).diff --git a/products/web_analytics/backend/hogql_queries/web_stats_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/web_stats_lazy_precompute.pyindex 5c593ada755b..3297855c7f4c 100644--- a/products/web_analytics/backend/hogql_queries/web_stats_lazy_precompute.py+++ b/products/web_analytics/backend/hogql_queries/web_stats_lazy_precompute.py@@ -196,6 +196,8 @@ def _check_stats_eligible(runner: LazyPrecomputeRunner) -> None:def can_use_lazy_precompute(runner: "WebStatsTableQueryRunner") -> bool:"""Return True iff the lazy precompute path is eligible for this web statstable query — the shared web analytics gate plus stats-specific checks."""+ if runner._effective_breakdown() != runner.query.breakdownBy:+ return Falsereturn _can_use_lazy_precompute_shared(runner, log_prefix="web_stats", extra_check=_check_stats_eligible)@@ -431,6 +433,12 @@ _KEEP_NULL_BREAKDOWNS = {WebStatsBreakdown.INITIAL_UTM_MEDIUM,WebStatsBreakdown.INITIAL_UTM_TERM,WebStatsBreakdown.INITIAL_UTM_CONTENT,+ WebStatsBreakdown.FIRST_PAGEVIEW_REFERRING_DOMAIN,+ WebStatsBreakdown.FIRST_PAGEVIEW_UTM_SOURCE,+ WebStatsBreakdown.FIRST_PAGEVIEW_UTM_CAMPAIGN,+ WebStatsBreakdown.FIRST_PAGEVIEW_UTM_MEDIUM,+ WebStatsBreakdown.FIRST_PAGEVIEW_UTM_TERM,+ WebStatsBreakdown.FIRST_PAGEVIEW_UTM_CONTENT,}@@ -457,7 +465,7 @@ def _breakdown_having_expr(breakdown_by: WebStatsBreakdown) -> ast.Expr:# real for these dimensions and surfaces as a "(none)" row, so it must not be# dropped. Source of truth is `WebStatsTableQueryRunner.outer_where_breakdown`.return ast.Constant(value=True)- if breakdown_by == WebStatsBreakdown.INITIAL_CHANNEL_TYPE:+ if breakdown_by in (WebStatsBreakdown.INITIAL_CHANNEL_TYPE, WebStatsBreakdown.FIRST_PAGEVIEW_CHANNEL_TYPE):# JSON scalars: 'null' is genuine null, '""' is empty string.return parse_expr("breakdown_value NOT IN ('null', '\"\"')")# Default: reject only genuine null.diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 1916ab51b4e7..11d353464ac6 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -3673,6 +3673,14 @@ export namespace Schemas {InitialUTMTerm: 'InitialUTMTerm',InitialUTMContent: 'InitialUTMContent',InitialUTMSourceMediumCampaign: 'InitialUTMSourceMediumCampaign',+ FirstPageviewChannelType: 'FirstPageviewChannelType',+ FirstPageviewReferringDomain: 'FirstPageviewReferringDomain',+ FirstPageviewUTMSource: 'FirstPageviewUTMSource',+ FirstPageviewUTMCampaign: 'FirstPageviewUTMCampaign',+ FirstPageviewUTMMedium: 'FirstPageviewUTMMedium',+ FirstPageviewUTMTerm: 'FirstPageviewUTMTerm',+ FirstPageviewUTMContent: 'FirstPageviewUTMContent',+ FirstPageviewUTMSourceMediumCampaign: 'FirstPageviewUTMSourceMediumCampaign',Browser: 'Browser',Os: 'OS',Viewport: 'Viewport',diff --git a/services/mcp/src/tools/generated/query-wrappers.ts b/services/mcp/src/tools/generated/query-wrappers.tsindex c03dbc9b39c4..a5b3552c1dea 100644--- a/services/mcp/src/tools/generated/query-wrappers.ts+++ b/services/mcp/src/tools/generated/query-wrappers.ts@@ -1344,6 +1344,14 @@ const WebStatsBreakdown = z.enum(['InitialUTMTerm','InitialUTMContent','InitialUTMSourceMediumCampaign',+ 'FirstPageviewChannelType',+ 'FirstPageviewReferringDomain',+ 'FirstPageviewUTMSource',+ 'FirstPageviewUTMCampaign',+ 'FirstPageviewUTMMedium',+ 'FirstPageviewUTMTerm',+ 'FirstPageviewUTMContent',+ 'FirstPageviewUTMSourceMediumCampaign','Browser','OS','Viewport',diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-web-stats.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-web-stats.jsonindex e6ee7d5d1a9a..4f7f86f63480 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-web-stats.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-web-stats.json@@ -19,6 +19,14 @@"InitialUTMTerm","InitialUTMContent","InitialUTMSourceMediumCampaign",+ "FirstPageviewChannelType",+ "FirstPageviewReferringDomain",+ "FirstPageviewUTMSource",+ "FirstPageviewUTMCampaign",+ "FirstPageviewUTMMedium",+ "FirstPageviewUTMTerm",+ "FirstPageviewUTMContent",+ "FirstPageviewUTMSourceMediumCampaign","Browser","OS","Viewport",