: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): support traffic metrics with conversion goals (#100562)
Javier Bahamondesa1d51280d312
diff --git a/docs/internal/web-analytics-query-serving.md b/docs/internal/web-analytics-query-serving.mdindex 2d61f6558ad4..41e19dc4107c 100644--- a/docs/internal/web-analytics-query-serving.md+++ b/docs/internal/web-analytics-query-serving.md@@ -86,6 +86,12 @@ The dashboard "enqueues precompute" as a side effect; it never waits on it.| 6 | No-join | Unfiltered: path-bounce, path-bounce+avg-time, or simple breakdown without session fields | `stats_table_no_join_*` || 7 | Full join | Fallback per shape | `stats_table_path_bounce`, `stats_table_entry_bounce`, `stats_table_channel_type`, `stats_table_simple_breakdown`, … |+### Traffic metrics alongside conversion goals++`WebStatsTableQuery.includeTrafficMetrics` adds sessions and retains pageviews alongside conversion columns. Traffic visitors and sessions require a pageview or screenview; goal-only sessions contribute to conversions without increasing the traffic denominator. The option defaults to off, preserving existing callers.++Queries with this option bypass the simple-breakdown and paths lazy caches and use the supported live or preaggregated execution path. Event and action conversion goals can carry property filters, which restrict conversions rather than traffic.+### Goals, vitals, external clicks| Runner | Tier 1 | Fallback | Notes |@@ -154,3 +160,5 @@ Suffix conventions: `*_lazy_query` = bucket read (served from precompute), `*_laFind the request in query_log and check `query_type`.A `*_lazy_query` taking seconds is a bucket-read problem (rare).A fast-path or full-join tag on an enrolled team means the lazy gate rejected the query (filters, avg-time-on-page, >90d range, opt-out) or the buckets weren't fresh — in which case a background warm is already in flight and the next identical request should hit.++Conversion goal property filters accept event, person, session and cohort filters. Unsupported filter types fail query validation. `includeTrafficMetrics` also retains session counts for page breakdowns with bounce rate or average time on page, including the join-free strategies.diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 86f38dc27203..37ceaf709ec8 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -963,6 +963,9 @@"properties": {"actionId": {"$ref": "#/definitions/integer"+ },+ "properties": {+ "$ref": "#/definitions/WebAnalyticsPropertyFilters"}},"required": ["actionId"],@@ -17384,6 +17387,9 @@"properties": {"customEventName": {"type": "string"+ },+ "properties": {+ "$ref": "#/definitions/WebAnalyticsPropertyFilters"}},"required": ["customEventName"],@@ -57607,6 +57613,9 @@"includeScrollDepth": {"type": "boolean"},+ "includeTrafficMetrics": {+ "type": "boolean"+ },"interval": {"$ref": "#/definitions/IntervalType","description": "Interval for date range calculation (affects date_to rounding for hour vs day ranges)"diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 5045a865f4af..9315bfe104a1 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -3246,9 +3246,11 @@ export type WebAnalyticsPropertyFilter =| CohortPropertyFilterexport type WebAnalyticsPropertyFilters = WebAnalyticsPropertyFilter[]export type ActionConversionGoal = {+ properties?: WebAnalyticsPropertyFiltersactionId: integer}export type CustomEventConversionGoal = {+ properties?: WebAnalyticsPropertyFilterscustomEventName: string}export type WebAnalyticsConversionGoal = ActionConversionGoal | CustomEventConversionGoal@@ -3873,6 +3875,7 @@ export enum WebStatsBreakdown {FrustrationMetrics = 'FrustrationMetrics',}export interface WebStatsTableQuery extends WebAnalyticsQueryBase<WebStatsTableQueryResponse> {+ includeTrafficMetrics?: booleankind: NodeKind.WebStatsTableQuerybreakdownBy: WebStatsBreakdownincludeScrollDepth?: boolean // automatically sets includeBounceRate to truediff --git a/posthog/schema.py b/posthog/schema.pyindex ca751256b325..72ac035a14a3 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -1074,13 +1074,6 @@ class ConditionalFormattingRule(BaseModel):templateId: str-class CustomEventConversionGoal(BaseModel):- model_config = ConfigDict(- extra="forbid",- )- customEventName: str--class DangerousOperationResponse(BaseModel):model_config = ConfigDict(extra="forbid",@@ -3377,13 +3370,6 @@ class AccountsTableRow(BaseModel):)-class ActionConversionGoal(BaseModel):- model_config = ConfigDict(- extra="forbid",- )- actionId: int--class ActorsPropertyTaxonomyResponse(BaseModel):model_config = ConfigDict(extra="forbid",@@ -9223,6 +9209,16 @@ class AccountsTableSort(BaseModel):direction: AccountsTableSortDirection+class ActionConversionGoal(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ actionId: int+ properties: (+ list[EventPropertyFilter | PersonPropertyFilter | SessionPropertyFilter | CohortPropertyFilter] | None+ ) = None++class ActorsPropertyTaxonomyQueryResponse(BaseModel):model_config = ConfigDict(extra="forbid",@@ -10549,184 +10545,6 @@ class AssistantTrendsQuery(BaseModel):)-class AssistantWebAnalyticsQueryBase(BaseModel):- model_config = ConfigDict(- extra="forbid",- )- compareFilter: CompareFilter | None = Field(- default=None,- description=(- "Compare the current period to a prior period. Disabled by default."- " Enabling roughly doubles query cost — leave it off unless the user"- " explicitly asks for a period-over-period comparison."- ),- )- conversionGoal: ActionConversionGoal | CustomEventConversionGoal | None = Field(- default=None,- description=(- "Conversion goal — pass an `actionId` (must belong to the current project)"- " or a `customEventName`. Adds conversion columns to the response. Disables"- " the pre-aggregated fast path — only set when the user explicitly asks"- " about a conversion."- ),- )- dateRange: AssistantDateRange | AssistantDurationRange | None = Field(- default=None,- description=(- "Date range for the query. Defaults to the last 7 days when omitted. Keep"- " ranges short — the backend has no upper bound and large windows on the"- " slow path (e.g. with `conversionGoal` or `includeAvgTimeOnPage`) can be"- " expensive."- ),- )- doPathCleaning: bool | None = Field(- default=False,- description="Apply the team's path-cleaning rules to URL-style breakdowns.",- )- filterTestAccounts: bool | None = Field(- default=False,- description=("Exclude internal and test users by applying the team's test-account filter."),- )- properties: (- list[EventPropertyFilter | PersonPropertyFilter | SessionPropertyFilter | CohortPropertyFilter] | None- ) = Field(- default=[],- description=("Property filters applied to the query. Accepts event, person, session, or cohort filters."),- )---class AssistantWebOverviewQuery(BaseModel):- model_config = ConfigDict(- extra="forbid",- )- compareFilter: CompareFilter | None = Field(- default=None,- description=(- "Compare the current period to a prior period. Disabled by default."- " Enabling roughly doubles query cost — leave it off unless the user"- " explicitly asks for a period-over-period comparison."- ),- )- conversionGoal: ActionConversionGoal | CustomEventConversionGoal | None = Field(- default=None,- description=(- "Conversion goal — pass an `actionId` (must belong to the current project)"- " or a `customEventName`. Adds conversion columns to the response. Disables"- " the pre-aggregated fast path — only set when the user explicitly asks"- " about a conversion."- ),- )- dateRange: AssistantDateRange | AssistantDurationRange | None = Field(- default=None,- description=(- "Date range for the query. Defaults to the last 7 days when omitted. Keep"- " ranges short — the backend has no upper bound and large windows on the"- " slow path (e.g. with `conversionGoal` or `includeAvgTimeOnPage`) can be"- " expensive."- ),- )- doPathCleaning: bool | None = Field(- default=False,- description="Apply the team's path-cleaning rules to URL-style breakdowns.",- )- filterTestAccounts: bool | None = Field(- default=False,- description=("Exclude internal and test users by applying the team's test-account filter."),- )- kind: Literal["WebOverviewQuery"] = "WebOverviewQuery"- properties: (- list[EventPropertyFilter | PersonPropertyFilter | SessionPropertyFilter | CohortPropertyFilter] | None- ) = Field(- default=[],- description=("Property filters applied to the query. Accepts event, person, session, or cohort filters."),- )---class AssistantWebStatsTableQuery(BaseModel):- model_config = ConfigDict(- extra="forbid",- )- breakdownBy: WebStatsBreakdown = Field(- ...,- description=(- "Required. Property to break down the table by. The full enum covers"- " path-style (`Page`, `InitialPage`, `ExitPage`, `PreviousPage`),"- " marketing/source (UTM source/medium/campaign/term/content, channel,"- " referring domain), audience/device (browser, OS, device type, viewport),"- " and geography (country, region, city, timezone, language). Path-style"- " breakdowns pair naturally with `includeBounceRate` /"- " `includeAvgTimeOnPage`."- ),- )- compareFilter: CompareFilter | None = Field(- default=None,- description=(- "Compare the current period to a prior period. Disabled by default."- " Enabling roughly doubles query cost — leave it off unless the user"- " explicitly asks for a period-over-period comparison."- ),- )- conversionGoal: ActionConversionGoal | CustomEventConversionGoal | None = Field(- default=None,- description=(- "Conversion goal — pass an `actionId` (must belong to the current project)"- " or a `customEventName`. Adds conversion columns to the response. Disables"- " the pre-aggregated fast path — only set when the user explicitly asks"- " about a conversion."- ),- )- dateRange: AssistantDateRange | AssistantDurationRange | None = Field(- default=None,- description=(- "Date range for the query. Defaults to the last 7 days when omitted. Keep"- " ranges short — the backend has no upper bound and large windows on the"- " slow path (e.g. with `conversionGoal` or `includeAvgTimeOnPage`) can be"- " expensive."- ),- )- doPathCleaning: bool | None = Field(- default=False,- description="Apply the team's path-cleaning rules to URL-style breakdowns.",- )- filterTestAccounts: bool | None = Field(- default=False,- description=("Exclude internal and test users by applying the team's test-account filter."),- )- includeAvgTimeOnPage: bool | None = Field(- default=False,- description=(- "Add an average-time-on-page column. Implies a Page-style breakdown. Disables the pre-aggregated fast path."- ),- )- includeBounceRate: bool | None = Field(- default=False,- description=("Add a bounce-rate column. Most useful with a path-style breakdown."),- )- includeHost: bool | None = Field(- default=False,- description=(- "When using a path-style breakdown (`Page`, `InitialPage`, `ExitPage`,"- " `PreviousPage`), concatenate host + pathname so the same path on"- " different hosts is counted separately."- ),- )- kind: Literal["WebStatsTableQuery"] = "WebStatsTableQuery"- limit: conint(ge=1) | None = Field(- default=None,- description=(- "Maximum rows to return. Prefer 10–25 unless the user explicitly asks for"- " more. Hard ceiling enforced at the wrapper."- ),- )- offset: conint(ge=0) | None = Field(default=None, description="Pagination offset.")- properties: (- list[EventPropertyFilter | PersonPropertyFilter | SessionPropertyFilter | CohortPropertyFilter] | None- ) = Field(- default=[],- description=("Property filters applied to the query. Accepts event, person, session, or cohort filters."),- )--class AssistantWebVitalsPathBreakdownQuery(BaseModel):model_config = ConfigDict(extra="forbid",@@ -15711,6 +15529,16 @@ class ContextMessage(BaseModel):type: Literal["context"] = "context"+class CustomEventConversionGoal(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ customEventName: str+ properties: (+ list[EventPropertyFilter | PersonPropertyFilter | SessionPropertyFilter | CohortPropertyFilter] | None+ ) = None++class Response(BaseModel):model_config = ConfigDict(extra="forbid",@@ -24433,53 +24261,6 @@ class VectorSearchQueryResponse(BaseModel):)-class WebAgentAnalyticsQuery(BaseModel):- model_config = ConfigDict(- extra="forbid",- )- aggregation_group_type_index: int | None = Field(- default=None,- description=("Groups aggregation - not used in Web Analytics but required for type compatibility"),- )- compareFilter: CompareFilter | None = None- contentGrouping: WebAgentContentGrouping | None = None- conversionGoal: ActionConversionGoal | CustomEventConversionGoal | None = None- dataColorTheme: float | None = Field(- default=None,- description=(- "Colors used in the insight's visualization - not used in Web Analytics but required for type compatibility"- ),- )- dateRange: DateRange | None = None- doPathCleaning: bool | None = None- filterTestAccounts: bool | None = None- includeCrawlers: bool | None = None- includeRevenue: bool | None = None- intentKey: str | None = None- interval: IntervalType | None = Field(- default=None,- description=("Interval for date range calculation (affects date_to rounding for hour vs day ranges)"),- )- journeyKey: str | None = Field(- default=None,- description=("Opaque journey identifier returned by the journeys list, used to load one journey's timeline."),- )- kind: Literal["WebAgentAnalyticsQuery"] = "WebAgentAnalyticsQuery"- limit: int | None = None- llmsTxtUrl: str | None = None- modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")- offset: int | None = None- orderBy: list[WebAnalyticsOrderByFields | WebAnalyticsOrderByDirection] | None = None- properties: list[EventPropertyFilter | PersonPropertyFilter | SessionPropertyFilter | CohortPropertyFilter]- queryType: WebAgentAnalyticsQueryType- response: WebAgentAnalyticsQueryResponse | None = None- sampling: WebAnalyticsSampling | None = None- samplingFactor: float | None = Field(default=None, description="Sampling rate")- tags: QueryLogTags | None = None- useSessionsTable: bool | None = None- version: float | None = Field(default=None, description="version of the node, used for schema migrations")--class WebAnalyticsAssistantFilters(BaseModel):model_config = ConfigDict(extra="forbid",@@ -24768,6 +24549,7 @@ class WebStatsTableQuery(BaseModel):includeHost: bool | None = NoneincludeRevenue: bool | None = NoneincludeScrollDepth: bool | None = None+ includeTrafficMetrics: bool | None = Noneinterval: IntervalType | None = Field(default=None,description=("Interval for date range calculation (affects date_to rounding for hour vs day ranges)"),@@ -25373,6 +25155,184 @@ class AssistantTrendsActorsQuery(BaseModel):)+class AssistantWebAnalyticsQueryBase(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ compareFilter: CompareFilter | None = Field(+ default=None,+ description=(+ "Compare the current period to a prior period. Disabled by default."+ " Enabling roughly doubles query cost — leave it off unless the user"+ " explicitly asks for a period-over-period comparison."+ ),+ )+ conversionGoal: ActionConversionGoal | CustomEventConversionGoal | None = Field(+ default=None,+ description=(+ "Conversion goal — pass an `actionId` (must belong to the current project)"+ " or a `customEventName`. Adds conversion columns to the response. Disables"+ " the pre-aggregated fast path — only set when the user explicitly asks"+ " about a conversion."+ ),+ )+ dateRange: AssistantDateRange | AssistantDurationRange | None = Field(+ default=None,+ description=(+ "Date range for the query. Defaults to the last 7 days when omitted. Keep"+ " ranges short — the backend has no upper bound and large windows on the"+ " slow path (e.g. with `conversionGoal` or `includeAvgTimeOnPage`) can be"+ " expensive."+ ),+ )+ doPathCleaning: bool | None = Field(+ default=False,+ description="Apply the team's path-cleaning rules to URL-style breakdowns.",+ )+ filterTestAccounts: bool | None = Field(+ default=False,+ description=("Exclude internal and test users by applying the team's test-account filter."),+ )+ properties: (+ list[EventPropertyFilter | PersonPropertyFilter | SessionPropertyFilter | CohortPropertyFilter] | None+ ) = Field(+ default=[],+ description=("Property filters applied to the query. Accepts event, person, session, or cohort filters."),+ )+++class AssistantWebOverviewQuery(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ compareFilter: CompareFilter | None = Field(+ default=None,+ description=(+ "Compare the current period to a prior period. Disabled by default."+ " Enabling roughly doubles query cost — leave it off unless the user"+ " explicitly asks for a period-over-period comparison."+ ),+ )+ conversionGoal: ActionConversionGoal | CustomEventConversionGoal | None = Field(+ default=None,+ description=(+ "Conversion goal — pass an `actionId` (must belong to the current project)"+ " or a `customEventName`. Adds conversion columns to the response. Disables"+ " the pre-aggregated fast path — only set when the user explicitly asks"+ " about a conversion."+ ),+ )+ dateRange: AssistantDateRange | AssistantDurationRange | None = Field(+ default=None,+ description=(+ "Date range for the query. Defaults to the last 7 days when omitted. Keep"+ " ranges short — the backend has no upper bound and large windows on the"+ " slow path (e.g. with `conversionGoal` or `includeAvgTimeOnPage`) can be"+ " expensive."+ ),+ )+ doPathCleaning: bool | None = Field(+ default=False,+ description="Apply the team's path-cleaning rules to URL-style breakdowns.",+ )+ filterTestAccounts: bool | None = Field(+ default=False,+ description=("Exclude internal and test users by applying the team's test-account filter."),+ )+ kind: Literal["WebOverviewQuery"] = "WebOverviewQuery"+ properties: (+ list[EventPropertyFilter | PersonPropertyFilter | SessionPropertyFilter | CohortPropertyFilter] | None+ ) = Field(+ default=[],+ description=("Property filters applied to the query. Accepts event, person, session, or cohort filters."),+ )+++class AssistantWebStatsTableQuery(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ breakdownBy: WebStatsBreakdown = Field(+ ...,+ description=(+ "Required. Property to break down the table by. The full enum covers"+ " path-style (`Page`, `InitialPage`, `ExitPage`, `PreviousPage`),"+ " marketing/source (UTM source/medium/campaign/term/content, channel,"+ " referring domain), audience/device (browser, OS, device type, viewport),"+ " and geography (country, region, city, timezone, language). Path-style"+ " breakdowns pair naturally with `includeBounceRate` /"+ " `includeAvgTimeOnPage`."+ ),+ )+ compareFilter: CompareFilter | None = Field(+ default=None,+ description=(+ "Compare the current period to a prior period. Disabled by default."+ " Enabling roughly doubles query cost — leave it off unless the user"+ " explicitly asks for a period-over-period comparison."+ ),+ )+ conversionGoal: ActionConversionGoal | CustomEventConversionGoal | None = Field(+ default=None,+ description=(+ "Conversion goal — pass an `actionId` (must belong to the current project)"+ " or a `customEventName`. Adds conversion columns to the response. Disables"+ " the pre-aggregated fast path — only set when the user explicitly asks"+ " about a conversion."+ ),+ )+ dateRange: AssistantDateRange | AssistantDurationRange | None = Field(+ default=None,+ description=(+ "Date range for the query. Defaults to the last 7 days when omitted. Keep"+ " ranges short — the backend has no upper bound and large windows on the"+ " slow path (e.g. with `conversionGoal` or `includeAvgTimeOnPage`) can be"+ " expensive."+ ),+ )+ doPathCleaning: bool | None = Field(+ default=False,+ description="Apply the team's path-cleaning rules to URL-style breakdowns.",+ )+ filterTestAccounts: bool | None = Field(+ default=False,+ description=("Exclude internal and test users by applying the team's test-account filter."),+ )+ includeAvgTimeOnPage: bool | None = Field(+ default=False,+ description=(+ "Add an average-time-on-page column. Implies a Page-style breakdown. Disables the pre-aggregated fast path."+ ),+ )+ includeBounceRate: bool | None = Field(+ default=False,+ description=("Add a bounce-rate column. Most useful with a path-style breakdown."),+ )+ includeHost: bool | None = Field(+ default=False,+ description=(+ "When using a path-style breakdown (`Page`, `InitialPage`, `ExitPage`,"+ " `PreviousPage`), concatenate host + pathname so the same path on"+ " different hosts is counted separately."+ ),+ )+ kind: Literal["WebStatsTableQuery"] = "WebStatsTableQuery"+ limit: conint(ge=1) | None = Field(+ default=None,+ description=(+ "Maximum rows to return. Prefer 10–25 unless the user explicitly asks for"+ " more. Hard ceiling enforced at the wrapper."+ ),+ )+ offset: conint(ge=0) | None = Field(default=None, description="Pagination offset.")+ properties: (+ list[EventPropertyFilter | PersonPropertyFilter | SessionPropertyFilter | CohortPropertyFilter] | None+ ) = Field(+ default=[],+ description=("Property filters applied to the query. Accepts event, person, session, or cohort filters."),+ )++class CachedErrorTrackingQueryResponse(BaseModel):model_config = ConfigDict(extra="forbid",@@ -28053,6 +28013,53 @@ class VectorSearchQuery(BaseModel):version: float | None = Field(default=None, description="version of the node, used for schema migrations")+class WebAgentAnalyticsQuery(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ aggregation_group_type_index: int | None = Field(+ default=None,+ description=("Groups aggregation - not used in Web Analytics but required for type compatibility"),+ )+ compareFilter: CompareFilter | None = None+ contentGrouping: WebAgentContentGrouping | None = None+ conversionGoal: ActionConversionGoal | CustomEventConversionGoal | None = None+ dataColorTheme: float | None = Field(+ default=None,+ description=(+ "Colors used in the insight's visualization - not used in Web Analytics but required for type compatibility"+ ),+ )+ dateRange: DateRange | None = None+ doPathCleaning: bool | None = None+ filterTestAccounts: bool | None = None+ includeCrawlers: bool | None = None+ includeRevenue: bool | None = None+ intentKey: str | None = None+ interval: IntervalType | None = Field(+ default=None,+ description=("Interval for date range calculation (affects date_to rounding for hour vs day ranges)"),+ )+ journeyKey: str | None = Field(+ default=None,+ description=("Opaque journey identifier returned by the journeys list, used to load one journey's timeline."),+ )+ kind: Literal["WebAgentAnalyticsQuery"] = "WebAgentAnalyticsQuery"+ limit: int | None = None+ llmsTxtUrl: str | None = None+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")+ offset: int | None = None+ orderBy: list[WebAnalyticsOrderByFields | WebAnalyticsOrderByDirection] | None = None+ properties: list[EventPropertyFilter | PersonPropertyFilter | SessionPropertyFilter | CohortPropertyFilter]+ queryType: WebAgentAnalyticsQueryType+ response: WebAgentAnalyticsQueryResponse | None = None+ sampling: WebAnalyticsSampling | None = None+ samplingFactor: float | None = Field(default=None, description="Sampling rate")+ tags: QueryLogTags | None = None+ useSessionsTable: bool | None = None+ version: float | None = Field(default=None, description="version of the node, used for schema migrations")++class WebVitalsPathBreakdownQuery(BaseModel):model_config = ConfigDict(extra="forbid",diff --git a/posthog/test/test_property_filter_discriminator.py b/posthog/test/test_property_filter_discriminator.pyindex b656a490f5bc..95c154b0d967 100644--- a/posthog/test/test_property_filter_discriminator.py+++ b/posthog/test/test_property_filter_discriminator.py@@ -5,8 +5,10 @@ from pydantic import ValidationErrorfrom posthog.schema import (AccountCustomPropertyFilter,+ ActionConversionGoal,BehavioralPropertyFilter,CohortPropertyFilter,+ CustomEventConversionGoal,DashboardFilter,DataWarehousePersonPropertyFilter,DataWarehousePropertyFilter,@@ -56,6 +58,18 @@ class TestPropertyFilterDiscriminator(SimpleTestCase):# log/span tags, and the AND/OR-tagged recursive group. These tests pin both the# routing and the tolerance so a schema regeneration that drops either fails here.+ @parameterized.expand([("action", {"actionId": 1}), ("event", {"customEventName": "customer_created"})])+ def test_conversion_goal_properties(self, kind: str, fields: dict[str, object]) -> None:+ model = ActionConversionGoal if kind == "action" else CustomEventConversionGoal+ goal = model.model_validate({**fields, "properties": [{"type": "event", "key": "plan", "value": "paid"}]})+ assert goal.properties is not None+ assert isinstance(goal.properties[0], EventPropertyFilter)+ for property_type in ["account_custom_property", "revenue_analytics", "recording"]:+ with self.assertRaises(ValidationError):+ model.model_validate(+ {**fields, "properties": [{"type": property_type, "key": "plan", "value": "paid"}]}+ )+@parameterized.expand([("event", {"type": "event", "key": "k", "operator": "exact"}, EventPropertyFilter),diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.tsindex 86cd560e658b..1f8cbc2fab36 100644--- a/products/dashboards/frontend/generated/api.schemas.ts+++ b/products/dashboards/frontend/generated/api.schemas.ts@@ -1328,12 +1328,53 @@ export interface CompareFilterApi {compare_to?: string | null}+export interface EventPropertyFilterApi {+ key: string+ label?: string | null+ operator?: PropertyOperatorApi | null+ /** Event properties */+ type?: 'event'+ value?: (string | number | boolean)[] | string | number | boolean | null+}++export interface PersonPropertyFilterApi {+ key: string+ label?: string | null+ operator: PropertyOperatorApi+ /** Person properties */+ type?: 'person'+ value?: (string | number | boolean)[] | string | number | boolean | null+}++export interface SessionPropertyFilterApi {+ key: string+ label?: string | null+ operator: PropertyOperatorApi+ type?: 'session'+ value?: (string | number | boolean)[] | string | number | boolean | null+}++export interface CohortPropertyFilterApi {+ cohort_name?: string | null+ key?: 'id'+ label?: string | null+ operator?: PropertyOperatorApi | null+ type?: 'cohort'+ value: number+}+export interface ActionConversionGoalApi {actionId: number+ properties?:+ | (EventPropertyFilterApi | PersonPropertyFilterApi | SessionPropertyFilterApi | CohortPropertyFilterApi)[]+ | null}export interface CustomEventConversionGoalApi {customEventName: string+ properties?:+ | (EventPropertyFilterApi | PersonPropertyFilterApi | SessionPropertyFilterApi | CohortPropertyFilterApi)[]+ | null}export type DaysOfWeekEnumApi = (typeof DaysOfWeekEnumApi)[keyof typeof DaysOfWeekEnumApi]@@ -1623,24 +1664,6 @@ export interface HogQLQueryModifiersApi {webAnalyticsFirstPageviewFilters?: boolean | null}-export interface EventPropertyFilterApi {- key: string- label?: string | null- operator?: PropertyOperatorApi | null- /** Event properties */- type?: 'event'- value?: (string | number | boolean)[] | string | number | boolean | null-}--export interface PersonPropertyFilterApi {- key: string- label?: string | null- operator: PropertyOperatorApi- /** Person properties */- type?: 'person'- value?: (string | number | boolean)[] | string | number | boolean | null-}-export interface PersonMetadataPropertyFilterApi {key: stringlabel?: string | null@@ -1675,23 +1698,6 @@ export interface EventMetadataPropertyFilterApi {value?: (string | number | boolean)[] | string | number | boolean | null}-export interface SessionPropertyFilterApi {- key: string- label?: string | null- operator: PropertyOperatorApi- type?: 'session'- value?: (string | number | boolean)[] | string | number | boolean | null-}--export interface CohortPropertyFilterApi {- cohort_name?: string | null- key?: 'id'- label?: string | null- operator?: PropertyOperatorApi | null- type?: 'cohort'- value: number-}-export type DurationTypeApi = (typeof DurationTypeApi)[keyof typeof DurationTypeApi]export const DurationTypeApi = {@@ -4455,6 +4461,7 @@ export interface WebStatsTableQueryApi {includeHost?: boolean | nullincludeRevenue?: boolean | nullincludeScrollDepth?: boolean | null+ includeTrafficMetrics?: boolean | null/** Interval for date range calculation (affects date_to rounding for hour vs day ranges) */interval?: IntervalTypeApi | nullkind?: 'WebStatsTableQuery'diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.tsindex afff7e59de48..2ceebf161950 100644--- a/products/product_analytics/frontend/generated/api.schemas.ts+++ b/products/product_analytics/frontend/generated/api.schemas.ts@@ -279,12 +279,96 @@ export interface CompareFilterApi {compare_to?: string | null}+export type PropertyOperatorApi = (typeof PropertyOperatorApi)[keyof typeof PropertyOperatorApi]++export const PropertyOperatorApi = {+ Exact: 'exact',+ IsNot: 'is_not',+ Icontains: 'icontains',+ NotIcontains: 'not_icontains',+ StartsWith: 'starts_with',+ NotStartsWith: 'not_starts_with',+ EndsWith: 'ends_with',+ NotEndsWith: 'not_ends_with',+ Regex: 'regex',+ NotRegex: 'not_regex',+ Gt: 'gt',+ Gte: 'gte',+ Lt: 'lt',+ Lte: 'lte',+ IsSet: 'is_set',+ IsNotSet: 'is_not_set',+ IsDateExact: 'is_date_exact',+ IsDateBefore: 'is_date_before',+ IsDateAfter: 'is_date_after',+ Between: 'between',+ NotBetween: 'not_between',+ Min: 'min',+ Max: 'max',+ In: 'in',+ NotIn: 'not_in',+ IsCleanedPathExact: 'is_cleaned_path_exact',+ FlagEvaluatesTo: 'flag_evaluates_to',+ SemverEq: 'semver_eq',+ SemverNeq: 'semver_neq',+ SemverGt: 'semver_gt',+ SemverGte: 'semver_gte',+ SemverLt: 'semver_lt',+ SemverLte: 'semver_lte',+ SemverTilde: 'semver_tilde',+ SemverCaret: 'semver_caret',+ SemverWildcard: 'semver_wildcard',+ IcontainsMulti: 'icontains_multi',+ NotIcontainsMulti: 'not_icontains_multi',+} as const++export interface EventPropertyFilterApi {+ key: string+ label?: string | null+ operator?: PropertyOperatorApi | null+ /** Event properties */+ type?: 'event'+ value?: (string | number | boolean)[] | string | number | boolean | null+}++export interface PersonPropertyFilterApi {+ key: string+ label?: string | null+ operator: PropertyOperatorApi+ /** Person properties */+ type?: 'person'+ value?: (string | number | boolean)[] | string | number | boolean | null+}++export interface SessionPropertyFilterApi {+ key: string+ label?: string | null+ operator: PropertyOperatorApi+ type?: 'session'+ value?: (string | number | boolean)[] | string | number | boolean | null+}++export interface CohortPropertyFilterApi {+ cohort_name?: string | null+ key?: 'id'+ label?: string | null+ operator?: PropertyOperatorApi | null+ type?: 'cohort'+ value: number+}+export interface ActionConversionGoalApi {actionId: number+ properties?:+ | (EventPropertyFilterApi | PersonPropertyFilterApi | SessionPropertyFilterApi | CohortPropertyFilterApi)[]+ | null}export interface CustomEventConversionGoalApi {customEventName: string+ properties?:+ | (EventPropertyFilterApi | PersonPropertyFilterApi | SessionPropertyFilterApi | CohortPropertyFilterApi)[]+ | null}export type DaysOfWeekEnumApi = (typeof DaysOfWeekEnumApi)[keyof typeof DaysOfWeekEnumApi]@@ -574,67 +658,6 @@ export interface HogQLQueryModifiersApi {webAnalyticsFirstPageviewFilters?: boolean | null}-export type PropertyOperatorApi = (typeof PropertyOperatorApi)[keyof typeof PropertyOperatorApi]--export const PropertyOperatorApi = {- Exact: 'exact',- IsNot: 'is_not',- Icontains: 'icontains',- NotIcontains: 'not_icontains',- StartsWith: 'starts_with',- NotStartsWith: 'not_starts_with',- EndsWith: 'ends_with',- NotEndsWith: 'not_ends_with',- Regex: 'regex',- NotRegex: 'not_regex',- Gt: 'gt',- Gte: 'gte',- Lt: 'lt',- Lte: 'lte',- IsSet: 'is_set',- IsNotSet: 'is_not_set',- IsDateExact: 'is_date_exact',- IsDateBefore: 'is_date_before',- IsDateAfter: 'is_date_after',- Between: 'between',- NotBetween: 'not_between',- Min: 'min',- Max: 'max',- In: 'in',- NotIn: 'not_in',- IsCleanedPathExact: 'is_cleaned_path_exact',- FlagEvaluatesTo: 'flag_evaluates_to',- SemverEq: 'semver_eq',- SemverNeq: 'semver_neq',- SemverGt: 'semver_gt',- SemverGte: 'semver_gte',- SemverLt: 'semver_lt',- SemverLte: 'semver_lte',- SemverTilde: 'semver_tilde',- SemverCaret: 'semver_caret',- SemverWildcard: 'semver_wildcard',- IcontainsMulti: 'icontains_multi',- NotIcontainsMulti: 'not_icontains_multi',-} as const--export interface EventPropertyFilterApi {- key: string- label?: string | null- operator?: PropertyOperatorApi | null- /** Event properties */- type?: 'event'- value?: (string | number | boolean)[] | string | number | boolean | null-}--export interface PersonPropertyFilterApi {- key: string- label?: string | null- operator: PropertyOperatorApi- /** Person properties */- type?: 'person'- value?: (string | number | boolean)[] | string | number | boolean | null-}-export interface PersonMetadataPropertyFilterApi {key: stringlabel?: string | null@@ -669,23 +692,6 @@ export interface EventMetadataPropertyFilterApi {value?: (string | number | boolean)[] | string | number | boolean | null}-export interface SessionPropertyFilterApi {- key: string- label?: string | null- operator: PropertyOperatorApi- type?: 'session'- value?: (string | number | boolean)[] | string | number | boolean | null-}--export interface CohortPropertyFilterApi {- cohort_name?: string | null- key?: 'id'- label?: string | null- operator?: PropertyOperatorApi | null- type?: 'cohort'- value: number-}-export type DurationTypeApi = (typeof DurationTypeApi)[keyof typeof DurationTypeApi]export const DurationTypeApi = {@@ -3449,6 +3455,7 @@ export interface WebStatsTableQueryApi {includeHost?: boolean | nullincludeRevenue?: boolean | nullincludeScrollDepth?: boolean | null+ includeTrafficMetrics?: boolean | null/** Interval for date range calculation (affects date_to rounding for hour vs day ranges) */interval?: IntervalTypeApi | nullkind?: 'WebStatsTableQuery'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 9dedeab616e9..669bfe86aa81 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@@ -171,8 +171,8 @@ GROUP BY session_id, breakdown_valueMAIN_INNER_QUERY = """SELECT- any(person_id) AS filtered_person_id,- count() AS filtered_pageview_count,+ {filtered_person_id} AS filtered_person_id,+ {filtered_pageview_count} AS filtered_pageview_count,{breakdown_value} AS breakdown_value,session.session_id AS session_id,any(session.$is_bounce) AS is_bounce,@@ -207,8 +207,8 @@ SELECTstart_timestampFROM (SELECT- any(person_id) AS filtered_person_id,- count() AS filtered_pageview_count,+ {filtered_person_id} AS filtered_person_id,+ {filtered_pageview_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,@@ -235,8 +235,8 @@ FROM (# to the single events scan.NO_JOIN_MAIN_INNER_QUERY = """SELECT- any(person_id) AS filtered_person_id,- count() AS filtered_pageview_count,+ {filtered_person_id} AS filtered_person_id,+ {filtered_pageview_count} AS filtered_pageview_count,{breakdown_value} AS breakdown_value,if(equals(bitAnd(bitShiftRight(events.$session_id_uuid, 76), 15), 7),diff --git a/products/web_analytics/backend/hogql_queries/stats_table.py b/products/web_analytics/backend/hogql_queries/stats_table.pyindex 24c0895fd9d6..5b9a9e08df72 100644--- a/products/web_analytics/backend/hogql_queries/stats_table.py+++ b/products/web_analytics/backend/hogql_queries/stats_table.py@@ -553,7 +553,7 @@ WHERE and(return True if get_query_tag_value("precompute_stale") else Nonedef get_lazy_precomputed_result(self) -> Optional[LazyStatsResult]:- if not can_use_lazy_precompute(self):+ if self.query.includeTrafficMetrics or not can_use_lazy_precompute(self):return Nonereturn execute_lazy_precomputed_read(self)@@ -597,7 +597,7 @@ WHERE and(Returns None when ineligible or on any failure, in which case the callerfalls through to the v2/raw HogQL path."""- if not can_use_paths_lazy_precompute(self):+ if self.query.includeTrafficMetrics or not can_use_paths_lazy_precompute(self):return Nonesort_column, sort_direction = self._resolve_sort_field()limit = self.paginator.limitdiff --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 1f9d6a0e40b8..e2a9745ff7c0 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@@ -248,6 +248,18 @@ class StatsTablePreAggregatedQueryBuilder(WebAnalyticsPreAggregatedQueryBuilder)),)+ if self.runner.query.includeTrafficMetrics:+ query.select.insert(+ 2,+ ast.Alias(+ alias="context.columns.sessions",+ expr=self._period_comparison_tuple(+ "sessions_uniq_state",+ "uniqMergeIf",+ period_filters=period_filters,+ ),+ ),+ )return querydef _default_breakdown_query_with_conversions(self, *, period_filters: PeriodFilters) -> ast.SelectQuery:@@ -292,6 +304,20 @@ class StatsTablePreAggregatedQueryBuilder(WebAnalyticsPreAggregatedQueryBuilder)),)+ if self.runner.query.includeTrafficMetrics:+ for offset, metric in enumerate(["sessions", "views"]):+ query.select.insert(+ 2 + offset,+ ast.Alias(+ alias=f"context.columns.{metric}",+ expr=ast.Tuple(+ exprs=[+ ast.Field(chain=["stats", f"{metric}_current"]),+ ast.Field(chain=["stats", f"{metric}_previous"]),+ ]+ ),+ ),+ )return querydef _build_stats_subquery(@@ -326,6 +352,23 @@ class StatsTablePreAggregatedQueryBuilder(WebAnalyticsPreAggregatedQueryBuilder)),]+ if self.runner.query.includeTrafficMetrics:+ for metric, state, function in [+ ("sessions", "sessions_uniq_state", "uniqMergeIf"),+ ("views", "pageviews_count_state", "sumMergeIf"),+ ]:+ for period, period_filter in [("current", current_period_filter), ("previous", previous_period_filter)]:+ stats_select_columns.append(+ ast.Alias(+ alias=f"{metric}_{period}",+ expr=(+ ast.Call(name=function, args=[ast.Field(chain=[state]), period_filter])+ if period == "current" or self.runner.query_compare_to_date_range+ else ast.Constant(value=0)+ ),+ )+ )+stats_query = ast.SelectQuery(select=cast(list[ast.Expr], stats_select_columns),select_from=ast.JoinExpr(table=ast.Field(chain=[self.stats_table])),@@ -506,6 +549,26 @@ class StatsTablePreAggregatedQueryBuilder(WebAnalyticsPreAggregatedQueryBuilder)else:query = self._default_breakdown_query()+ if self.runner.query.includeTrafficMetrics and not self.runner.query.conversionGoal:+ if self.runner.query.breakdownBy in (WebStatsBreakdown.PAGE, WebStatsBreakdown.INITIAL_PAGE):+ table = (+ self.bounces_table+ if self.runner.query.breakdownBy == WebStatsBreakdown.INITIAL_PAGE+ else self.stats_table+ )+ query.select.insert(+ 2,+ ast.Alias(+ alias="context.columns.sessions",+ expr=self._period_comparison_tuple(+ "sessions_uniq_state",+ "uniqMergeIf",+ period_filters=self.get_date_ranges(table_name=table),+ table_prefix=table,+ ),+ ),+ )+query.order_by = [self._get_order_by()]fill_fraction_expr = self.runner._fill_fraction(query.order_by)diff --git a/products/web_analytics/backend/hogql_queries/stats_table_strategies.py b/products/web_analytics/backend/hogql_queries/stats_table_strategies.pyindex 3d0457ed0c50..706722d33a6a 100644--- a/products/web_analytics/backend/hogql_queries/stats_table_strategies.py+++ b/products/web_analytics/backend/hogql_queries/stats_table_strategies.py@@ -36,7 +36,29 @@ class StatsTableQueryStrategy(ABC):@abstractmethoddef build_query(self) -> ast.SelectQuery: ...- def _finalize_query(self, query: ast.SelectQuery) -> ast.SelectQuery:+ def _finalize_query(+ self, query: ast.SelectQuery, session_column: str = "session_id", period_column: str = "start_timestamp"+ ) -> ast.SelectQuery:+ if self.runner.query.includeTrafficMetrics:+ assert query.select_from is not None+ counts = query.select_from.table+ assert isinstance(counts, ast.SelectQuery)+ for alias, period in [+ ("sessions", self.runner._current_period_expression(period_column)),+ ("previous_sessions", self.runner._previous_period_expression(period_column)),+ ]:+ counts.select.append(+ ast.Alias(+ alias=alias, expr=ast.Call(name="uniqIf", args=[ast.Field(chain=[session_column]), period])+ )+ )+ query.select.insert(+ 2,+ ast.Alias(+ alias="context.columns.sessions",+ expr=parse_expr("tuple(counts.sessions, counts.previous_sessions)"),+ ),+ )columns = [select.alias for select in query.select if isinstance(select, ast.Alias)]query.order_by = self.runner._order_by(columns)fill_fraction = self.runner._fill_fraction(query.order_by)@@ -74,9 +96,17 @@ class SimpleBreakdownStrategy(StatsTableQueryStrategy):with self.runner.timings.measure(self.runner.query_strategy()):selects: list[ast.Expr] = [ast.Alias(alias="context.columns.breakdown_value", expr=self.runner._processed_breakdown_value()),- self.runner._period_comparison_tuple("filtered_person_id", "context.columns.visitors", "uniq"),+ self._traffic_comparison_tuple("filtered_person_id", "context.columns.visitors"),]+ if self.runner.query.includeTrafficMetrics:+ selects.extend(+ [+ self._traffic_comparison_tuple("session_id", "context.columns.sessions"),+ self.runner._period_comparison_tuple("filtered_pageview_count", "context.columns.views", "sum"),+ ]+ )+if self.runner.query.conversionGoal is not None:selects.extend([@@ -102,9 +132,10 @@ class SimpleBreakdownStrategy(StatsTableQueryStrategy):])else:- selects.append(- self.runner._period_comparison_tuple("filtered_pageview_count", "context.columns.views", "sum"),- )+ if not self.runner.query.includeTrafficMetrics:+ selects.append(+ self.runner._period_comparison_tuple("filtered_pageview_count", "context.columns.views", "sum"),+ )if self.runner._include_extra_aggregation_value():selects.append(self.runner._extra_aggregation_value())@@ -121,9 +152,10 @@ class SimpleBreakdownStrategy(StatsTableQueryStrategy):if fill_fraction_expr:selects.append(fill_fraction_expr)+ inner_query = self._inner_query(breakdown)query = ast.SelectQuery(select=selects,- select_from=ast.JoinExpr(table=self._inner_query(breakdown)),+ select_from=ast.JoinExpr(table=inner_query),group_by=[ast.Field(chain=["context.columns.breakdown_value"])],order_by=order_by,having=self.runner.outer_where_breakdown(),@@ -131,11 +163,56 @@ class SimpleBreakdownStrategy(StatsTableQueryStrategy):return query+ def _traffic_comparison_tuple(self, column: str, alias: str) -> ast.Alias:+ if not self.runner.query.includeTrafficMetrics:+ return self.runner._period_comparison_tuple(column, alias, "uniq")+ traffic_filter = parse_expr("filtered_pageview_count > 0")+ return ast.Alias(+ alias=alias,+ expr=ast.Tuple(+ exprs=[+ ast.Call(+ name="uniqIf",+ args=[+ ast.Field(chain=[column]),+ ast.And(exprs=[traffic_filter, self.runner._current_period_expression()])+ if self.runner.query_compare_to_date_range+ else traffic_filter,+ ],+ ),+ ast.Call(+ name="uniqIf",+ args=[+ ast.Field(chain=[column]),+ ast.And(exprs=[traffic_filter, self.runner._previous_period_expression()]),+ ],+ )+ if self.runner.query_compare_to_date_range+ else ast.Constant(value=None),+ ]+ ),+ )++ def _event_aggregation_placeholders(self) -> dict[str, ast.Expr]:+ if not self.runner.query.includeTrafficMetrics:+ return {+ "filtered_person_id": parse_expr("any(person_id)"),+ "filtered_pageview_count": parse_expr("count()"),+ }+ traffic_event = parse_expr("events.event = '$pageview' OR events.event = '$screen'")+ return {+ "filtered_person_id": ast.Call(+ name="anyIf", args=[ast.Field(chain=["events", "person_id"]), traffic_event]+ ),+ "filtered_pageview_count": ast.Call(name="countIf", args=[traffic_event]),+ }+def _inner_query(self, breakdown: ast.Expr) -> ast.SelectQuery:query = parse_select(self.INNER_QUERY,timings=self.runner.timings,placeholders={+ **self._event_aggregation_placeholders(),"breakdown_value": breakdown,"event_where": self.runner.event_type_expr,"all_properties": self.runner.all_properties(),@@ -172,6 +249,7 @@ class NoJoinSimpleBreakdownStrategy(SimpleBreakdownStrategy):NO_JOIN_MAIN_INNER_QUERY,timings=self.runner.timings,placeholders={+ **self._event_aggregation_placeholders(),"breakdown_value": breakdown,"event_where": self.runner.event_type_expr,"all_properties": self.runner.all_properties(),@@ -217,6 +295,7 @@ class FirstPageviewAttributionStrategy(SimpleBreakdownStrategy):self.INNER_QUERY,timings=self.runner.timings,placeholders={+ **self._event_aggregation_placeholders(),"breakdown_value": breakdown,"first_pageview_properties": self.runner._first_pageview_properties_expr(),"event_where": self.runner.event_type_expr,@@ -316,7 +395,7 @@ class NoJoinPathBounceStrategy(StatsTableQueryStrategy):placeholders=self._placeholders(),)assert isinstance(query, ast.SelectQuery)- return self._finalize_query(query)+ return self._finalize_query(query, session_column="$session_id_uuid", period_column="timestamp")def _placeholders(self) -> dict[str, ast.Expr]:return {diff --git a/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_overview.ambr b/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_overview.ambrindex e0e9867839c3..ef5ac64a7823 100644--- a/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_overview.ambr+++ b/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_overview.ambr@@ -965,6 +965,448 @@use_hive_partitioning=0'''# ---+# name: TestWebOverviewQueryRunner.test_goal_properties_preserve_visitors_and_deduplicate_customers_0_event+ '''+ SELECT uniq(session_person_id) AS unique_users,+ NULL AS previous_unique_users,+ sum(conversion_count) AS total_conversion_count,+ NULL AS previous_total_conversion_count,+ uniq(conversion_person_id) AS unique_conversions,+ NULL AS previous_unique_conversions,+ divide(unique_conversions, unique_users) AS conversion_rate,+ NULL AS previous_conversion_rate+ FROM+ (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS session_person_id,+ events__session.session_id AS session_id,+ min(events__session.`$start_timestamp`) AS start_timestamp,+ countIf(and(equals(events.event, 'customer_created'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'plan'), ''), 'null'), '^"|"$', ''), 'paid'), 0))) AS conversion_count,+ any(if(and(equals(events.event, 'customer_created'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'plan'), ''), 'null'), '^"|"$', ''), 'paid'), 0)), 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,+ 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('2023-12-01 00:00:00', 'UTC')), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC')), toIntervalDay(3))))+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.`$session_id_uuid`, events__session.session_id_v7)+ LEFT OUTER JOIN+ (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,+ person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 99999)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ WHERE and(equals(events.team_id, 99999), and(isNotNull(events.`$session_id`), or(equals(events.event, '$pageview'), equals(events.event, '$screen'), and(equals(events.event, 'customer_created'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'plan'), ''), 'null'), '^"|"$', ''), 'paid'), 0))), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC')))), 0), 1))+ GROUP BY session_id+ HAVING or(and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC')))), 0))+ LIMIT 100 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ optimize_rewrite_aggregate_function_with_if=0,+ optimize_min_inequality_conjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestWebOverviewQueryRunner.test_goal_properties_preserve_visitors_and_deduplicate_customers_0_event.1+ '''+ SELECT breakdown_value AS `context.columns.breakdown_value`,+ tuple(uniqIf(filtered_person_id, greater(filtered_pageview_count, 0)), NULL) AS `context.columns.visitors`,+ tuple(uniqIf(session_id, greater(filtered_pageview_count, 0)), NULL) AS `context.columns.sessions`,+ tuple(sum(filtered_pageview_count), NULL) AS `context.columns.views`,+ 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 anyIf(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), or(equals(events.event, '$pageview'), equals(events.event, '$screen'))) AS filtered_person_id,+ countIf(or(equals(events.event, '$pageview'), equals(events.event, '$screen'))) 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,+ countIf(and(equals(events.event, 'customer_created'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'plan'), ''), 'null'), '^"|"$', ''), 'paid'), 0))) AS conversion_count,+ any(if(and(equals(events.event, 'customer_created'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'plan'), ''), 'null'), '^"|"$', ''), 'paid'), 0)), if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), NULL)) AS conversion_person_id+ 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('2023-12-01 00:00:00', 'UTC')), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime('2023-12-03 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('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC')))), 0), or(equals(events.event, '$pageview'), equals(events.event, '$screen'), and(equals(events.event, 'customer_created'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'plan'), ''), 'null'), '^"|"$', ''), 'paid'), 0))), 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.unique_conversions` DESC,+ `context.columns.total_conversions` DESC,+ `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: TestWebOverviewQueryRunner.test_goal_properties_preserve_visitors_and_deduplicate_customers_0_event.2+ '''+ SELECT breakdown_value AS `context.columns.breakdown_value`,+ tuple(uniqIf(filtered_person_id, greater(filtered_pageview_count, 0)), NULL) AS `context.columns.visitors`,+ tuple(uniqIf(session_id, greater(filtered_pageview_count, 0)), NULL) AS `context.columns.sessions`,+ 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 anyIf(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), or(equals(events.event, '$pageview'), equals(events.event, '$screen'))) AS filtered_person_id,+ countIf(or(equals(events.event, '$pageview'), equals(events.event, '$screen'))) 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('2023-12-01 00:00:00', 'UTC')), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime('2023-12-03 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('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-03 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: TestWebOverviewQueryRunner.test_goal_properties_preserve_visitors_and_deduplicate_customers_0_event.3+ '''+ 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 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,+ countIf(and(equals(events.event, 'customer_created'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'plan'), ''), 'null'), '^"|"$', ''), 'paid'), 0))) AS conversion_count,+ any(if(and(equals(events.event, 'customer_created'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'plan'), ''), 'null'), '^"|"$', ''), 'paid'), 0)), if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), NULL)) AS conversion_person_id+ 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('2023-12-01 00:00:00', 'UTC')), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime('2023-12-03 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('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC')))), 0), or(equals(events.event, '$pageview'), equals(events.event, '$screen'), and(equals(events.event, 'customer_created'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'plan'), ''), 'null'), '^"|"$', ''), 'paid'), 0))), 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.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: TestWebOverviewQueryRunner.test_goal_properties_preserve_visitors_and_deduplicate_customers_1_action+ '''+ SELECT uniq(session_person_id) AS unique_users,+ NULL AS previous_unique_users,+ sum(conversion_count) AS total_conversion_count,+ NULL AS previous_total_conversion_count,+ uniq(conversion_person_id) AS unique_conversions,+ NULL AS previous_unique_conversions,+ divide(unique_conversions, unique_users) AS conversion_rate,+ NULL AS previous_conversion_rate+ FROM+ (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS session_person_id,+ events__session.session_id AS session_id,+ min(events__session.`$start_timestamp`) AS start_timestamp,+ countIf(and(equals(events.event, 'customer_created'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'plan'), ''), 'null'), '^"|"$', ''), 'paid'), 0))) AS conversion_count,+ any(if(and(equals(events.event, 'customer_created'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'plan'), ''), 'null'), '^"|"$', ''), 'paid'), 0)), 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,+ 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('2023-12-01 00:00:00', 'UTC')), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC')), toIntervalDay(3))))+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.`$session_id_uuid`, events__session.session_id_v7)+ LEFT OUTER JOIN+ (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,+ person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 99999)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ WHERE and(equals(events.team_id, 99999), and(isNotNull(events.`$session_id`), or(equals(events.event, '$pageview'), equals(events.event, '$screen'), and(equals(events.event, 'customer_created'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'plan'), ''), 'null'), '^"|"$', ''), 'paid'), 0))), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC')))), 0), 1))+ GROUP BY session_id+ HAVING or(and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC')))), 0))+ LIMIT 100 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ optimize_rewrite_aggregate_function_with_if=0,+ optimize_min_inequality_conjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestWebOverviewQueryRunner.test_goal_properties_preserve_visitors_and_deduplicate_customers_1_action.1+ '''+ SELECT breakdown_value AS `context.columns.breakdown_value`,+ tuple(uniqIf(filtered_person_id, greater(filtered_pageview_count, 0)), NULL) AS `context.columns.visitors`,+ tuple(uniqIf(session_id, greater(filtered_pageview_count, 0)), NULL) AS `context.columns.sessions`,+ tuple(sum(filtered_pageview_count), NULL) AS `context.columns.views`,+ 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 anyIf(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), or(equals(events.event, '$pageview'), equals(events.event, '$screen'))) AS filtered_person_id,+ countIf(or(equals(events.event, '$pageview'), equals(events.event, '$screen'))) 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,+ countIf(and(equals(events.event, 'customer_created'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'plan'), ''), 'null'), '^"|"$', ''), 'paid'), 0))) AS conversion_count,+ any(if(and(equals(events.event, 'customer_created'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'plan'), ''), 'null'), '^"|"$', ''), 'paid'), 0)), if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), NULL)) AS conversion_person_id+ 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('2023-12-01 00:00:00', 'UTC')), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime('2023-12-03 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('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC')))), 0), or(equals(events.event, '$pageview'), equals(events.event, '$screen'), and(equals(events.event, 'customer_created'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'plan'), ''), 'null'), '^"|"$', ''), 'paid'), 0))), 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.unique_conversions` DESC,+ `context.columns.total_conversions` DESC,+ `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: TestWebOverviewQueryRunner.test_goal_properties_preserve_visitors_and_deduplicate_customers_1_action.2+ '''+ SELECT breakdown_value AS `context.columns.breakdown_value`,+ tuple(uniqIf(filtered_person_id, greater(filtered_pageview_count, 0)), NULL) AS `context.columns.visitors`,+ tuple(uniqIf(session_id, greater(filtered_pageview_count, 0)), NULL) AS `context.columns.sessions`,+ 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 anyIf(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), or(equals(events.event, '$pageview'), equals(events.event, '$screen'))) AS filtered_person_id,+ countIf(or(equals(events.event, '$pageview'), equals(events.event, '$screen'))) 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('2023-12-01 00:00:00', 'UTC')), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime('2023-12-03 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('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-03 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: TestWebOverviewQueryRunner.test_goal_properties_preserve_visitors_and_deduplicate_customers_1_action.3+ '''+ 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 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,+ countIf(and(equals(events.event, 'customer_created'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'plan'), ''), 'null'), '^"|"$', ''), 'paid'), 0))) AS conversion_count,+ any(if(and(equals(events.event, 'customer_created'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'plan'), ''), 'null'), '^"|"$', ''), 'paid'), 0)), if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), NULL)) AS conversion_person_id+ 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('2023-12-01 00:00:00', 'UTC')), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime('2023-12-03 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('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC')))), 0), or(equals(events.event, '$pageview'), equals(events.event, '$screen'), and(equals(events.event, 'customer_created'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'plan'), ''), 'null'), '^"|"$', ''), 'paid'), 0))), 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.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: TestWebOverviewQueryRunner.test_increase_in_users'''SELECT uniqIf(session_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS unique_users,diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_overview.py b/products/web_analytics/backend/hogql_queries/test/test_web_overview.pyindex 87946a2d4f6b..db07c11de39c 100644--- a/products/web_analytics/backend/hogql_queries/test/test_web_overview.py+++ b/products/web_analytics/backend/hogql_queries/test/test_web_overview.py@@ -33,6 +33,8 @@ from posthog.schema import (WebAnalyticsSampling,WebOverviewQuery,WebOverviewQueryResponse,+ WebStatsBreakdown,+ WebStatsTableQuery,)from posthog.hogql.constants import LimitContext@@ -47,6 +49,7 @@ from posthog.settings import HOGQL_INCREASED_MAX_EXECUTION_TIMEfrom products.actions.backend.models.action import Actionfrom products.cohorts.backend.models.cohort import Cohort+from products.web_analytics.backend.hogql_queries.stats_table import WebStatsTableQueryRunnerfrom products.web_analytics.backend.hogql_queries.test.first_pageview_attribution_test_base import (FirstPageviewAttributionTestMixin,)@@ -570,6 +573,69 @@ class TestWebOverviewQueryRunner(FirstPageviewAttributionTestMixin, ClickhouseTeconversion_rate = results[3]assert conversion_rate.value == 100+ @parameterized.expand([("event", False), ("action", True)])+ def test_goal_properties_preserve_visitors_and_deduplicate_customers(self, _name: str, use_action: bool) -> None:+ s1, s2 = str(uuid7("2023-12-01")), str(uuid7("2023-12-02"))+ self._create_events(+ [+ ("p1", [("2023-12-01", s1, "https://example.com")]),+ ("p2", [("2023-12-02", s2, "https://example.com")]),+ ]+ )+ self._create_events(+ [+ ("p1", [("2023-12-01", s1, None, {"plan": "paid"}), ("2023-12-01", s1, None, {"plan": "paid"})]),+ ("p2", [("2023-12-02", s2, None, {"plan": "free"})]),+ ],+ event="customer_created",+ )+ properties = [EventPropertyFilter(key="plan", value="paid", operator=PropertyOperator.EXACT)]+ goal: ActionConversionGoal | CustomEventConversionGoal+ if use_action:+ action = Action.objects.create(+ team=self.team, name="Customer created", steps_json=[{"event": "customer_created"}]+ )+ goal = ActionConversionGoal(actionId=action.id, properties=properties)+ else:+ goal = CustomEventConversionGoal(customEventName="customer_created", properties=properties)+ query = WebOverviewQuery(+ dateRange=DateRange(date_from="2023-12-01", date_to="2023-12-03"), properties=[], conversionGoal=goal+ )+ results = {+ item.key: item.value for item in WebOverviewQueryRunner(team=self.team, query=query).calculate().results+ }+ assert results["visitors"] == 2+ assert results["total conversions"] == 2+ assert results["unique conversions"] == 1+ assert results["conversion rate"] == 50+ self._create_events(+ [(f"goal_only_{i}", [("2023-12-02", str(uuid7("2023-12-02")), None, {"plan": "paid"})]) for i in range(3)],+ event="customer_created",+ )+ for selected_goal, include_traffic in [(goal, True), (None, True), (goal, None)]:+ table = WebStatsTableQueryRunner(+ team=self.team,+ query=WebStatsTableQuery(+ dateRange=query.dateRange,+ properties=[],+ breakdownBy=WebStatsBreakdown.INITIAL_CHANNEL_TYPE,+ conversionGoal=selected_goal,+ includeTrafficMetrics=include_traffic,+ ),+ ).calculate()+ assert table.columns is not None+ row = dict(zip(table.columns, table.results[0]))+ if include_traffic:+ assert row["context.columns.sessions"][0] == 2+ assert row["context.columns.views"][0] == 2+ assert row["context.columns.visitors"][0] == 2+ else:+ assert "context.columns.sessions" not in row+ assert row["context.columns.visitors"][0] == 5+ if selected_goal:+ assert row["context.columns.unique_conversions"][0] == 4+ assert row["context.columns.conversion_rate"][0] == (2 if include_traffic else 0.8)+def test_conversion_goal_one_custom_event_conversion(self):s1 = str(uuid7("2023-12-01"))self._create_events(diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_stats_table_pre_aggregated_conversions.py b/products/web_analytics/backend/hogql_queries/test/test_web_stats_table_pre_aggregated_conversions.pyindex 7404e62cbeb7..5caac76f0209 100644--- a/products/web_analytics/backend/hogql_queries/test/test_web_stats_table_pre_aggregated_conversions.py+++ b/products/web_analytics/backend/hogql_queries/test/test_web_stats_table_pre_aggregated_conversions.py@@ -1,9 +1,16 @@import time_machinefrom posthog.test.base import _create_event, _create_person, flush_persons_and_events+from django.test import override_settings++from parameterized import parameterized+from posthog.schema import (ActionConversionGoal,+ CompareFilter,+ CustomEventConversionGoal,DateRange,+ EventPropertyFilter,HogQLQueryModifiers,SessionTableVersion,WebStatsBreakdown,@@ -140,6 +147,113 @@ class TestWebStatsTablePreAggregatedConversions(WebAnalyticsPreAggregatedTestBasassert total_conversions_current == 0.0assert unique_conversions_current == 0.0assert conversion_rate_current == 0.0+ query.includeTrafficMetrics = True+ traffic_response = WebStatsTableQueryRunner(team=self.team, query=query, modifiers=modifiers).calculate()+ assert traffic_response.columns is not None+ traffic_row = dict(+ zip(traffic_response.columns, next(row for row in traffic_response.results if row[0] == "/page1"))+ )+ assert traffic_row["context.columns.sessions"][0] >= 1+ assert traffic_row["context.columns.views"][0] >= 1+ assert traffic_row["context.columns.unique_conversions"][0] >= 1+ query.conversionGoal = None+ without_goal = WebStatsTableQueryRunner(team=self.team, query=query, modifiers=modifiers).calculate()+ assert without_goal.columns is not None+ without_goal_row = dict(+ zip(without_goal.columns, next(row for row in without_goal.results if row[0] == "/page1"))+ )+ assert without_goal_row["context.columns.sessions"] == traffic_row["context.columns.sessions"]+ assert without_goal_row["context.columns.views"] == traffic_row["context.columns.views"]++ def test_traffic_population_excludes_goal_only_sessions(self):+ for i in range(3):+ distinct_id = f"goal_only_{i}"+ _create_person(team_id=self.team.pk, distinct_ids=[distinct_id])+ _create_event(+ team=self.team,+ event="customer_created",+ distinct_id=distinct_id,+ timestamp="2024-01-01T12:00:00Z",+ properties={+ "$session_id": str(uuid7("2024-01-01T12:00:00")),+ "$current_url": "https://example.com/page1",+ "$pathname": "/page1",+ },+ )+ flush_persons_and_events()+ sql = WEB_STATS_INSERT_SQL(+ date_start="2024-01-01", date_end="2024-01-02", team_ids=[self.team.pk], select_only=True+ )+ sync_execute(f"INSERT INTO web_pre_aggregated_stats {sql}")+ with time_machine.travel("2024-01-02T00:00:00Z", tick=False):+ for preaggregated in [False, True]:+ for goal in [CustomEventConversionGoal(customEventName="customer_created"), None]:+ response = WebStatsTableQueryRunner(+ team=self.team,+ query=WebStatsTableQuery(+ dateRange=DateRange(date_from="2024-01-01", date_to="2024-01-02"),+ breakdownBy=WebStatsBreakdown.PAGE,+ conversionGoal=goal,+ includeTrafficMetrics=True,+ properties=[],+ ),+ modifiers=HogQLQueryModifiers(+ sessionTableVersion=SessionTableVersion.V2,+ useWebAnalyticsPreAggregatedTables=preaggregated,+ ),+ ).calculate()+ assert response.columns is not None+ row = dict(zip(response.columns, next(row for row in response.results if row[0] == "/page1")))+ assert row["context.columns.visitors"][0] == 1+ assert row["context.columns.sessions"][0] == 1+ assert row["context.columns.views"][0] == 1+ if goal:+ assert row["context.columns.unique_conversions"][0] == 3+ assert row["context.columns.conversion_rate"][0] == 3++ @parameterized.expand(+ [+ ("join_bounce", False, False, False),+ ("join_time", False, False, True),+ ("no_join_bounce", True, False, False),+ ("no_join_time", True, False, True),+ ("session_set_bounce", False, True, False),+ ("session_set_time", False, True, True),+ ]+ )+ def test_page_traffic_metrics_with_engagement(+ self, _name: str, no_join: bool, session_set: bool, average_time: bool+ ) -> None:+ with (+ override_settings(+ WEB_ANALYTICS_NO_JOIN_TEAM_IDS=[self.team.pk] if no_join else [],+ WEB_ANALYTICS_SESSION_ID_SET_TEAM_IDS=[self.team.pk] if session_set else [],+ ),+ time_machine.travel("2024-01-02T00:00:00Z", tick=False),+ ):+ response = WebStatsTableQueryRunner(+ team=self.team,+ query=WebStatsTableQuery(+ dateRange=DateRange(date_from="2024-01-01", date_to="2024-01-02"),+ compareFilter=CompareFilter(compare=True),+ breakdownBy=WebStatsBreakdown.PAGE,+ includeTrafficMetrics=True,+ includeBounceRate=True,+ includeAvgTimeOnPage=average_time,+ properties=[EventPropertyFilter(key="$pathname", value="/page1")] if session_set else [],+ ),+ modifiers=HogQLQueryModifiers(+ sessionTableVersion=SessionTableVersion.V2, useWebAnalyticsPreAggregatedTables=False+ ),+ ).calculate()+ assert response.columns is not None+ row = dict(zip(response.columns, next(row for row in response.results if row[0] == "/page1")))+ assert row["context.columns.sessions"] == (1, 0)+ assert row["context.columns.visitors"] == (1, 0)+ assert row["context.columns.views"] == (1, 0)+ assert row["context.columns.bounce_rate"][0] == 1+ if average_time:+ assert "context.columns.avg_time_on_page" in rowdef test_conversion_goal_with_preaggregated_tables_bounce_style(self):"""Test conversion goals using bounce-rate-style query pattern (alternative implementation)"""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 b4e12d83f794..1a320e9cb252 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@@ -524,15 +524,18 @@ WHERE and(raise QueryError(f"Conversion goal action with id={self.query.conversionGoal.actionId} not found in this project.")- return action_to_expr(action)+ goal_expr = action_to_expr(action)elif isinstance(self.query.conversionGoal, CustomEventConversionGoal):- return ast.CompareOperation(+ goal_expr = ast.CompareOperation(left=ast.Field(chain=["events", "event"]),op=ast.CompareOperationOp.Eq,right=ast.Constant(value=self.query.conversionGoal.customEventName),)else:return None+ if self.query.conversionGoal.properties:+ return ast.And(exprs=[goal_expr, property_to_expr(self.query.conversionGoal.properties, team=self.team)])+ return goal_expr@cached_propertydef conversion_count_expr(self) -> Optional[ast.Expr]:diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 40163bcc0f5f..e662742fe1a4 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -2808,6 +2808,7 @@ export namespace Schemas {export interface ActionConversionGoal {actionId: number;+ properties?: (EventPropertyFilter | PersonPropertyFilter | SessionPropertyFilter | CohortPropertyFilter)[] | null;}export interface ActionReference {@@ -3666,6 +3667,7 @@ export namespace Schemas {export interface CustomEventConversionGoal {customEventName: string;+ properties?: (EventPropertyFilter | PersonPropertyFilter | SessionPropertyFilter | CohortPropertyFilter)[] | null;}export type DaysOfWeekEnum = typeof DaysOfWeekEnum[keyof typeof DaysOfWeekEnum];@@ -5145,6 +5147,7 @@ export namespace Schemas {includeHost?: boolean | null;includeRevenue?: boolean | null;includeScrollDepth?: boolean | null;+ includeTrafficMetrics?: boolean | null;/** Interval for date range calculation (affects date_to rounding for hour vs day ranges) */interval?: IntervalType | null;kind?: 'WebStatsTableQuery';diff --git a/services/mcp/src/tools/generated/web_analytics.ts b/services/mcp/src/tools/generated/web_analytics.tsindex 31172be8bcdd..f66bca060f23 100644--- a/services/mcp/src/tools/generated/web_analytics.ts+++ b/services/mcp/src/tools/generated/web_analytics.ts@@ -396,31 +396,6 @@ const CompareFilter = z.object({const integer = z.coerce.number().int()-const ActionConversionGoal = z.object({- actionId: integer,-})--const CustomEventConversionGoal = z.object({- customEventName: z.string(),-})--const WebAnalyticsConversionGoal = z.union([ActionConversionGoal, CustomEventConversionGoal])--const AssistantDateRange = z.object({- date_from: z.string().describe('ISO8601 date string.'),- date_to: z.string().nullable().describe('ISO8601 date string.').optional(),-})--const AssistantDurationRange = z.object({- date_from: z- .string()- .describe(- "Duration in the past. Supported units are: `h` (hour), `d` (day), `w` (week), `m` (month), `y` (year), `all` (all time). Use the `Start` suffix to define the exact left date boundary. Examples: `-1d` last day from now, `-180d` last 180 days from now, `mStart` this month start, `-1dStart` yesterday's start."- ),-})--const AssistantDateRangeFilter = z.union([AssistantDateRange, AssistantDurationRange])-const PropertyOperator = z.enum(['exact','is_not',@@ -508,6 +483,33 @@ const WebAnalyticsPropertyFilter = z.union([const WebAnalyticsPropertyFilters = z.array(WebAnalyticsPropertyFilter)+const ActionConversionGoal = z.object({+ actionId: integer,+ properties: WebAnalyticsPropertyFilters.optional(),+})++const CustomEventConversionGoal = z.object({+ customEventName: z.string(),+ properties: WebAnalyticsPropertyFilters.optional(),+})++const WebAnalyticsConversionGoal = z.union([ActionConversionGoal, CustomEventConversionGoal])++const AssistantDateRange = z.object({+ date_from: z.string().describe('ISO8601 date string.'),+ date_to: z.string().nullable().describe('ISO8601 date string.').optional(),+})++const AssistantDurationRange = z.object({+ date_from: z+ .string()+ .describe(+ "Duration in the past. Supported units are: `h` (hour), `d` (day), `w` (week), `m` (month), `y` (year), `all` (all time). Use the `Start` suffix to define the exact left date boundary. Examples: `-1d` last day from now, `-180d` last 180 days from now, `mStart` this month start, `-1dStart` yesterday's start."+ ),+})++const AssistantDateRangeFilter = z.union([AssistantDateRange, AssistantDurationRange])+const AssistantWebOverviewQuery = z.object({compareFilter: CompareFilter.describe('Compare the current period to a prior period. Disabled by default. Enabling roughly doubles query cost — leave it off unless the user explicitly asks for a period-over-period comparison.'diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-web-overview.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-web-overview.jsonindex 5739735789df..4d20a863bbed 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-web-overview.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-web-overview.json@@ -26,6 +26,375 @@"maximum": 9007199254740991,"minimum": -9007199254740991,"type": "integer"+ },+ "properties": {+ "items": {+ "anyOf": [+ {+ "properties": {+ "key": {+ "type": "string"+ },+ "label": {+ "type": "string"+ },+ "operator": {+ "default": "exact",+ "enum": [+ "exact",+ "is_not",+ "icontains",+ "not_icontains",+ "starts_with",+ "not_starts_with",+ "ends_with",+ "not_ends_with",+ "regex",+ "not_regex",+ "gt",+ "gte",+ "lt",+ "lte",+ "is_set",+ "is_not_set",+ "is_date_exact",+ "is_date_before",+ "is_date_after",+ "between",+ "not_between",+ "min",+ "max",+ "in",+ "not_in",+ "is_cleaned_path_exact",+ "flag_evaluates_to",+ "semver_eq",+ "semver_neq",+ "semver_gt",+ "semver_gte",+ "semver_lt",+ "semver_lte",+ "semver_tilde",+ "semver_caret",+ "semver_wildcard",+ "icontains_multi",+ "not_icontains_multi"+ ],+ "type": "string"+ },+ "type": {+ "const": "event",+ "default": "event",+ "description": "Event properties",+ "type": "string"+ },+ "value": {+ "anyOf": [+ {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "number"+ },+ {+ "type": "boolean"+ }+ ]+ },+ {+ "items": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "number"+ },+ {+ "type": "boolean"+ }+ ]+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ "required": ["key"],+ "type": "object"+ },+ {+ "properties": {+ "key": {+ "type": "string"+ },+ "label": {+ "type": "string"+ },+ "operator": {+ "enum": [+ "exact",+ "is_not",+ "icontains",+ "not_icontains",+ "starts_with",+ "not_starts_with",+ "ends_with",+ "not_ends_with",+ "regex",+ "not_regex",+ "gt",+ "gte",+ "lt",+ "lte",+ "is_set",+ "is_not_set",+ "is_date_exact",+ "is_date_before",+ "is_date_after",+ "between",+ "not_between",+ "min",+ "max",+ "in",+ "not_in",+ "is_cleaned_path_exact",+ "flag_evaluates_to",+ "semver_eq",+ "semver_neq",+ "semver_gt",+ "semver_gte",+ "semver_lt",+ "semver_lte",+ "semver_tilde",+ "semver_caret",+ "semver_wildcard",+ "icontains_multi",+ "not_icontains_multi"+ ],+ "type": "string"+ },+ "type": {+ "const": "person",+ "default": "person",+ "description": "Person properties",+ "type": "string"+ },+ "value": {+ "anyOf": [+ {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "number"+ },+ {+ "type": "boolean"+ }+ ]+ },+ {+ "items": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "number"+ },+ {+ "type": "boolean"+ }+ ]+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ "required": ["key", "operator"],+ "type": "object"+ },+ {+ "properties": {+ "key": {+ "type": "string"+ },+ "label": {+ "type": "string"+ },+ "operator": {+ "enum": [+ "exact",+ "is_not",+ "icontains",+ "not_icontains",+ "starts_with",+ "not_starts_with",+ "ends_with",+ "not_ends_with",+ "regex",+ "not_regex",+ "gt",+ "gte",+ "lt",+ "lte",+ "is_set",+ "is_not_set",+ "is_date_exact",+ "is_date_before",+ "is_date_after",+ "between",+ "not_between",+ "min",+ "max",+ "in",+ "not_in",+ "is_cleaned_path_exact",+ "flag_evaluates_to",+ "semver_eq",+ "semver_neq",+ "semver_gt",+ "semver_gte",+ "semver_lt",+ "semver_lte",+ "semver_tilde",+ "semver_caret",+ "semver_wildcard",+ "icontains_multi",+ "not_icontains_multi"+ ],+ "type": "string"+ },+ "type": {+ "const": "session",+ "default": "session",+ "type": "string"+ },+ "value": {+ "anyOf": [+ {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "number"+ },+ {+ "type": "boolean"+ }+ ]+ },+ {+ "items": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "number"+ },+ {+ "type": "boolean"+ }+ ]+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ "required": ["key", "operator"],+ "type": "object"+ },+ {+ "properties": {+ "cohort_name": {+ "type": "string"+ },+ "key": {+ "const": "id",+ "default": "id",+ "type": "string"+ },+ "label": {+ "type": "string"+ },+ "operator": {+ "default": "in",+ "enum": [+ "exact",+ "is_not",+ "icontains",+ "not_icontains",+ "starts_with",+ "not_starts_with",+ "ends_with",+ "not_ends_with",+ "regex",+ "not_regex",+ "gt",+ "gte",+ "lt",+ "lte",+ "is_set",+ "is_not_set",+ "is_date_exact",+ "is_date_before",+ "is_date_after",+ "between",+ "not_between",+ "min",+ "max",+ "in",+ "not_in",+ "is_cleaned_path_exact",+ "flag_evaluates_to",+ "semver_eq",+ "semver_neq",+ "semver_gt",+ "semver_gte",+ "semver_lt",+ "semver_lte",+ "semver_tilde",+ "semver_caret",+ "semver_wildcard",+ "icontains_multi",+ "not_icontains_multi"+ ],+ "type": "string"+ },+ "type": {+ "const": "cohort",+ "default": "cohort",+ "type": "string"+ },+ "value": {+ "maximum": 9007199254740991,+ "minimum": -9007199254740991,+ "type": "integer"+ }+ },+ "required": ["value"],+ "type": "object"+ }+ ]+ },+ "type": "array"}},"required": ["actionId"],@@ -35,6 +404,375 @@"properties": {"customEventName": {"type": "string"+ },+ "properties": {+ "items": {+ "anyOf": [+ {+ "properties": {+ "key": {+ "type": "string"+ },+ "label": {+ "type": "string"+ },+ "operator": {+ "default": "exact",+ "enum": [+ "exact",+ "is_not",+ "icontains",+ "not_icontains",+ "starts_with",+ "not_starts_with",+ "ends_with",+ "not_ends_with",+ "regex",+ "not_regex",+ "gt",+ "gte",+ "lt",+ "lte",+ "is_set",+ "is_not_set",+ "is_date_exact",+ "is_date_before",+ "is_date_after",+ "between",+ "not_between",+ "min",+ "max",+ "in",+ "not_in",+ "is_cleaned_path_exact",+ "flag_evaluates_to",+ "semver_eq",+ "semver_neq",+ "semver_gt",+ "semver_gte",+ "semver_lt",+ "semver_lte",+ "semver_tilde",+ "semver_caret",+ "semver_wildcard",+ "icontains_multi",+ "not_icontains_multi"+ ],+ "type": "string"+ },+ "type": {+ "const": "event",+ "default": "event",+ "description": "Event properties",+ "type": "string"+ },+ "value": {+ "anyOf": [+ {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "number"+ },+ {+ "type": "boolean"+ }+ ]+ },+ {+ "items": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "number"+ },+ {+ "type": "boolean"+ }+ ]+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ "required": ["key"],+ "type": "object"+ },+ {+ "properties": {+ "key": {+ "type": "string"+ },+ "label": {+ "type": "string"+ },+ "operator": {+ "enum": [+ "exact",+ "is_not",+ "icontains",+ "not_icontains",+ "starts_with",+ "not_starts_with",+ "ends_with",+ "not_ends_with",+ "regex",+ "not_regex",+ "gt",+ "gte",+ "lt",+ "lte",+ "is_set",+ "is_not_set",+ "is_date_exact",+ "is_date_before",+ "is_date_after",+ "between",+ "not_between",+ "min",+ "max",+ "in",+ "not_in",+ "is_cleaned_path_exact",+ "flag_evaluates_to",+ "semver_eq",+ "semver_neq",+ "semver_gt",+ "semver_gte",+ "semver_lt",+ "semver_lte",+ "semver_tilde",+ "semver_caret",+ "semver_wildcard",+ "icontains_multi",+ "not_icontains_multi"+ ],+ "type": "string"+ },+ "type": {+ "const": "person",+ "default": "person",+ "description": "Person properties",+ "type": "string"+ },+ "value": {+ "anyOf": [+ {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "number"+ },+ {+ "type": "boolean"+ }+ ]+ },+ {+ "items": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "number"+ },+ {+ "type": "boolean"+ }+ ]+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ "required": ["key", "operator"],+ "type": "object"+ },+ {+ "properties": {+ "key": {+ "type": "string"+ },+ "label": {+ "type": "string"+ },+ "operator": {+ "enum": [+ "exact",+ "is_not",+ "icontains",+ "not_icontains",+ "starts_with",+ "not_starts_with",+ "ends_with",+ "not_ends_with",+ "regex",+ "not_regex",+ "gt",+ "gte",+ "lt",+ "lte",+ "is_set",+ "is_not_set",+ "is_date_exact",+ "is_date_before",+ "is_date_after",+ "between",+ "not_between",+ "min",+ "max",+ "in",+ "not_in",+ "is_cleaned_path_exact",+ "flag_evaluates_to",+ "semver_eq",+ "semver_neq",+ "semver_gt",+ "semver_gte",+ "semver_lt",+ "semver_lte",+ "semver_tilde",+ "semver_caret",+ "semver_wildcard",+ "icontains_multi",+ "not_icontains_multi"+ ],+ "type": "string"+ },+ "type": {+ "const": "session",+ "default": "session",+ "type": "string"+ },+ "value": {+ "anyOf": [+ {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "number"+ },+ {+ "type": "boolean"+ }+ ]+ },+ {+ "items": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "number"+ },+ {+ "type": "boolean"+ }+ ]+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ "required": ["key", "operator"],+ "type": "object"+ },+ {+ "properties": {+ "cohort_name": {+ "type": "string"+ },+ "key": {+ "const": "id",+ "default": "id",+ "type": "string"+ },+ "label": {+ "type": "string"+ },+ "operator": {+ "default": "in",+ "enum": [+ "exact",+ "is_not",+ "icontains",+ "not_icontains",+ "starts_with",+ "not_starts_with",+ "ends_with",+ "not_ends_with",+ "regex",+ "not_regex",+ "gt",+ "gte",+ "lt",+ "lte",+ "is_set",+ "is_not_set",+ "is_date_exact",+ "is_date_before",+ "is_date_after",+ "between",+ "not_between",+ "min",+ "max",+ "in",+ "not_in",+ "is_cleaned_path_exact",+ "flag_evaluates_to",+ "semver_eq",+ "semver_neq",+ "semver_gt",+ "semver_gte",+ "semver_lt",+ "semver_lte",+ "semver_tilde",+ "semver_caret",+ "semver_wildcard",+ "icontains_multi",+ "not_icontains_multi"+ ],+ "type": "string"+ },+ "type": {+ "const": "cohort",+ "default": "cohort",+ "type": "string"+ },+ "value": {+ "maximum": 9007199254740991,+ "minimum": -9007199254740991,+ "type": "integer"+ }+ },+ "required": ["value"],+ "type": "object"+ }+ ]+ },+ "type": "array"}},"required": ["customEventName"],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 a36d818b7a79..561ad1ff1834 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@@ -65,6 +65,375 @@"maximum": 9007199254740991,"minimum": -9007199254740991,"type": "integer"+ },+ "properties": {+ "items": {+ "anyOf": [+ {+ "properties": {+ "key": {+ "type": "string"+ },+ "label": {+ "type": "string"+ },+ "operator": {+ "default": "exact",+ "enum": [+ "exact",+ "is_not",+ "icontains",+ "not_icontains",+ "starts_with",+ "not_starts_with",+ "ends_with",+ "not_ends_with",+ "regex",+ "not_regex",+ "gt",+ "gte",+ "lt",+ "lte",+ "is_set",+ "is_not_set",+ "is_date_exact",+ "is_date_before",+ "is_date_after",+ "between",+ "not_between",+ "min",+ "max",+ "in",+ "not_in",+ "is_cleaned_path_exact",+ "flag_evaluates_to",+ "semver_eq",+ "semver_neq",+ "semver_gt",+ "semver_gte",+ "semver_lt",+ "semver_lte",+ "semver_tilde",+ "semver_caret",+ "semver_wildcard",+ "icontains_multi",+ "not_icontains_multi"+ ],+ "type": "string"+ },+ "type": {+ "const": "event",+ "default": "event",+ "description": "Event properties",+ "type": "string"+ },+ "value": {+ "anyOf": [+ {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "number"+ },+ {+ "type": "boolean"+ }+ ]+ },+ {+ "items": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "number"+ },+ {+ "type": "boolean"+ }+ ]+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ "required": ["key"],+ "type": "object"+ },+ {+ "properties": {+ "key": {+ "type": "string"+ },+ "label": {+ "type": "string"+ },+ "operator": {+ "enum": [+ "exact",+ "is_not",+ "icontains",+ "not_icontains",+ "starts_with",+ "not_starts_with",+ "ends_with",+ "not_ends_with",+ "regex",+ "not_regex",+ "gt",+ "gte",+ "lt",+ "lte",+ "is_set",+ "is_not_set",+ "is_date_exact",+ "is_date_before",+ "is_date_after",+ "between",+ "not_between",+ "min",+ "max",+ "in",+ "not_in",+ "is_cleaned_path_exact",+ "flag_evaluates_to",+ "semver_eq",+ "semver_neq",+ "semver_gt",+ "semver_gte",+ "semver_lt",+ "semver_lte",+ "semver_tilde",+ "semver_caret",+ "semver_wildcard",+ "icontains_multi",+ "not_icontains_multi"+ ],+ "type": "string"+ },+ "type": {+ "const": "person",+ "default": "person",+ "description": "Person properties",+ "type": "string"+ },+ "value": {+ "anyOf": [+ {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "number"+ },+ {+ "type": "boolean"+ }+ ]+ },+ {+ "items": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "number"+ },+ {+ "type": "boolean"+ }+ ]+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ "required": ["key", "operator"],+ "type": "object"+ },+ {+ "properties": {+ "key": {+ "type": "string"+ },+ "label": {+ "type": "string"+ },+ "operator": {+ "enum": [+ "exact",+ "is_not",+ "icontains",+ "not_icontains",+ "starts_with",+ "not_starts_with",+ "ends_with",+ "not_ends_with",+ "regex",+ "not_regex",+ "gt",+ "gte",+ "lt",+ "lte",+ "is_set",+ "is_not_set",+ "is_date_exact",+ "is_date_before",+ "is_date_after",+ "between",+ "not_between",+ "min",+ "max",+ "in",+ "not_in",+ "is_cleaned_path_exact",+ "flag_evaluates_to",+ "semver_eq",+ "semver_neq",+ "semver_gt",+ "semver_gte",+ "semver_lt",+ "semver_lte",+ "semver_tilde",+ "semver_caret",+ "semver_wildcard",+ "icontains_multi",+ "not_icontains_multi"+ ],+ "type": "string"+ },+ "type": {+ "const": "session",+ "default": "session",+ "type": "string"+ },+ "value": {+ "anyOf": [+ {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "number"+ },+ {+ "type": "boolean"+ }+ ]+ },+ {+ "items": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "number"+ },+ {+ "type": "boolean"+ }+ ]+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ "required": ["key", "operator"],+ "type": "object"+ },+ {+ "properties": {+ "cohort_name": {+ "type": "string"+ },+ "key": {+ "const": "id",+ "default": "id",+ "type": "string"+ },+ "label": {+ "type": "string"+ },+ "operator": {+ "default": "in",+ "enum": [+ "exact",+ "is_not",+ "icontains",+ "not_icontains",+ "starts_with",+ "not_starts_with",+ "ends_with",+ "not_ends_with",+ "regex",+ "not_regex",+ "gt",+ "gte",+ "lt",+ "lte",+ "is_set",+ "is_not_set",+ "is_date_exact",+ "is_date_before",+ "is_date_after",+ "between",+ "not_between",+ "min",+ "max",+ "in",+ "not_in",+ "is_cleaned_path_exact",+ "flag_evaluates_to",+ "semver_eq",+ "semver_neq",+ "semver_gt",+ "semver_gte",+ "semver_lt",+ "semver_lte",+ "semver_tilde",+ "semver_caret",+ "semver_wildcard",+ "icontains_multi",+ "not_icontains_multi"+ ],+ "type": "string"+ },+ "type": {+ "const": "cohort",+ "default": "cohort",+ "type": "string"+ },+ "value": {+ "maximum": 9007199254740991,+ "minimum": -9007199254740991,+ "type": "integer"+ }+ },+ "required": ["value"],+ "type": "object"+ }+ ]+ },+ "type": "array"}},"required": ["actionId"],@@ -74,6 +443,375 @@"properties": {"customEventName": {"type": "string"+ },+ "properties": {+ "items": {+ "anyOf": [+ {+ "properties": {+ "key": {+ "type": "string"+ },+ "label": {+ "type": "string"+ },+ "operator": {+ "default": "exact",+ "enum": [+ "exact",+ "is_not",+ "icontains",+ "not_icontains",+ "starts_with",+ "not_starts_with",+ "ends_with",+ "not_ends_with",+ "regex",+ "not_regex",+ "gt",+ "gte",+ "lt",+ "lte",+ "is_set",+ "is_not_set",+ "is_date_exact",+ "is_date_before",+ "is_date_after",+ "between",+ "not_between",+ "min",+ "max",+ "in",+ "not_in",+ "is_cleaned_path_exact",+ "flag_evaluates_to",+ "semver_eq",+ "semver_neq",+ "semver_gt",+ "semver_gte",+ "semver_lt",+ "semver_lte",+ "semver_tilde",+ "semver_caret",+ "semver_wildcard",+ "icontains_multi",+ "not_icontains_multi"+ ],+ "type": "string"+ },+ "type": {+ "const": "event",+ "default": "event",+ "description": "Event properties",+ "type": "string"+ },+ "value": {+ "anyOf": [+ {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "number"+ },+ {+ "type": "boolean"+ }+ ]+ },+ {+ "items": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "number"+ },+ {+ "type": "boolean"+ }+ ]+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ "required": ["key"],+ "type": "object"+ },+ {+ "properties": {+ "key": {+ "type": "string"+ },+ "label": {+ "type": "string"+ },+ "operator": {+ "enum": [+ "exact",+ "is_not",+ "icontains",+ "not_icontains",+ "starts_with",+ "not_starts_with",+ "ends_with",+ "not_ends_with",+ "regex",+ "not_regex",+ "gt",+ "gte",+ "lt",+ "lte",+ "is_set",+ "is_not_set",+ "is_date_exact",+ "is_date_before",+ "is_date_after",+ "between",+ "not_between",+ "min",+ "max",+ "in",+ "not_in",+ "is_cleaned_path_exact",+ "flag_evaluates_to",+ "semver_eq",+ "semver_neq",+ "semver_gt",+ "semver_gte",+ "semver_lt",+ "semver_lte",+ "semver_tilde",+ "semver_caret",+ "semver_wildcard",+ "icontains_multi",+ "not_icontains_multi"+ ],+ "type": "string"+ },+ "type": {+ "const": "person",+ "default": "person",+ "description": "Person properties",+ "type": "string"+ },+ "value": {+ "anyOf": [+ {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "number"+ },+ {+ "type": "boolean"+ }+ ]+ },+ {+ "items": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "number"+ },+ {+ "type": "boolean"+ }+ ]+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ "required": ["key", "operator"],+ "type": "object"+ },+ {+ "properties": {+ "key": {+ "type": "string"+ },+ "label": {+ "type": "string"+ },+ "operator": {+ "enum": [+ "exact",+ "is_not",+ "icontains",+ "not_icontains",+ "starts_with",+ "not_starts_with",+ "ends_with",+ "not_ends_with",+ "regex",+ "not_regex",+ "gt",+ "gte",+ "lt",+ "lte",+ "is_set",+ "is_not_set",+ "is_date_exact",+ "is_date_before",+ "is_date_after",+ "between",+ "not_between",+ "min",+ "max",+ "in",+ "not_in",+ "is_cleaned_path_exact",+ "flag_evaluates_to",+ "semver_eq",+ "semver_neq",+ "semver_gt",+ "semver_gte",+ "semver_lt",+ "semver_lte",+ "semver_tilde",+ "semver_caret",+ "semver_wildcard",+ "icontains_multi",+ "not_icontains_multi"+ ],+ "type": "string"+ },+ "type": {+ "const": "session",+ "default": "session",+ "type": "string"+ },+ "value": {+ "anyOf": [+ {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "number"+ },+ {+ "type": "boolean"+ }+ ]+ },+ {+ "items": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "number"+ },+ {+ "type": "boolean"+ }+ ]+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ "required": ["key", "operator"],+ "type": "object"+ },+ {+ "properties": {+ "cohort_name": {+ "type": "string"+ },+ "key": {+ "const": "id",+ "default": "id",+ "type": "string"+ },+ "label": {+ "type": "string"+ },+ "operator": {+ "default": "in",+ "enum": [+ "exact",+ "is_not",+ "icontains",+ "not_icontains",+ "starts_with",+ "not_starts_with",+ "ends_with",+ "not_ends_with",+ "regex",+ "not_regex",+ "gt",+ "gte",+ "lt",+ "lte",+ "is_set",+ "is_not_set",+ "is_date_exact",+ "is_date_before",+ "is_date_after",+ "between",+ "not_between",+ "min",+ "max",+ "in",+ "not_in",+ "is_cleaned_path_exact",+ "flag_evaluates_to",+ "semver_eq",+ "semver_neq",+ "semver_gt",+ "semver_gte",+ "semver_lt",+ "semver_lte",+ "semver_tilde",+ "semver_caret",+ "semver_wildcard",+ "icontains_multi",+ "not_icontains_multi"+ ],+ "type": "string"+ },+ "type": {+ "const": "cohort",+ "default": "cohort",+ "type": "string"+ },+ "value": {+ "maximum": 9007199254740991,+ "minimum": -9007199254740991,+ "type": "integer"+ }+ },+ "required": ["value"],+ "type": "object"+ }+ ]+ },+ "type": "array"}},"required": ["customEventName"],