Skip to content

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

feat(marketing): attribution explorer refresh, exclude unattributed, and conversion paths (#76886)

Mike Warrene72366fb9b47
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 914f4f3f2c9c..5f52d033842f 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -909,6 +909,9 @@
{
"$ref": "#/definitions/MarketingAnalyticsAttributionQuery"
},
+ {
+ "$ref": "#/definitions/MarketingAnalyticsAttributionPathsQuery"
+ },
{
"$ref": "#/definitions/NonIntegratedConversionsTableQuery"
},
@@ -10032,6 +10035,135 @@
],
"type": "object"
},
+ "CachedMarketingAnalyticsAttributionPathsQueryResponse": {
+ "additionalProperties": false,
+ "properties": {
+ "attributedConversions": {
+ "$ref": "#/definitions/integer",
+ "description": "Conversions with at least one in-window touchpoint. The share denominator — deliberately unfiltered by min/maxTouchpoints so shares stay comparable across filter values."
+ },
+ "attributionWindowDays": {
+ "$ref": "#/definitions/integer",
+ "description": "The attribution window actually used, for the tooltips."
+ },
+ "cache_key": {
+ "type": "string"
+ },
+ "cache_target_age": {
+ "format": "date-time",
+ "type": "string"
+ },
+ "calculation_trigger": {
+ "description": "What triggered the calculation of the query, leave empty if user/immediate",
+ "type": "string"
+ },
+ "error": {
+ "description": "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise.",
+ "type": "string"
+ },
+ "hasMore": {
+ "type": "boolean"
+ },
+ "hasValue": {
+ "description": "Whether the goal is revenue-bearing, which gates the value column.",
+ "type": "boolean"
+ },
+ "hogql": {
+ "description": "Generated HogQL query.",
+ "type": "string"
+ },
+ "is_cached": {
+ "type": "boolean"
+ },
+ "last_refresh": {
+ "format": "date-time",
+ "type": "string"
+ },
+ "limit": {
+ "$ref": "#/definitions/integer"
+ },
+ "modifiers": {
+ "$ref": "#/definitions/HogQLQueryModifiers",
+ "description": "Modifiers used when performing the query"
+ },
+ "next_allowed_client_refresh": {
+ "format": "date-time",
+ "type": "string"
+ },
+ "offset": {
+ "$ref": "#/definitions/integer"
+ },
+ "query_metadata": {
+ "type": "object"
+ },
+ "query_status": {
+ "$ref": "#/definitions/QueryStatus",
+ "description": "Query status indicates whether next to the provided data, a query is still running."
+ },
+ "resolved_compare_date_range": {
+ "$ref": "#/definitions/ResolvedDateRangeResponse",
+ "description": "The resolved previous/comparison period date range, when comparing against another period"
+ },
+ "resolved_date_range": {
+ "$ref": "#/definitions/ResolvedDateRangeResponse",
+ "description": "The date range used for the query"
+ },
+ "results": {
+ "items": {
+ "$ref": "#/definitions/MarketingAnalyticsAttributionPathRow"
+ },
+ "type": "array"
+ },
+ "timezone": {
+ "type": "string"
+ },
+ "timings": {
+ "description": "Measured timings for different parts of the query generation process",
+ "items": {
+ "$ref": "#/definitions/QueryTiming"
+ },
+ "type": "array"
+ },
+ "totalConversions": {
+ "$ref": "#/definitions/integer",
+ "description": "All conversions in range, before the touchpoint-count filter."
+ },
+ "used_data_warehouse_sources": {
+ "description": "Connector-synced data warehouse sources referenced by this query, if any.",
+ "items": {
+ "$ref": "#/definitions/DataWarehouseSourceUsage"
+ },
+ "type": "array"
+ },
+ "warnings": {
+ "description": "Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access.",
+ "items": {
+ "anyOf": [
+ {
+ "$ref": "#/definitions/DataWarehouseSyncWarning"
+ },
+ {
+ "$ref": "#/definitions/AccessControlFilterWarning"
+ }
+ ]
+ },
+ "type": "array"
+ }
+ },
+ "required": [
+ "attributedConversions",
+ "attributionWindowDays",
+ "cache_key",
+ "hasValue",
+ "is_cached",
+ "last_refresh",
+ "next_allowed_client_refresh",
+ "results",
+ "timezone",
+ "totalConversions"
+ ],
+ "type": "object"
+ },
"CachedMarketingAnalyticsAttributionQueryResponse": {
"additionalProperties": false,
"properties": {
@@ -31637,6 +31769,245 @@
"required": ["model", "conversions", "conversionRate", "conversionValue"],
"type": "object"
},
+ "MarketingAnalyticsAttributionPathRow": {
+ "additionalProperties": false,
+ "properties": {
+ "conversionValue": {
+ "description": "Null unless the goal is revenue-bearing.",
+ "type": ["number", "null"]
+ },
+ "conversions": {
+ "$ref": "#/definitions/integer",
+ "description": "Conversions whose in-window touchpoints form exactly this path."
+ },
+ "path": {
+ "description": "Breakdown values in touch order, oldest first. Consecutive repeats are preserved — collapsing them to \"×N\" is a display concern. Truncated to the most recent steps when the journey is longer than the grouping cap.",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "pathTruncated": {
+ "description": "True when at least one grouped conversion had more touchpoints than the path shows.",
+ "type": "boolean"
+ }
+ },
+ "required": ["path", "conversions", "conversionValue", "pathTruncated"],
+ "type": "object"
+ },
+ "MarketingAnalyticsAttributionPathsQuery": {
+ "additionalProperties": false,
+ "properties": {
+ "aggregation_group_type_index": {
+ "anyOf": [
+ {
+ "$ref": "#/definitions/integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Groups aggregation - not used in Web Analytics but required for type compatibility"
+ },
+ "allowMultipleConversionsPerVisitor": {
+ "description": "Whether one person converting repeatedly contributes one path or one per conversion. Null follows the goal's math.",
+ "type": "boolean"
+ },
+ "breakdownBy": {
+ "$ref": "#/definitions/MarketingAnalyticsAttributionBreakdown",
+ "description": "Path step dimension. Defaults to channel."
+ },
+ "conversionGoal": {
+ "anyOf": [
+ {
+ "$ref": "#/definitions/WebAnalyticsConversionGoal"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "conversionGoalId": {
+ "description": "conversion_goal_id of the goal whose conversions the paths lead to.",
+ "type": "string"
+ },
+ "dataColorTheme": {
+ "description": "Colors used in the insight's visualization - not used in Web Analytics but required for type compatibility",
+ "type": ["number", "null"]
+ },
+ "dateRange": {
+ "$ref": "#/definitions/DateRange"
+ },
+ "doPathCleaning": {
+ "type": "boolean"
+ },
+ "excludeDirectTraffic": {
+ "description": "Drop direct sessions from every path, mirroring the attribution table's option.",
+ "type": "boolean"
+ },
+ "excludeUnattributed": {
+ "description": "Drop touchpoints whose breakdown value is empty or unknown — the \"(none)\" steps.",
+ "type": "boolean"
+ },
+ "filterTestAccounts": {
+ "description": "Filter test accounts",
+ "type": "boolean"
+ },
+ "includeRevenue": {
+ "deprecated": "ignored, always treated as disabled",
+ "type": "boolean"
+ },
+ "interval": {
+ "$ref": "#/definitions/IntervalType",
+ "description": "Interval for date range calculation (affects date_to rounding for hour vs day ranges)"
+ },
+ "kind": {
+ "const": "MarketingAnalyticsAttributionPathsQuery",
+ "type": "string"
+ },
+ "limit": {
+ "$ref": "#/definitions/integer",
+ "description": "Number of rows to return"
+ },
+ "lookbackWindowDays": {
+ "$ref": "#/definitions/integer",
+ "description": "How many days before each conversion a touchpoint can be part of its path, overriding the team's configured attribution window for this query only."
+ },
+ "maxTouchpoints": {
+ "$ref": "#/definitions/integer",
+ "description": "Only paths with at most this many touchpoints, counted before truncation."
+ },
+ "minTouchpoints": {
+ "$ref": "#/definitions/integer",
+ "description": "Only paths with at least this many touchpoints, counted before truncation."
+ },
+ "modifiers": {
+ "$ref": "#/definitions/HogQLQueryModifiers",
+ "description": "Modifiers used when performing the query"
+ },
+ "offset": {
+ "$ref": "#/definitions/integer",
+ "description": "Number of rows to skip before returning rows"
+ },
+ "properties": {
+ "$ref": "#/definitions/WebAnalyticsPropertyFilters"
+ },
+ "response": {
+ "$ref": "#/definitions/MarketingAnalyticsAttributionPathsQueryResponse"
+ },
+ "sampling": {
+ "$ref": "#/definitions/WebAnalyticsSampling",
+ "deprecated": "Use samplingFactor instead"
+ },
+ "samplingFactor": {
+ "description": "Sampling rate",
+ "type": ["number", "null"]
+ },
+ "tags": {
+ "$ref": "#/definitions/QueryLogTags"
+ },
+ "useSessionsTable": {
+ "deprecated": "ignored, always treated as enabled *",
+ "type": "boolean"
+ },
+ "version": {
+ "description": "version of the node, used for schema migrations",
+ "type": "number"
+ }
+ },
+ "required": ["conversionGoalId", "kind", "properties"],
+ "type": "object"
+ },
+ "MarketingAnalyticsAttributionPathsQueryResponse": {
+ "additionalProperties": false,
+ "properties": {
+ "attributedConversions": {
+ "$ref": "#/definitions/integer",
+ "description": "Conversions with at least one in-window touchpoint. The share denominator — deliberately unfiltered by min/maxTouchpoints so shares stay comparable across filter values."
+ },
+ "attributionWindowDays": {
+ "$ref": "#/definitions/integer",
+ "description": "The attribution window actually used, for the tooltips."
+ },
+ "error": {
+ "description": "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise.",
+ "type": "string"
+ },
+ "hasMore": {
+ "type": "boolean"
+ },
+ "hasValue": {
+ "description": "Whether the goal is revenue-bearing, which gates the value column.",
+ "type": "boolean"
+ },
+ "hogql": {
+ "description": "Generated HogQL query.",
+ "type": "string"
+ },
+ "limit": {
+ "$ref": "#/definitions/integer"
+ },
+ "modifiers": {
+ "$ref": "#/definitions/HogQLQueryModifiers",
+ "description": "Modifiers used when performing the query"
+ },
+ "offset": {
+ "$ref": "#/definitions/integer"
+ },
+ "query_status": {
+ "$ref": "#/definitions/QueryStatus",
+ "description": "Query status indicates whether next to the provided data, a query is still running."
+ },
+ "resolved_compare_date_range": {
+ "$ref": "#/definitions/ResolvedDateRangeResponse",
+ "description": "The resolved previous/comparison period date range, when comparing against another period"
+ },
+ "resolved_date_range": {
+ "$ref": "#/definitions/ResolvedDateRangeResponse",
+ "description": "The date range used for the query"
+ },
+ "results": {
+ "items": {
+ "$ref": "#/definitions/MarketingAnalyticsAttributionPathRow"
+ },
+ "type": "array"
+ },
+ "timings": {
+ "description": "Measured timings for different parts of the query generation process",
+ "items": {
+ "$ref": "#/definitions/QueryTiming"
+ },
+ "type": "array"
+ },
+ "totalConversions": {
+ "$ref": "#/definitions/integer",
+ "description": "All conversions in range, before the touchpoint-count filter."
+ },
+ "used_data_warehouse_sources": {
+ "description": "Connector-synced data warehouse sources referenced by this query, if any.",
+ "items": {
+ "$ref": "#/definitions/DataWarehouseSourceUsage"
+ },
+ "type": "array"
+ },
+ "warnings": {
+ "description": "Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access.",
+ "items": {
+ "anyOf": [
+ {
+ "$ref": "#/definitions/DataWarehouseSyncWarning"
+ },
+ {
+ "$ref": "#/definitions/AccessControlFilterWarning"
+ }
+ ]
+ },
+ "type": "array"
+ }
+ },
+ "required": ["attributedConversions", "attributionWindowDays", "hasValue", "results", "totalConversions"],
+ "type": "object"
+ },
"MarketingAnalyticsAttributionQuery": {
"additionalProperties": false,
"properties": {
@@ -31687,6 +32058,10 @@
"description": "Drop direct sessions from the touchpoint set before weights are computed, so the remaining touchpoints renormalize to full credit rather than losing direct's share.",
"type": "boolean"
},
+ "excludeUnattributed": {
+ "description": "Drop touchpoints whose current breakdown value is empty or unknown — the \"(none)\" row — before weights are computed, so the remaining touchpoints renormalize to full credit.",
+ "type": "boolean"
+ },
"filterTestAccounts": {
"description": "Filter test accounts",
"type": "boolean"
@@ -34969,6 +35344,7 @@
"MarketingAnalyticsTableQuery",
"MarketingAnalyticsAggregatedQuery",
"MarketingAnalyticsAttributionQuery",
+ "MarketingAnalyticsAttributionPathsQuery",
"NonIntegratedConversionsTableQuery",
"ExperimentMetric",
"ExperimentQuery",
@@ -38975,6 +39351,102 @@
],
"type": "object"
},
+ {
+ "additionalProperties": false,
+ "properties": {
+ "attributedConversions": {
+ "$ref": "#/definitions/integer",
+ "description": "Conversions with at least one in-window touchpoint. The share denominator — deliberately unfiltered by min/maxTouchpoints so shares stay comparable across filter values."
+ },
+ "attributionWindowDays": {
+ "$ref": "#/definitions/integer",
+ "description": "The attribution window actually used, for the tooltips."
+ },
+ "error": {
+ "description": "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise.",
+ "type": "string"
+ },
+ "hasMore": {
+ "type": "boolean"
+ },
+ "hasValue": {
+ "description": "Whether the goal is revenue-bearing, which gates the value column.",
+ "type": "boolean"
+ },
+ "hogql": {
+ "description": "Generated HogQL query.",
+ "type": "string"
+ },
+ "limit": {
+ "$ref": "#/definitions/integer"
+ },
+ "modifiers": {
+ "$ref": "#/definitions/HogQLQueryModifiers",
+ "description": "Modifiers used when performing the query"
+ },
+ "offset": {
+ "$ref": "#/definitions/integer"
+ },
+ "query_status": {
+ "$ref": "#/definitions/QueryStatus",
+ "description": "Query status indicates whether next to the provided data, a query is still running."
+ },
+ "resolved_compare_date_range": {
+ "$ref": "#/definitions/ResolvedDateRangeResponse",
+ "description": "The resolved previous/comparison period date range, when comparing against another period"
+ },
+ "resolved_date_range": {
+ "$ref": "#/definitions/ResolvedDateRangeResponse",
+ "description": "The date range used for the query"
+ },
+ "results": {
+ "items": {
+ "$ref": "#/definitions/MarketingAnalyticsAttributionPathRow"
+ },
+ "type": "array"
+ },
+ "timings": {
+ "description": "Measured timings for different parts of the query generation process",
+ "items": {
+ "$ref": "#/definitions/QueryTiming"
+ },
+ "type": "array"
+ },
+ "totalConversions": {
+ "$ref": "#/definitions/integer",
+ "description": "All conversions in range, before the touchpoint-count filter."
+ },
+ "used_data_warehouse_sources": {
+ "description": "Connector-synced data warehouse sources referenced by this query, if any.",
+ "items": {
+ "$ref": "#/definitions/DataWarehouseSourceUsage"
+ },
+ "type": "array"
+ },
+ "warnings": {
+ "description": "Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access.",
+ "items": {
+ "anyOf": [
+ {
+ "$ref": "#/definitions/DataWarehouseSyncWarning"
+ },
+ {
+ "$ref": "#/definitions/AccessControlFilterWarning"
+ }
+ ]
+ },
+ "type": "array"
+ }
+ },
+ "required": [
+ "attributedConversions",
+ "attributionWindowDays",
+ "hasValue",
+ "results",
+ "totalConversions"
+ ],
+ "type": "object"
+ },
{
"additionalProperties": false,
"properties": {
@@ -44220,6 +44692,9 @@
{
"$ref": "#/definitions/MarketingAnalyticsAttributionQuery"
},
+ {
+ "$ref": "#/definitions/MarketingAnalyticsAttributionPathsQuery"
+ },
{
"$ref": "#/definitions/NonIntegratedConversionsTableQuery"
},
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 590d0da9d8c4..f3b8fa1a223f 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -151,6 +151,7 @@ export enum NodeKind {
MarketingAnalyticsTableQuery = 'MarketingAnalyticsTableQuery',
MarketingAnalyticsAggregatedQuery = 'MarketingAnalyticsAggregatedQuery',
MarketingAnalyticsAttributionQuery = 'MarketingAnalyticsAttributionQuery',
+ MarketingAnalyticsAttributionPathsQuery = 'MarketingAnalyticsAttributionPathsQuery',
NonIntegratedConversionsTableQuery = 'NonIntegratedConversionsTableQuery',
// Experiment queries
@@ -229,6 +230,7 @@ export type AnyDataNode =
| MarketingAnalyticsTableQuery
| MarketingAnalyticsAggregatedQuery
| MarketingAnalyticsAttributionQuery
+ | MarketingAnalyticsAttributionPathsQuery
| NonIntegratedConversionsTableQuery
| WebOverviewQuery
| WebStatsTableQuery
@@ -334,6 +336,7 @@ export type QuerySchema =
| MarketingAnalyticsTableQuery
| MarketingAnalyticsAggregatedQuery
| MarketingAnalyticsAttributionQuery
+ | MarketingAnalyticsAttributionPathsQuery
| NonIntegratedConversionsTableQuery
// Interface nodes
@@ -6421,6 +6424,11 @@ export interface MarketingAnalyticsAttributionQuery extends Omit<
* touchpoints renormalize to full credit rather than losing direct's share.
*/
excludeDirectTraffic?: boolean
+ /**
+ * Drop touchpoints whose current breakdown value is empty or unknown — the "(none)" row — before
+ * weights are computed, so the remaining touchpoints renormalize to full credit.
+ */
+ excludeUnattributed?: boolean
/**
* How many days before each conversion a touchpoint can earn credit, overriding the team's
* configured attribution window for this query only.
@@ -6494,6 +6502,75 @@ export interface MarketingAnalyticsAttributionQueryResponse extends AnalyticsQue
export type CachedMarketingAnalyticsAttributionQueryResponse =
CachedQueryResponse<MarketingAnalyticsAttributionQueryResponse>
+export interface MarketingAnalyticsAttributionPathsQuery extends Omit<
+ WebAnalyticsQueryBase<MarketingAnalyticsAttributionPathsQueryResponse>,
+ 'orderBy' | 'compareFilter'
+> {
+ kind: NodeKind.MarketingAnalyticsAttributionPathsQuery
+ /** Path step dimension. Defaults to channel. */
+ breakdownBy?: MarketingAnalyticsAttributionBreakdown
+ /** conversion_goal_id of the goal whose conversions the paths lead to. */
+ conversionGoalId: string
+ /** Drop direct sessions from every path, mirroring the attribution table's option. */
+ excludeDirectTraffic?: boolean
+ /** Drop touchpoints whose breakdown value is empty or unknown — the "(none)" steps. */
+ excludeUnattributed?: boolean
+ /**
+ * How many days before each conversion a touchpoint can be part of its path, overriding the
+ * team's configured attribution window for this query only.
+ */
+ lookbackWindowDays?: integer
+ /** Whether one person converting repeatedly contributes one path or one per conversion. Null follows the goal's math. */
+ allowMultipleConversionsPerVisitor?: boolean
+ /** Only paths with at least this many touchpoints, counted before truncation. */
+ minTouchpoints?: integer
+ /** Only paths with at most this many touchpoints, counted before truncation. */
+ maxTouchpoints?: integer
+ /** Number of rows to return */
+ limit?: integer
+ /** Number of rows to skip before returning rows */
+ offset?: integer
+ /** Filter test accounts */
+ filterTestAccounts?: boolean
+}
+
+export interface MarketingAnalyticsAttributionPathRow {
+ /**
+ * Breakdown values in touch order, oldest first. Consecutive repeats are preserved — collapsing
+ * them to "×N" is a display concern. Truncated to the most recent steps when the journey is
+ * longer than the grouping cap.
+ */
+ path: string[]
+ /** Conversions whose in-window touchpoints form exactly this path. */
+ conversions: integer
+ /** Null unless the goal is revenue-bearing. */
+ conversionValue: number | null
+ /** True when at least one grouped conversion had more touchpoints than the path shows. */
+ pathTruncated: boolean
+}
+
+export interface MarketingAnalyticsAttributionPathsQueryResponse extends AnalyticsQueryResponseBase {
+ results: MarketingAnalyticsAttributionPathRow[]
+ /** All conversions in range, before the touchpoint-count filter. */
+ totalConversions: integer
+ /**
+ * Conversions with at least one in-window touchpoint. The share denominator — deliberately
+ * unfiltered by min/maxTouchpoints so shares stay comparable across filter values.
+ */
+ attributedConversions: integer
+ /** The attribution window actually used, for the tooltips. */
+ attributionWindowDays: integer
+ /** Whether the goal is revenue-bearing, which gates the value column. */
+ hasValue: boolean
+ hogql?: string
+ hasMore?: boolean
+ limit?: integer
+ offset?: integer
+}
+
+export type CachedMarketingAnalyticsAttributionPathsQueryResponse =
+ CachedQueryResponse<MarketingAnalyticsAttributionPathsQueryResponse>
+
/** Columns for non-integrated conversions table */
export enum NonIntegratedConversionsColumnsSchemaNames {
Source = 'Source',
diff --git a/frontend/src/scenes/saved-insights/insightTypesMetadata.tsx b/frontend/src/scenes/saved-insights/insightTypesMetadata.tsx
index e2338eec22fb..6625214d8245 100644
--- a/frontend/src/scenes/saved-insights/insightTypesMetadata.tsx
+++ b/frontend/src/scenes/saved-insights/insightTypesMetadata.tsx
@@ -513,6 +513,11 @@ export const QUERY_TYPES_METADATA: Record<NodeKind, InsightTypeMetadata> = {
icon: IconHogQL,
inMenu: false,
},
+ [NodeKind.MarketingAnalyticsAttributionPathsQuery]: {
+ name: 'Marketing Analytics Attribution Paths',
+ icon: IconHogQL,
+ inMenu: false,
+ },
[NodeKind.NonIntegratedConversionsTableQuery]: {
name: 'Non-Integrated Conversions Table',
icon: IconHogQL,
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/AttributionTab.tsx b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/AttributionTab.tsx
index e354c8d5e454..8d5bde7cefa4 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/AttributionTab.tsx
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/AttributionTab.tsx
@@ -1,4 +1,4 @@
-import { useActions, useValues } from 'kea'
+import { BindLogic, useActions, useValues } from 'kea'
import { IconGear } from '@posthog/icons'
import { LemonBanner, LemonButton, LemonDivider, LemonSelect, LemonSwitch, Popover } from '@posthog/lemon-ui'
@@ -7,12 +7,20 @@ import { DateFilter } from 'lib/components/DateFilter/DateFilter'
import { FilterBar } from 'lib/components/FilterBar'
import { urls } from 'scenes/urls'
+import { dataNodeCollectionLogic } from '~/queries/nodes/DataNode/dataNodeCollectionLogic'
+import { ReloadAll } from '~/queries/nodes/DataNode/Reload'
import { MarketingAnalyticsAttributionBreakdown } from '~/queries/schema/schema-general'
import { marketingAnalyticsLogic } from '../../logic/marketingAnalyticsLogic'
import { marketingAnalyticsSettingsLogic } from '../../logic/marketingAnalyticsSettingsLogic'
-import { BREAKDOWN_LABELS, marketingAttributionLogic } from '../../logic/marketingAttributionLogic'
+import {
+ BREAKDOWN_LABELS,
+ MARKETING_ANALYTICS_ATTRIBUTION_COLLECTION_ID,
+ marketingAttributionLogic,
+ unattributedTooltip,
+} from '../../logic/marketingAttributionLogic'
import { AttributionTable } from './AttributionTable'
+import { ConversionPaths } from './ConversionPaths'
// Offered but disabled: they exist on the Dashboard's drill-down, so dropping them silently reads as
// a bug, but events carry no ad identifier for any model to credit.
@@ -30,9 +38,11 @@ export function AttributionTab(): JSX.Element {
const {
breakdownBy,
excludeDirectTraffic,
+ excludeUnattributed,
attributableGoals,
selectedGoalId,
query,
+ pathsQuery,
attribution_window_days,
effectiveLookbackDays,
effectiveAllowMultipleConversions,
@@ -42,6 +52,7 @@ export function AttributionTab(): JSX.Element {
setBreakdownBy,
setConversionGoalId,
setExcludeDirectTraffic,
+ setExcludeUnattributed,
setLookbackWindowDays,
setAllowMultipleConversionsPerVisitor,
setOptionsOpen,
@@ -103,6 +114,14 @@ export function AttributionTab(): JSX.Element {
tooltip="Direct sessions stop counting as touchpoints, and the credit they would have taken is shared across the remaining ones."
data-attr="marketing-attribution-exclude-direct"
/>
+ <LemonSwitch
+ fullWidth
+ checked={excludeUnattributed}
+ onChange={setExcludeUnattributed}
+ label="Exclude unattributed traffic"
+ tooltip={unattributedTooltip(breakdownBy)}
+ data-attr="marketing-attribution-exclude-unattributed"
+ />
<LemonSwitch
fullWidth
checked={effectiveAllowMultipleConversions}
@@ -115,66 +134,74 @@ export function AttributionTab(): JSX.Element {
)
return (
- <div className="flex flex-col">
- <FilterBar
- showBorderBottom
- left={
- <div className="flex flex-wrap items-center gap-4">
- <div className="flex items-center gap-2">
- <span className="text-secondary">Conversion goal</span>
- <LemonSelect
- size="small"
- value={selectedGoalId}
- onChange={(value) => value && setConversionGoalId(value)}
- options={attributableGoals.map((goal) => ({
- value: goal.conversion_goal_id,
- label: goal.conversion_goal_name,
- }))}
- />
+ // Rebinds the collection inside the tab, shadowing the scene-level binding on purpose: the
+ // refresh button reloads the attribution queries, not the dashboard tiles.
+ <BindLogic logic={dataNodeCollectionLogic} props={{ key: MARKETING_ANALYTICS_ATTRIBUTION_COLLECTION_ID }}>
+ <div className="flex flex-col">
+ <FilterBar
+ showBorderBottom
+ left={
+ <div className="flex flex-wrap items-center gap-4">
+ <div className="flex items-center gap-2">
+ <span className="text-secondary">Conversion goal</span>
+ <LemonSelect
+ size="small"
+ value={selectedGoalId}
+ onChange={(value) => value && setConversionGoalId(value)}
+ options={attributableGoals.map((goal) => ({
+ value: goal.conversion_goal_id,
+ label: goal.conversion_goal_name,
+ }))}
+ />
+ </div>
+ <div className="flex items-center gap-2">
+ <span className="text-secondary">Break down by</span>
+ <LemonSelect
+ size="small"
+ value={breakdownBy}
+ onChange={(value) => value && setBreakdownBy(value)}
+ options={[
+ ...Object.values(MarketingAnalyticsAttributionBreakdown).map((level) => ({
+ value: level,
+ label: BREAKDOWN_LABELS[level],
+ })),
+ ...UNATTRIBUTABLE_LEVELS.map((level) => ({
+ value: level.value as MarketingAnalyticsAttributionBreakdown,
+ label: level.label,
+ disabledReason: UNATTRIBUTABLE_REASON,
+ })),
+ ]}
+ />
+ </div>
</div>
+ }
+ right={
<div className="flex items-center gap-2">
- <span className="text-secondary">Break down by</span>
- <LemonSelect
- size="small"
- value={breakdownBy}
- onChange={(value) => value && setBreakdownBy(value)}
- options={[
- ...Object.values(MarketingAnalyticsAttributionBreakdown).map((level) => ({
- value: level,
- label: BREAKDOWN_LABELS[level],
- })),
- ...UNATTRIBUTABLE_LEVELS.map((level) => ({
- value: level.value as MarketingAnalyticsAttributionBreakdown,
- label: level.label,
- disabledReason: UNATTRIBUTABLE_REASON,
- })),
- ]}
- />
+ <ReloadAll iconOnly />
+ <Popover
+ visible={optionsOpen}
+ onClickOutside={() => setOptionsOpen(false)}
+ placement="bottom-end"
+ overlay={optionsContent}
+ >
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconGear />}
+ onClick={() => setOptionsOpen(!optionsOpen)}
+ data-attr="marketing-attribution-options"
+ >
+ Options
+ </LemonButton>
+ </Popover>
</div>
- </div>
- }
- right={
- <Popover
- visible={optionsOpen}
- onClickOutside={() => setOptionsOpen(false)}
- placement="bottom-end"
- overlay={optionsContent}
- >
- <LemonButton
- type="secondary"
- size="small"
- icon={<IconGear />}
- onClick={() => setOptionsOpen(!optionsOpen)}
- data-attr="marketing-attribution-options"
- >
- Options
- </LemonButton>
- </Popover>
- }
- />
- <div className="mt-4 flex flex-col gap-4 pb-8">
- {query && <AttributionTable query={query} attachTo={marketingAnalyticsLogic} />}
+ }
+ />
+ <div className="mt-4 flex flex-col gap-4 pb-8">
+ {query && <AttributionTable query={query} attachTo={marketingAnalyticsLogic} />}
+ {pathsQuery && <ConversionPaths query={pathsQuery} attachTo={marketingAnalyticsLogic} />}
+ </div>
</div>
- </div>
+ </BindLogic>
)
}
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/AttributionTable.tsx b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/AttributionTable.tsx
index 91cfde9e5114..bd0c44b986bd 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/AttributionTable.tsx
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/AttributionTable.tsx
@@ -23,6 +23,7 @@ import {
import {
ATTRIBUTION_ROW_LIMIT,
BREAKDOWN_LABELS,
+ MARKETING_ANALYTICS_ATTRIBUTION_COLLECTION_ID,
MODEL_LABELS,
marketingAttributionLogic,
} from '../../logic/marketingAttributionLogic'
@@ -56,7 +57,8 @@ export function AttributionTable({
attachTo?: LogicWrapper | BuiltLogic
}): JSX.Element {
const [key] = useState(() => `MarketingAttribution.${uniqueNode++}`)
- const logic = dataNodeLogic({ query, key, dataNodeCollectionId: key })
+ // Registered under the tab's shared collection so the filter bar's ReloadAll reaches this query.
+ const logic = dataNodeLogic({ query, key, dataNodeCollectionId: MARKETING_ANALYTICS_ATTRIBUTION_COLLECTION_ID })
const { response, responseLoading, responseError } = useValues(logic)
const { loadData } = useActions(logic)
const { breakdownBy, effectiveLookbackDays } = useValues(marketingAttributionLogic)
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/ConversionPathChips.test.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/ConversionPathChips.test.ts
new file mode 100644
index 000000000000..466d9daebda5
--- /dev/null
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/ConversionPathChips.test.ts
@@ -0,0 +1,34 @@
+import { collapseConsecutive } from './ConversionPathChips'
+
+describe('collapseConsecutive', () => {
+ it('returns an empty list for an empty path', () => {
+ expect(collapseConsecutive([])).toEqual([])
+ })
+
+ it('keeps distinct steps as-is', () => {
+ expect(collapseConsecutive(['google', 'newsletter', 'direct'])).toEqual([
+ { value: 'google', count: 1 },
+ { value: 'newsletter', count: 1 },
+ { value: 'direct', count: 1 },
+ ])
+ })
+
+ it('collapses consecutive repeats into a count', () => {
+ expect(collapseConsecutive(['google', 'google', 'google'])).toEqual([{ value: 'google', count: 3 }])
+ })
+
+ it('only collapses adjacent repeats, not the same value elsewhere in the journey', () => {
+ expect(collapseConsecutive(['google', 'google', 'direct', 'google'])).toEqual([
+ { value: 'google', count: 2 },
+ { value: 'direct', count: 1 },
+ { value: 'google', count: 1 },
+ ])
+ })
+
+ it('collapses empty-string steps too, since "(none)" journeys repeat like any other', () => {
+ expect(collapseConsecutive(['', '', 'google'])).toEqual([
+ { value: '', count: 2 },
+ { value: 'google', count: 1 },
+ ])
+ })
+})
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/ConversionPathChips.tsx b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/ConversionPathChips.tsx
new file mode 100644
index 000000000000..c29d149bd033
--- /dev/null
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/ConversionPathChips.tsx
@@ -0,0 +1,69 @@
+import './ConversionPaths.scss'
+
+import clsx from 'clsx'
+
+import { Tooltip } from '@posthog/lemon-ui'
+
+/**
+ * Collapse consecutive repeats for display: ['google', 'google', 'direct'] becomes google ×2 → direct.
+ * The backend deliberately returns the raw sequence — two google visits are a different journey than
+ * one — so the ×N is purely how that journey reads on screen.
+ */
+export function collapseConsecutive(path: string[]): { value: string; count: number }[] {
+ const collapsed: { value: string; count: number }[] = []
+ for (const value of path) {
+ const last = collapsed[collapsed.length - 1]
+ if (last && last.value === value) {
+ last.count += 1
+ } else {
+ collapsed.push({ value, count: 1 })
+ }
+ }
+ return collapsed
+}
+
+export function ConversionPathChips({
+ path,
+ truncated,
+ colorFor,
+}: {
+ path: string[]
+ truncated: boolean
+ /** Deterministic color per breakdown value, so "google" reads as the same hue on every row. */
+ colorFor: (value: string) => string
+}): JSX.Element {
+ const steps = collapseConsecutive(path)
+
+ return (
+ <ol className="ConversionPaths__path">
+ {truncated && (
+ <Tooltip title="This journey started earlier — showing its most recent touchpoints.">
+ <li className="ConversionPaths__chip ConversionPaths__chip--overflow">…</li>
+ </Tooltip>
+ )}
+ {steps.map((step, index) => {
+ const first = index === 0 && !truncated
+ const last = index === steps.length - 1
+ return (
+ <li
+ key={index}
+ className={clsx('ConversionPaths__chip', {
+ 'ConversionPaths__chip--first': first && !last,
+ 'ConversionPaths__chip--last': last && !first,
+ 'ConversionPaths__chip--only': first && last,
+ })}
+ // eslint-disable-next-line react/forbid-dom-props
+ style={
+ {
+ '--path-chip-color': colorFor(step.value),
+ } as React.CSSProperties
+ }
+ >
+ {step.value || <span className="text-secondary">(none)</span>}
+ {step.count > 1 && <span className="ConversionPaths__chip-count">×{step.count}</span>}
+ </li>
+ )
+ })}
+ </ol>
+ )
+}
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/ConversionPaths.scss b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/ConversionPaths.scss
new file mode 100644
index 000000000000..ee2d6b8981c6
--- /dev/null
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/ConversionPaths.scss
@@ -0,0 +1,78 @@
+.ConversionPaths {
+ // Chevron chips reading left to right as a journey. Each chip carries its breakdown value's color
+ // in --path-chip-color; mixed against the surface rather than used raw so the label keeps its
+ // normal text color and contrast survives dark mode — same technique as the attribution table's
+ // magnitude bars.
+ &__path {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ padding: 0;
+ margin: 0;
+ list-style: none;
+ }
+
+ &__chip {
+ padding: 2px 16px 2px 18px;
+
+ // The pointed right edge and notched left edge that make consecutive chips read as a sequence.
+ clip-path: polygon(0 0, calc(100% - 9px) 0, 100% 50%, calc(100% - 9px) 100%, 0 100%, 9px 50%);
+ font-weight: 500;
+ white-space: nowrap;
+ background-color: color-mix(
+ in sRGB,
+ var(--path-chip-color, var(--color-border-primary)) 30%,
+ var(--color-bg-surface-primary)
+ );
+
+ // Overlap so each chevron's point tucks into the next chip's notch.
+ &:not(:first-child) {
+ margin-left: -6px;
+ }
+ }
+
+ // Journey ends are squared off (with a soft radius) instead of notched/pointed.
+ &__chip--first {
+ padding-left: 12px;
+ clip-path: polygon(0 0, calc(100% - 9px) 0, 100% 50%, calc(100% - 9px) 100%, 0 100%);
+ border-radius: 4px 0 0 4px;
+ }
+
+ &__chip--last {
+ padding-right: 12px;
+ clip-path: polygon(0 0, 100% 0, 100% 100%, 0 100%, 9px 50%);
+ border-radius: 0 4px 4px 0;
+ }
+
+ &__chip--only {
+ padding: 2px 12px;
+ clip-path: none;
+ border-radius: 4px;
+ }
+
+ // The "journey started earlier" marker: neutral, since it stands for unknown touchpoints.
+ &__chip--overflow {
+ padding-left: 12px;
+ clip-path: polygon(0 0, calc(100% - 9px) 0, 100% 50%, calc(100% - 9px) 100%, 0 100%);
+ color: var(--color-text-secondary);
+ border-radius: 4px 0 0 4px;
+ }
+
+ &__chip-count {
+ margin-left: 6px;
+ font-size: 0.6875rem;
+ font-weight: 600;
+ color: var(--color-text-secondary);
+ }
+
+ // Same magnitude-bar affordance as the attribution table, for the same reason: painted as the
+ // cell's own background so it can't cover the collapsed borders.
+ td.ConversionPaths__magnitude-cell {
+ background-image: linear-gradient(
+ to right,
+ color-mix(in sRGB, var(--color-bg-fill-info-secondary) 50%, transparent) var(--conversion-paths-fill, 0%),
+ transparent var(--conversion-paths-fill, 0%)
+ );
+ background-clip: padding-box;
+ }
+}
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/ConversionPaths.tsx b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/ConversionPaths.tsx
new file mode 100644
index 000000000000..ba2aeb8ff060
--- /dev/null
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/ConversionPaths.tsx
@@ -0,0 +1,214 @@
+import './ConversionPaths.scss'
+
+import { BuiltLogic, LogicWrapper, useActions, useValues } from 'kea'
+import { useMemo, useState } from 'react'
+
+import { LemonSegmentedButton, LemonTable, LemonTableColumns } from '@posthog/lemon-ui'
+
+import { getSeriesColor } from 'lib/colors'
+import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'
+import { formatCurrency } from 'lib/utils/currency'
+import { humanFriendlyNumber, percentage } from 'lib/utils/numbers'
+import { InsightErrorState } from 'scenes/insights/EmptyStates'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
+import {
+ MarketingAnalyticsAttributionPathRow,
+ MarketingAnalyticsAttributionPathsQuery,
+ MarketingAnalyticsAttributionPathsQueryResponse,
+} from '~/queries/schema/schema-general'
+
+import {
+ BREAKDOWN_LABELS,
+ MARKETING_ANALYTICS_ATTRIBUTION_COLLECTION_ID,
+ PATHS_ROW_LIMIT,
+ PathTouchpointFilter,
+ marketingAttributionLogic,
+} from '../../logic/marketingAttributionLogic'
+import { ConversionPathChips } from './ConversionPathChips'
+
+// The segmented control offers exact lengths up to this, then an open-ended "N+" bucket.
+const MAX_EXACT_TOUCHPOINTS = 3
+
+// LemonSegmentedButton values must be React.Keys, so "any" stands in for the filter's null.
+const TOUCHPOINT_OPTIONS: {
+ value: number | 'any' | 'four_plus'
+ label: string
+ tooltip?: string
+}[] = [
+ { value: 'any', label: 'Any' },
+ ...Array.from({ length: MAX_EXACT_TOUCHPOINTS }, (_, i) => ({
+ value: i + 1,
+ label: `${i + 1}`,
+ tooltip: `Only journeys with exactly ${i + 1} touchpoint${i ? 's' : ''}`,
+ })),
+ {
+ value: 'four_plus' as const,
+ label: '4+',
+ tooltip: 'Only journeys with four or more touchpoints',
+ },
+]
+
+let uniqueNode = 0
+
+export function ConversionPaths({
+ query,
+ attachTo,
+}: {
+ query: MarketingAnalyticsAttributionPathsQuery
+ attachTo?: LogicWrapper | BuiltLogic
+}): JSX.Element {
+ const [key] = useState(() => `MarketingAttributionPaths.${uniqueNode++}`)
+ // Registered under the tab's shared collection so the filter bar's ReloadAll reaches this query.
+ const logic = dataNodeLogic({
+ query,
+ key,
+ dataNodeCollectionId: MARKETING_ANALYTICS_ATTRIBUTION_COLLECTION_ID,
+ })
+ const { response, responseLoading, responseError } = useValues(logic)
+ const { loadData } = useActions(logic)
+ const { breakdownBy, pathTouchpointFilter } = useValues(marketingAttributionLogic)
+ const { setPathTouchpointFilter } = useActions(marketingAttributionLogic)
+ const { baseCurrency } = useValues(teamLogic)
+ useAttachedLogic(logic, attachTo)
+
+ const pathsResponse = response as MarketingAnalyticsAttributionPathsQueryResponse | undefined
+ const rows = pathsResponse?.results ?? []
+ const hasValue = pathsResponse?.hasValue ?? false
+ const attributedConversions = pathsResponse?.attributedConversions ?? 0
+ const dimensionLabel = BREAKDOWN_LABELS[breakdownBy]
+
+ // One color per breakdown value, ranked by how many conversions the value participates in, so the
+ // most prominent value on screen takes the first series color and every row paints "google" alike.
+ const colorFor = useMemo(() => {
+ const totals = new Map<string, number>()
+ for (const row of rows) {
+ for (const step of row.path) {
+ totals.set(step, (totals.get(step) ?? 0) + row.conversions)
+ }
+ }
+ const ranked = [...totals.entries()].sort((a, b) => b[1] - a[1]).map(([value]) => value)
+ const colors = new Map(ranked.map((value, rank) => [value, getSeriesColor(rank)]))
+ return (value: string): string => colors.get(value) ?? getSeriesColor(0)
+ }, [rows])
+
+ const maxConversions = Math.max(0, ...rows.map((row) => row.conversions))
+
+ const columns: LemonTableColumns<MarketingAnalyticsAttributionPathRow> = [
+ {
+ title: 'Path',
+ key: 'path',
+ render: (_, row) => (
+ <ConversionPathChips path={row.path} truncated={row.pathTruncated} colorFor={colorFor} />
+ ),
+ },
+ {
+ title: 'Conversions',
+ key: 'conversions',
+ align: 'right',
+ width: 140,
+ render: (_, row) => humanFriendlyNumber(row.conversions),
+ sorter: (a, b) => a.conversions - b.conversions,
+ className: 'ConversionPaths__magnitude-cell',
+ style: (_, row) =>
+ ({
+ '--conversion-paths-fill': `${
+ maxConversions > 0 ? Math.round((row.conversions / maxConversions) * 100) : 0
+ }%`,
+ }) as React.CSSProperties,
+ },
+ {
+ title: 'Share',
+ tooltip: `This path's share of every conversion that had at least one touchpoint, whatever its length — so shares stay comparable when the touchpoint filter changes.`,
+ key: 'share',
+ align: 'right',
+ width: 100,
+ render: (_, row) =>
+ attributedConversions > 0 ? (
+ percentage(row.conversions / attributedConversions, 1)
+ ) : (
+ <span className="text-secondary">-</span>
+ ),
+ sorter: (a, b) => a.conversions - b.conversions,
+ },
+ ...(hasValue
+ ? [
+ {
+ title: 'Value',
+ key: 'value',
+ align: 'right' as const,
+ width: 120,
+ render: (_: unknown, row: MarketingAnalyticsAttributionPathRow) =>
+ row.conversionValue === null ? (
+ <span className="text-secondary">-</span>
+ ) : (
+ formatCurrency(row.conversionValue, baseCurrency)
+ ),
+ sorter: (a: MarketingAnalyticsAttributionPathRow, b: MarketingAnalyticsAttributionPathRow) =>
+ (a.conversionValue ?? -1) - (b.conversionValue ?? -1),
+ },
+ ]
+ : []),
+ ]
+
+ const emptyState =
+ pathTouchpointFilter === null
+ ? `No conversions had any ${dimensionLabel.toLowerCase()} touchpoints in this date range.`
+ : pathTouchpointFilter === 'four_plus'
+ ? 'No conversion journeys had four or more touchpoints in this date range.'
+ : `No conversion journeys had exactly ${pathTouchpointFilter} touchpoint${
+ pathTouchpointFilter === 1 ? '' : 's'
+ } in this date range.`
+
+ return (
+ <div className="ConversionPaths flex flex-col gap-2 rounded border bg-surface-primary p-4">
+ <div className="flex flex-wrap items-start justify-between gap-2">
+ <div>
+ <h3 className="mb-0 text-base font-semibold">Conversion paths</h3>
+ <p className="mb-0 text-secondary">
+ The most common journeys through your {dimensionLabel.toLowerCase()} touchpoints, oldest touch
+ first, ranked by the conversions they ended in.
+ </p>
+ </div>
+ <div className="flex items-center gap-2">
+ <span className="text-secondary">Touchpoints</span>
+ <LemonSegmentedButton
+ size="small"
+ value={pathTouchpointFilter ?? 'any'}
+ onChange={(value) =>
+ setPathTouchpointFilter((value === 'any' ? null : value) as PathTouchpointFilter)
+ }
+ options={TOUCHPOINT_OPTIONS.map((option) => ({
+ ...option,
+ 'data-attr': `marketing-attribution-path-touchpoints-${option.value}`,
+ }))}
+ />
+ </div>
+ </div>
+ {responseError ? (
+ <InsightErrorState
+ query={query}
+ excludeDetail
+ title={responseError}
+ onRetry={() => loadData('force_blocking')}
+ />
+ ) : (
+ <LemonTable
+ columns={columns}
+ dataSource={rows}
+ loading={responseLoading}
+ rowKey={(row) => row.path.join('→')}
+ emptyState={emptyState}
+ footer={
+ pathsResponse?.hasMore ? (
+ <div className="px-2 py-2 text-secondary">
+ Showing the top {PATHS_ROW_LIMIT} paths by conversions.
+ </div>
+ ) : undefined
+ }
+ />
+ )}
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAttributionLogic.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAttributionLogic.ts
index 74dd944c9b62..98c253a01f09 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAttributionLogic.ts
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAttributionLogic.ts
@@ -4,6 +4,7 @@ import {
AttributionMode,
ConversionGoalFilter,
MarketingAnalyticsAttributionBreakdown,
+ MarketingAnalyticsAttributionPathsQuery,
MarketingAnalyticsAttributionQuery,
NodeKind,
} from '~/queries/schema/schema-general'
@@ -15,6 +16,18 @@ import { marketingAnalyticsSettingsLogic } from './marketingAnalyticsSettingsLog
/** Rows the table asks for. Sorting happens client side over this page, so it's also the sort scope. */
export const ATTRIBUTION_ROW_LIMIT = 100
+/** Fewer than the table's limit: paths are a long-tail distribution and row 51 is almost always a singleton. */
+export const PATHS_ROW_LIMIT = 50
+
+/**
+ * Both attribution queries register under this collection, so the tab's refresh button reloads exactly
+ * them — not the dashboard tiles living in the scene-level collection.
+ */
+export const MARKETING_ANALYTICS_ATTRIBUTION_COLLECTION_ID = 'marketing-analytics-attribution'
+
+/** The conversion paths length filter: an exact touchpoint count, "4 or more", or null for any. */
+export type PathTouchpointFilter = number | 'four_plus' | null
+
export const BREAKDOWN_LABELS: Record<MarketingAnalyticsAttributionBreakdown, string> = {
[MarketingAnalyticsAttributionBreakdown.Channel]: 'Channel',
[MarketingAnalyticsAttributionBreakdown.Source]: 'Source',
@@ -26,6 +39,35 @@ export const BREAKDOWN_LABELS: Record<MarketingAnalyticsAttributionBreakdown, st
[MarketingAnalyticsAttributionBreakdown.LandingPage]: 'Landing page',
}
+/**
+ * How the row that "Exclude unattributed traffic" removes is labelled — only where that label is
+ * knowable from here. Most breakdowns leave the value empty and render as "(none)"; channel and
+ * referring domain substitute a fixed sentinel instead.
+ *
+ * Source is deliberately absent. Its empty value is displayed via the organic source bucket, but that
+ * happens *before* source normalization, so a team that lists "organic" among an ad platform's custom
+ * UTM sources sees those touchpoints reported under the platform's name instead. The label therefore
+ * depends on team config the frontend doesn't have, and guessing it is what the previous copy did.
+ */
+const UNATTRIBUTED_ROW_LABELS: Partial<Record<MarketingAnalyticsAttributionBreakdown, string>> = {
+ [MarketingAnalyticsAttributionBreakdown.Channel]: '"Unknown"',
+ [MarketingAnalyticsAttributionBreakdown.ReferringDomain]: '"$direct"',
+ [MarketingAnalyticsAttributionBreakdown.Campaign]: '"(none)"',
+ [MarketingAnalyticsAttributionBreakdown.Medium]: '"(none)"',
+ [MarketingAnalyticsAttributionBreakdown.Content]: '"(none)"',
+ [MarketingAnalyticsAttributionBreakdown.Term]: '"(none)"',
+ [MarketingAnalyticsAttributionBreakdown.LandingPage]: '"(none)"',
+}
+
+/** Names the row that disappears when it's knowable, and stays quiet about it when it isn't. */
+export const unattributedTooltip = (breakdownBy: MarketingAnalyticsAttributionBreakdown): string => {
+ const label = UNATTRIBUTED_ROW_LABELS[breakdownBy]
+ const rowClause = label ? ` — the ones shown as ${label} —` : ''
+ return `Sessions with no ${BREAKDOWN_LABELS[
+ breakdownBy
+ ].toLowerCase()}${rowClause} stop counting as touchpoints, and their credit is shared across the remaining ones.`
+}
+
export const MODEL_LABELS: Record<AttributionMode, string> = {
[AttributionMode.FirstTouch]: 'First touch',
[AttributionMode.LastTouch]: 'Last touch',
@@ -56,8 +98,11 @@ export interface marketingAttributionLogicValues {
effectiveAllowMultipleConversions: boolean
effectiveLookbackDays: number
excludeDirectTraffic: boolean
+ excludeUnattributed: boolean
lookbackWindowDays: number | null
optionsOpen: boolean
+ pathTouchpointFilter: PathTouchpointFilter
+ pathsQuery: MarketingAnalyticsAttributionPathsQuery | null
query: MarketingAnalyticsAttributionQuery | null
selectedGoalId: string | null
}
@@ -76,12 +121,18 @@ export interface marketingAttributionLogicActions {
setExcludeDirectTraffic: (excludeDirectTraffic: boolean) => {
excludeDirectTraffic: boolean
}
+ setExcludeUnattributed: (excludeUnattributed: boolean) => {
+ excludeUnattributed: boolean
+ }
setLookbackWindowDays: (lookbackWindowDays: number | null) => {
lookbackWindowDays: number | null
}
setOptionsOpen: (optionsOpen: boolean) => {
optionsOpen: boolean
}
+ setPathTouchpointFilter: (pathTouchpointFilter: PathTouchpointFilter) => {
+ pathTouchpointFilter: PathTouchpointFilter
+ }
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -99,6 +150,7 @@ export interface marketingAttributionLogicMeta {
selectedGoalId: string | null,
breakdownBy: MarketingAnalyticsAttributionBreakdown,
excludeDirectTraffic: boolean,
+ excludeUnattributed: boolean,
lookbackWindowDays: number | null,
allowMultipleConversionsPerVisitor: boolean | null,
dateFilter: {
@@ -107,6 +159,10 @@ export interface marketingAttributionLogicMeta {
interval: IntervalType
}
) => MarketingAnalyticsAttributionQuery | null
+ pathsQuery: (
+ query: MarketingAnalyticsAttributionQuery | null,
+ pathTouchpointFilter: PathTouchpointFilter
+ ) => MarketingAnalyticsAttributionPathsQuery | null
}
}
@@ -133,7 +189,9 @@ export const marketingAttributionLogic = kea<marketingAttributionLogicType>([
setBreakdownBy: (breakdownBy: MarketingAnalyticsAttributionBreakdown) => ({ breakdownBy }),
setConversionGoalId: (conversionGoalId: string) => ({ conversionGoalId }),
setExcludeDirectTraffic: (excludeDirectTraffic: boolean) => ({ excludeDirectTraffic }),
+ setExcludeUnattributed: (excludeUnattributed: boolean) => ({ excludeUnattributed }),
setLookbackWindowDays: (lookbackWindowDays: number | null) => ({ lookbackWindowDays }),
+ setPathTouchpointFilter: (pathTouchpointFilter: PathTouchpointFilter) => ({ pathTouchpointFilter }),
setAllowMultipleConversionsPerVisitor: (allowMultipleConversionsPerVisitor: boolean) => ({
allowMultipleConversionsPerVisitor,
}),
@@ -152,6 +210,12 @@ export const marketingAttributionLogic = kea<marketingAttributionLogicType>([
false,
{ setExcludeDirectTraffic: (_, { excludeDirectTraffic }) => excludeDirectTraffic },
],
+ excludeUnattributed: [false, { setExcludeUnattributed: (_, { excludeUnattributed }) => excludeUnattributed }],
+ // null means "any number of touchpoints".
+ pathTouchpointFilter: [
+ null as PathTouchpointFilter,
+ { setPathTouchpointFilter: (_, { pathTouchpointFilter }) => pathTouchpointFilter },
+ ],
// null means "use the team's configured window", so a later settings change flows through.
lookbackWindowDays: [
null as number | null,
@@ -213,6 +277,7 @@ export const marketingAttributionLogic = kea<marketingAttributionLogicType>([
s.selectedGoalId,
s.breakdownBy,
s.excludeDirectTraffic,
+ s.excludeUnattributed,
s.lookbackWindowDays,
s.allowMultipleConversionsPerVisitor,
s.dateFilter,
@@ -221,6 +286,7 @@ export const marketingAttributionLogic = kea<marketingAttributionLogicType>([
selectedGoalId: string | null,
breakdownBy: MarketingAnalyticsAttributionBreakdown,
excludeDirectTraffic: boolean,
+ excludeUnattributed: boolean,
lookbackWindowDays: number | null,
allowMultipleConversionsPerVisitor: boolean | null,
dateFilter: DateFilter
@@ -234,6 +300,7 @@ export const marketingAttributionLogic = kea<marketingAttributionLogicType>([
breakdownBy,
conversionGoalId: selectedGoalId,
excludeDirectTraffic,
+ excludeUnattributed,
...(lookbackWindowDays ? { lookbackWindowDays } : {}),
// Omitted when null so the backend applies the goal's own math.
...(allowMultipleConversionsPerVisitor !== null ? { allowMultipleConversionsPerVisitor } : {}),
@@ -242,5 +309,37 @@ export const marketingAttributionLogic = kea<marketingAttributionLogicType>([
}
},
],
+ pathsQuery: [
+ (s) => [s.query, s.pathTouchpointFilter],
+ // Derived from the table's query so the two sections can never disagree on goal, breakdown,
+ // window or exclusions; only the kind, the length filter and the row limit differ.
+ (
+ query: MarketingAnalyticsAttributionQuery | null,
+ pathTouchpointFilter: PathTouchpointFilter
+ ): MarketingAnalyticsAttributionPathsQuery | null => {
+ if (!query) {
+ return null
+ }
+ return {
+ kind: NodeKind.MarketingAnalyticsAttributionPathsQuery,
+ dateRange: query.dateRange,
+ breakdownBy: query.breakdownBy,
+ conversionGoalId: query.conversionGoalId,
+ excludeDirectTraffic: query.excludeDirectTraffic,
+ excludeUnattributed: query.excludeUnattributed,
+ ...(query.lookbackWindowDays ? { lookbackWindowDays: query.lookbackWindowDays } : {}),
+ ...(query.allowMultipleConversionsPerVisitor !== undefined
+ ? { allowMultipleConversionsPerVisitor: query.allowMultipleConversionsPerVisitor }
+ : {}),
+ ...(pathTouchpointFilter === 'four_plus'
+ ? { minTouchpoints: 4 }
+ : pathTouchpointFilter !== null
+ ? { minTouchpoints: pathTouchpointFilter, maxTouchpoints: pathTouchpointFilter }
+ : {}),
+ limit: PATHS_ROW_LIMIT,
+ properties: [],
+ }
+ },
+ ],
}),
])
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/unattributedTooltip.test.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/unattributedTooltip.test.ts
new file mode 100644
index 000000000000..7312899d4574
--- /dev/null
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/unattributedTooltip.test.ts
@@ -0,0 +1,34 @@
+import { MarketingAnalyticsAttributionBreakdown } from '~/queries/schema/schema-general'
+
+import { unattributedTooltip } from './marketingAttributionLogic'
+
+describe('unattributedTooltip', () => {
+ it('names the sentinel row for channel', () => {
+ expect(unattributedTooltip(MarketingAnalyticsAttributionBreakdown.Channel)).toBe(
+ 'Sessions with no channel — the ones shown as "Unknown" — stop counting as touchpoints, and their credit is shared across the remaining ones.'
+ )
+ })
+
+ it('names the sentinel row for referring domain', () => {
+ expect(unattributedTooltip(MarketingAnalyticsAttributionBreakdown.ReferringDomain)).toContain(
+ 'the ones shown as "$direct"'
+ )
+ })
+
+ it('names the "(none)" row for the plain UTM breakdowns', () => {
+ expect(unattributedTooltip(MarketingAnalyticsAttributionBreakdown.Campaign)).toContain(
+ 'the ones shown as "(none)"'
+ )
+ })
+
+ it("names no row for source, whose label depends on the team's source normalization", () => {
+ // An empty utm_source is displayed via the organic bucket, but that substitution happens before
+ // source normalization runs — a team listing "organic" among an ad platform's custom UTM sources
+ // sees those touchpoints under the platform's name instead. Naming any row here would be a guess.
+ const tooltip = unattributedTooltip(MarketingAnalyticsAttributionBreakdown.Source)
+ expect(tooltip).toBe(
+ 'Sessions with no source stop counting as touchpoints, and their credit is shared across the remaining ones.'
+ )
+ expect(tooltip).not.toContain('shown as')
+ })
+})
diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.py
index a8a523be5cb2..cce41c3edffd 100644
--- a/posthog/clickhouse/query_tagging.py
+++ b/posthog/clickhouse/query_tagging.py
@@ -264,6 +264,7 @@ def kind_fallback_tags(kind: NodeKind) -> FallbackTags | None:
NodeKind.MARKETING_ANALYTICS_TABLE_QUERY
| NodeKind.MARKETING_ANALYTICS_AGGREGATED_QUERY
| NodeKind.MARKETING_ANALYTICS_ATTRIBUTION_QUERY
+ | NodeKind.MARKETING_ANALYTICS_ATTRIBUTION_PATHS_QUERY
| NodeKind.NON_INTEGRATED_CONVERSIONS_TABLE_QUERY
):
return {"product": Product.MARKETING_ANALYTICS}
diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.py
index e3cc2c2fd24c..032c58db1ef2 100644
--- a/posthog/hogql_queries/query_runner.py
+++ b/posthog/hogql_queries/query_runner.py
@@ -1178,6 +1178,20 @@ def get_query_runner(
user=user,
)
+ if kind == NodeKind.MARKETING_ANALYTICS_ATTRIBUTION_PATHS_QUERY:
+ from products.marketing_analytics.backend.hogql_queries.attribution_paths_query_runner import (
+ MarketingAnalyticsAttributionPathsQueryRunner,
+ )
+
+ return MarketingAnalyticsAttributionPathsQueryRunner(
+ query=query,
+ team=team,
+ timings=timings,
+ modifiers=modifiers,
+ limit_context=limit_context,
+ user=user,
+ )
+
if kind == NodeKind.NON_INTEGRATED_CONVERSIONS_TABLE_QUERY:
from products.marketing_analytics.backend.hogql_queries.non_integrated_conversions_table_query_runner import (
NonIntegratedConversionsTableQueryRunner,
diff --git a/posthog/schema.py b/posthog/schema.py
index 470edbff9092..b3328e696573 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -2295,7 +2295,7 @@ class QueryResponseAlternative7(BaseModel):
stdout: str | None = None
-class QueryResponseAlternative74(BaseModel):
+class QueryResponseAlternative75(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -5496,6 +5496,29 @@ class MCPToolTopUserItem(BaseModel):
)
+class MarketingAnalyticsAttributionPathRow(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ conversionValue: float | None = Field(..., description="Null unless the goal is revenue-bearing.")
+ conversions: int = Field(
+ ...,
+ description="Conversions whose in-window touchpoints form exactly this path.",
+ )
+ path: list[str] = Field(
+ ...,
+ description=(
+ "Breakdown values in touch order, oldest first. Consecutive repeats are"
+ ' preserved — collapsing them to "×N" is a display concern. Truncated to'
+ " the most recent steps when the journey is longer than the grouping cap."
+ ),
+ )
+ pathTruncated: bool = Field(
+ ...,
+ description=("True when at least one grouped conversion had more touchpoints than the path shows."),
+ )
+
+
class MarketingAnalyticsAttributionRow(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -5898,7 +5921,7 @@ class QueryResponseAlternative28(BaseModel):
status: ExternalQueryStatus
-class QueryResponseAlternative81(BaseModel):
+class QueryResponseAlternative82(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -11862,6 +11885,81 @@ class CachedMarketingAnalyticsAggregatedQueryResponse(BaseModel):
)
+class CachedMarketingAnalyticsAttributionPathsQueryResponse(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ attributedConversions: int = Field(
+ ...,
+ description=(
+ "Conversions with at least one in-window touchpoint. The share denominator"
+ " — deliberately unfiltered by min/maxTouchpoints so shares stay comparable"
+ " across filter values."
+ ),
+ )
+ attributionWindowDays: int = Field(..., description="The attribution window actually used, for the tooltips.")
+ cache_key: str
+ cache_target_age: AwareDatetime | None = None
+ calculation_trigger: str | None = Field(
+ default=None,
+ description=("What triggered the calculation of the query, leave empty if user/immediate"),
+ )
+ error: str | None = Field(
+ default=None,
+ description=(
+ "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise."
+ ),
+ )
+ hasMore: bool | None = None
+ hasValue: bool = Field(
+ ...,
+ description=("Whether the goal is revenue-bearing, which gates the value column."),
+ )
+ hogql: str | None = Field(default=None, description="Generated HogQL query.")
+ is_cached: bool
+ last_refresh: AwareDatetime
+ limit: int | None = None
+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
+ next_allowed_client_refresh: AwareDatetime
+ offset: int | None = None
+ query_metadata: dict[str, Any] | None = None
+ query_status: QueryStatus | None = Field(
+ default=None,
+ description=("Query status indicates whether next to the provided data, a query is still running."),
+ )
+ resolved_compare_date_range: ResolvedDateRangeResponse | None = Field(
+ default=None,
+ description=("The resolved previous/comparison period date range, when comparing against another period"),
+ )
+ resolved_date_range: ResolvedDateRangeResponse | None = Field(
+ default=None, description="The date range used for the query"
+ )
+ results: list[MarketingAnalyticsAttributionPathRow]
+ timezone: str
+ timings: list[QueryTiming] | None = Field(
+ default=None,
+ description=("Measured timings for different parts of the query generation process"),
+ )
+ totalConversions: int = Field(..., description="All conversions in range, before the touchpoint-count filter.")
+ used_data_warehouse_sources: list[DataWarehouseSourceUsage] | None = Field(
+ default=None,
+ description=("Connector-synced data warehouse sources referenced by this query, if any."),
+ )
+ warnings: list[DataWarehouseSyncWarning | AccessControlFilterWarning] | None = Field(
+ default=None,
+ description=(
+ "Warnings about data warehouse sources referenced by the query whose"
+ " latest sync failed, is paused, hit a billing limit, or is otherwise"
+ " stale. Results may not reflect current source data. Accumulated"
+ " across every HogQL execution that contributes to this response — so"
+ " insights backed by warehouse tables (Trends, Funnels, etc.) receive"
+ " the same warnings as raw HogQL queries. Also carries access control"
+ " warnings when a system-table query filters out objects the user can't"
+ " access."
+ ),
+ )
+
+
class CachedMarketingAnalyticsAttributionQueryResponse(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -17604,6 +17702,70 @@ class MarketingAnalyticsAggregatedQueryResponse(BaseModel):
)
+class MarketingAnalyticsAttributionPathsQueryResponse(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ attributedConversions: int = Field(
+ ...,
+ description=(
+ "Conversions with at least one in-window touchpoint. The share denominator"
+ " — deliberately unfiltered by min/maxTouchpoints so shares stay comparable"
+ " across filter values."
+ ),
+ )
+ attributionWindowDays: int = Field(..., description="The attribution window actually used, for the tooltips.")
+ error: str | None = Field(
+ default=None,
+ description=(
+ "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise."
+ ),
+ )
+ hasMore: bool | None = None
+ hasValue: bool = Field(
+ ...,
+ description=("Whether the goal is revenue-bearing, which gates the value column."),
+ )
+ hogql: str | None = Field(default=None, description="Generated HogQL query.")
+ limit: int | None = None
+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
+ offset: int | None = None
+ query_status: QueryStatus | None = Field(
+ default=None,
+ description=("Query status indicates whether next to the provided data, a query is still running."),
+ )
+ resolved_compare_date_range: ResolvedDateRangeResponse | None = Field(
+ default=None,
+ description=("The resolved previous/comparison period date range, when comparing against another period"),
+ )
+ resolved_date_range: ResolvedDateRangeResponse | None = Field(
+ default=None, description="The date range used for the query"
+ )
+ results: list[MarketingAnalyticsAttributionPathRow]
+ timings: list[QueryTiming] | None = Field(
+ default=None,
+ description=("Measured timings for different parts of the query generation process"),
+ )
+ totalConversions: int = Field(..., description="All conversions in range, before the touchpoint-count filter.")
+ used_data_warehouse_sources: list[DataWarehouseSourceUsage] | None = Field(
+ default=None,
+ description=("Connector-synced data warehouse sources referenced by this query, if any."),
+ )
+ warnings: list[DataWarehouseSyncWarning | AccessControlFilterWarning] | None = Field(
+ default=None,
+ description=(
+ "Warnings about data warehouse sources referenced by the query whose"
+ " latest sync failed, is paused, hit a billing limit, or is otherwise"
+ " stale. Results may not reflect current source data. Accumulated"
+ " across every HogQL execution that contributes to this response — so"
+ " insights backed by warehouse tables (Trends, Funnels, etc.) receive"
+ " the same warnings as raw HogQL queries. Also carries access control"
+ " warnings when a system-table query filters out objects the user can't"
+ " access."
+ ),
+ )
+
+
class MarketingAnalyticsAttributionQueryResponse(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -19270,6 +19432,70 @@ class QueryResponseAlternative32(BaseModel):
class QueryResponseAlternative33(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ attributedConversions: int = Field(
+ ...,
+ description=(
+ "Conversions with at least one in-window touchpoint. The share denominator"
+ " — deliberately unfiltered by min/maxTouchpoints so shares stay comparable"
+ " across filter values."
+ ),
+ )
+ attributionWindowDays: int = Field(..., description="The attribution window actually used, for the tooltips.")
+ error: str | None = Field(
+ default=None,
+ description=(
+ "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise."
+ ),
+ )
+ hasMore: bool | None = None
+ hasValue: bool = Field(
+ ...,
+ description=("Whether the goal is revenue-bearing, which gates the value column."),
+ )
+ hogql: str | None = Field(default=None, description="Generated HogQL query.")
+ limit: int | None = None
+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
+ offset: int | None = None
+ query_status: QueryStatus | None = Field(
+ default=None,
+ description=("Query status indicates whether next to the provided data, a query is still running."),
+ )
+ resolved_compare_date_range: ResolvedDateRangeResponse | None = Field(
+ default=None,
+ description=("The resolved previous/comparison period date range, when comparing against another period"),
+ )
+ resolved_date_range: ResolvedDateRangeResponse | None = Field(
+ default=None, description="The date range used for the query"
+ )
+ results: list[MarketingAnalyticsAttributionPathRow]
+ timings: list[QueryTiming] | None = Field(
+ default=None,
+ description=("Measured timings for different parts of the query generation process"),
+ )
+ totalConversions: int = Field(..., description="All conversions in range, before the touchpoint-count filter.")
+ used_data_warehouse_sources: list[DataWarehouseSourceUsage] | None = Field(
+ default=None,
+ description=("Connector-synced data warehouse sources referenced by this query, if any."),
+ )
+ warnings: list[DataWarehouseSyncWarning | AccessControlFilterWarning] | None = Field(
+ default=None,
+ description=(
+ "Warnings about data warehouse sources referenced by the query whose"
+ " latest sync failed, is paused, hit a billing limit, or is otherwise"
+ " stale. Results may not reflect current source data. Accumulated"
+ " across every HogQL execution that contributes to this response — so"
+ " insights backed by warehouse tables (Trends, Funnels, etc.) receive"
+ " the same warnings as raw HogQL queries. Also carries access control"
+ " warnings when a system-table query filters out objects the user can't"
+ " access."
+ ),
+ )
+
+
+class QueryResponseAlternative34(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -19322,7 +19548,7 @@ class QueryResponseAlternative33(BaseModel):
)
-class QueryResponseAlternative34(BaseModel):
+class QueryResponseAlternative35(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -19375,7 +19601,7 @@ class QueryResponseAlternative34(BaseModel):
)
-class QueryResponseAlternative35(BaseModel):
+class QueryResponseAlternative36(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -19428,7 +19654,7 @@ class QueryResponseAlternative35(BaseModel):
)
-class QueryResponseAlternative36(BaseModel):
+class QueryResponseAlternative37(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -19481,7 +19707,7 @@ class QueryResponseAlternative36(BaseModel):
)
-class QueryResponseAlternative37(BaseModel):
+class QueryResponseAlternative38(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -19534,7 +19760,7 @@ class QueryResponseAlternative37(BaseModel):
)
-class QueryResponseAlternative38(BaseModel):
+class QueryResponseAlternative39(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -19585,7 +19811,7 @@ class QueryResponseAlternative38(BaseModel):
)
-class QueryResponseAlternative39(BaseModel):
+class QueryResponseAlternative40(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -19646,7 +19872,7 @@ class QueryResponseAlternative39(BaseModel):
)
-class QueryResponseAlternative40(BaseModel):
+class QueryResponseAlternative41(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -19699,7 +19925,7 @@ class QueryResponseAlternative40(BaseModel):
)
-class QueryResponseAlternative41(BaseModel):
+class QueryResponseAlternative42(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -19751,7 +19977,7 @@ class QueryResponseAlternative41(BaseModel):
)
-class QueryResponseAlternative42(BaseModel):
+class QueryResponseAlternative43(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -19805,7 +20031,7 @@ class QueryResponseAlternative42(BaseModel):
)
-class QueryResponseAlternative43(BaseModel):
+class QueryResponseAlternative44(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -19853,7 +20079,7 @@ class QueryResponseAlternative43(BaseModel):
)
-class QueryResponseAlternative44(BaseModel):
+class QueryResponseAlternative45(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -19905,7 +20131,7 @@ class QueryResponseAlternative44(BaseModel):
)
-class QueryResponseAlternative45(BaseModel):
+class QueryResponseAlternative46(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -19957,7 +20183,7 @@ class QueryResponseAlternative45(BaseModel):
)
-class QueryResponseAlternative46(BaseModel):
+class QueryResponseAlternative47(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20010,7 +20236,7 @@ class QueryResponseAlternative46(BaseModel):
)
-class QueryResponseAlternative47(BaseModel):
+class QueryResponseAlternative48(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20058,7 +20284,7 @@ class QueryResponseAlternative47(BaseModel):
)
-class QueryResponseAlternative48(BaseModel):
+class QueryResponseAlternative49(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20111,7 +20337,7 @@ class QueryResponseAlternative48(BaseModel):
)
-class QueryResponseAlternative49(BaseModel):
+class QueryResponseAlternative50(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20162,7 +20388,7 @@ class QueryResponseAlternative49(BaseModel):
)
-class QueryResponseAlternative53(BaseModel):
+class QueryResponseAlternative54(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20213,7 +20439,7 @@ class QueryResponseAlternative53(BaseModel):
)
-class QueryResponseAlternative55(BaseModel):
+class QueryResponseAlternative56(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20265,7 +20491,7 @@ class QueryResponseAlternative55(BaseModel):
)
-class QueryResponseAlternative56(BaseModel):
+class QueryResponseAlternative57(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20322,7 +20548,7 @@ class QueryResponseAlternative56(BaseModel):
)
-class QueryResponseAlternative57(BaseModel):
+class QueryResponseAlternative58(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20371,7 +20597,7 @@ class QueryResponseAlternative57(BaseModel):
)
-class QueryResponseAlternative58(BaseModel):
+class QueryResponseAlternative59(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20425,7 +20651,7 @@ class QueryResponseAlternative58(BaseModel):
)
-class QueryResponseAlternative59(BaseModel):
+class QueryResponseAlternative60(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20472,7 +20698,7 @@ class QueryResponseAlternative59(BaseModel):
)
-class QueryResponseAlternative60(BaseModel):
+class QueryResponseAlternative61(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20519,7 +20745,7 @@ class QueryResponseAlternative60(BaseModel):
)
-class QueryResponseAlternative61(BaseModel):
+class QueryResponseAlternative62(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20566,7 +20792,7 @@ class QueryResponseAlternative61(BaseModel):
)
-class QueryResponseAlternative63(BaseModel):
+class QueryResponseAlternative64(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20618,7 +20844,7 @@ class QueryResponseAlternative63(BaseModel):
)
-class QueryResponseAlternative65(BaseModel):
+class QueryResponseAlternative66(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20670,7 +20896,7 @@ class QueryResponseAlternative65(BaseModel):
)
-class QueryResponseAlternative66(BaseModel):
+class QueryResponseAlternative67(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20722,7 +20948,7 @@ class QueryResponseAlternative66(BaseModel):
)
-class QueryResponseAlternative67(BaseModel):
+class QueryResponseAlternative68(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20770,7 +20996,7 @@ class QueryResponseAlternative67(BaseModel):
)
-class QueryResponseAlternative68(BaseModel):
+class QueryResponseAlternative69(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20817,7 +21043,7 @@ class QueryResponseAlternative68(BaseModel):
)
-class QueryResponseAlternative69(BaseModel):
+class QueryResponseAlternative70(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20864,7 +21090,7 @@ class QueryResponseAlternative69(BaseModel):
)
-class QueryResponseAlternative70(BaseModel):
+class QueryResponseAlternative71(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20915,7 +21141,7 @@ class QueryResponseAlternative70(BaseModel):
)
-class QueryResponseAlternative71(BaseModel):
+class QueryResponseAlternative72(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20966,7 +21192,7 @@ class QueryResponseAlternative71(BaseModel):
)
-class QueryResponseAlternative72(BaseModel):
+class QueryResponseAlternative73(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21017,7 +21243,7 @@ class QueryResponseAlternative72(BaseModel):
)
-class QueryResponseAlternative73(BaseModel):
+class QueryResponseAlternative74(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21068,7 +21294,7 @@ class QueryResponseAlternative73(BaseModel):
)
-class QueryResponseAlternative75(BaseModel):
+class QueryResponseAlternative76(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21118,7 +21344,7 @@ class QueryResponseAlternative75(BaseModel):
)
-class QueryResponseAlternative76(BaseModel):
+class QueryResponseAlternative77(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21168,7 +21394,7 @@ class QueryResponseAlternative76(BaseModel):
)
-class QueryResponseAlternative77(BaseModel):
+class QueryResponseAlternative78(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21215,7 +21441,7 @@ class QueryResponseAlternative77(BaseModel):
)
-class QueryResponseAlternative78(BaseModel):
+class QueryResponseAlternative79(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21266,7 +21492,7 @@ class QueryResponseAlternative78(BaseModel):
)
-class QueryResponseAlternative82(BaseModel):
+class QueryResponseAlternative83(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21313,7 +21539,7 @@ class QueryResponseAlternative82(BaseModel):
)
-class QueryResponseAlternative83(BaseModel):
+class QueryResponseAlternative84(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21360,7 +21586,7 @@ class QueryResponseAlternative83(BaseModel):
)
-class QueryResponseAlternative84(BaseModel):
+class QueryResponseAlternative85(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21417,7 +21643,7 @@ class QueryResponseAlternative84(BaseModel):
)
-class QueryResponseAlternative85(BaseModel):
+class QueryResponseAlternative86(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21464,7 +21690,7 @@ class QueryResponseAlternative85(BaseModel):
)
-class QueryResponseAlternative86(BaseModel):
+class QueryResponseAlternative87(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21516,7 +21742,7 @@ class QueryResponseAlternative86(BaseModel):
)
-class QueryResponseAlternative87(BaseModel):
+class QueryResponseAlternative88(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21563,7 +21789,7 @@ class QueryResponseAlternative87(BaseModel):
)
-class QueryResponseAlternative88(BaseModel):
+class QueryResponseAlternative89(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21610,7 +21836,7 @@ class QueryResponseAlternative88(BaseModel):
)
-class QueryResponseAlternative89(BaseModel):
+class QueryResponseAlternative90(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21657,7 +21883,7 @@ class QueryResponseAlternative89(BaseModel):
)
-class QueryResponseAlternative90(BaseModel):
+class QueryResponseAlternative91(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21704,7 +21930,7 @@ class QueryResponseAlternative90(BaseModel):
)
-class QueryResponseAlternative91(BaseModel):
+class QueryResponseAlternative92(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21751,7 +21977,7 @@ class QueryResponseAlternative91(BaseModel):
)
-class QueryResponseAlternative92(BaseModel):
+class QueryResponseAlternative93(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21798,7 +22024,7 @@ class QueryResponseAlternative92(BaseModel):
)
-class QueryResponseAlternative93(BaseModel):
+class QueryResponseAlternative94(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21845,7 +22071,7 @@ class QueryResponseAlternative93(BaseModel):
)
-class QueryResponseAlternative94(BaseModel):
+class QueryResponseAlternative95(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21895,7 +22121,7 @@ class QueryResponseAlternative94(BaseModel):
)
-class QueryResponseAlternative95(BaseModel):
+class QueryResponseAlternative96(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21942,7 +22168,7 @@ class QueryResponseAlternative95(BaseModel):
)
-class QueryResponseAlternative96(BaseModel):
+class QueryResponseAlternative97(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21989,7 +22215,7 @@ class QueryResponseAlternative96(BaseModel):
)
-class QueryResponseAlternative97(BaseModel):
+class QueryResponseAlternative98(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22036,7 +22262,7 @@ class QueryResponseAlternative97(BaseModel):
)
-class QueryResponseAlternative98(BaseModel):
+class QueryResponseAlternative99(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22083,7 +22309,7 @@ class QueryResponseAlternative98(BaseModel):
)
-class QueryResponseAlternative99(BaseModel):
+class QueryResponseAlternative100(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22130,7 +22356,7 @@ class QueryResponseAlternative99(BaseModel):
)
-class QueryResponseAlternative100(BaseModel):
+class QueryResponseAlternative101(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22177,7 +22403,7 @@ class QueryResponseAlternative100(BaseModel):
)
-class QueryResponseAlternative101(BaseModel):
+class QueryResponseAlternative102(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22224,7 +22450,7 @@ class QueryResponseAlternative101(BaseModel):
)
-class QueryResponseAlternative102(BaseModel):
+class QueryResponseAlternative103(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22271,7 +22497,7 @@ class QueryResponseAlternative102(BaseModel):
)
-class QueryResponseAlternative103(BaseModel):
+class QueryResponseAlternative104(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -24754,6 +24980,79 @@ class MarketingAnalyticsAggregatedQuery(BaseModel):
version: float | None = Field(default=None, description="version of the node, used for schema migrations")
+class MarketingAnalyticsAttributionPathsQuery(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"),
+ )
+ allowMultipleConversionsPerVisitor: bool | None = Field(
+ default=None,
+ description=(
+ "Whether one person converting repeatedly contributes one path or one per"
+ " conversion. Null follows the goal's math."
+ ),
+ )
+ breakdownBy: MarketingAnalyticsAttributionBreakdown | None = Field(
+ default=None, description="Path step dimension. Defaults to channel."
+ )
+ conversionGoal: ActionConversionGoal | CustomEventConversionGoal | None = None
+ conversionGoalId: str = Field(
+ ...,
+ description=("conversion_goal_id of the goal whose conversions the paths lead to."),
+ )
+ 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
+ excludeDirectTraffic: bool | None = Field(
+ default=None,
+ description=("Drop direct sessions from every path, mirroring the attribution table's option."),
+ )
+ excludeUnattributed: bool | None = Field(
+ default=None,
+ description=('Drop touchpoints whose breakdown value is empty or unknown — the "(none)" steps.'),
+ )
+ filterTestAccounts: bool | None = Field(default=None, description="Filter test accounts")
+ includeRevenue: bool | None = None
+ interval: IntervalType | None = Field(
+ default=None,
+ description=("Interval for date range calculation (affects date_to rounding for hour vs day ranges)"),
+ )
+ kind: Literal["MarketingAnalyticsAttributionPathsQuery"] = "MarketingAnalyticsAttributionPathsQuery"
+ limit: int | None = Field(default=None, description="Number of rows to return")
+ lookbackWindowDays: int | None = Field(
+ default=None,
+ description=(
+ "How many days before each conversion a touchpoint can be part of its path,"
+ " overriding the team's configured attribution window for this query only."
+ ),
+ )
+ maxTouchpoints: int | None = Field(
+ default=None,
+ description=("Only paths with at most this many touchpoints, counted before truncation."),
+ )
+ minTouchpoints: int | None = Field(
+ default=None,
+ description=("Only paths with at least this many touchpoints, counted before truncation."),
+ )
+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
+ offset: int | None = Field(default=None, description="Number of rows to skip before returning rows")
+ properties: list[EventPropertyFilter | PersonPropertyFilter | SessionPropertyFilter | CohortPropertyFilter]
+ response: MarketingAnalyticsAttributionPathsQueryResponse | 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 MarketingAnalyticsAttributionQuery(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -24796,6 +25095,14 @@ class MarketingAnalyticsAttributionQuery(BaseModel):
" losing direct's share."
),
)
+ excludeUnattributed: bool | None = Field(
+ default=None,
+ description=(
+ "Drop touchpoints whose current breakdown value is empty or unknown — the"
+ ' "(none)" row — before weights are computed, so the remaining touchpoints'
+ " renormalize to full credit."
+ ),
+ )
filterTestAccounts: bool | None = Field(default=None, description="Filter test accounts")
includeRevenue: bool | None = None
interval: IntervalType | None = Field(
@@ -26312,7 +26619,7 @@ class LifecycleQuery(BaseModel):
version: float | None = Field(default=None, description="version of the node, used for schema migrations")
-class QueryResponseAlternative64(BaseModel):
+class QueryResponseAlternative65(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -26907,7 +27214,7 @@ class QueryResponseAlternative17(BaseModel):
)
-class QueryResponseAlternative51(BaseModel):
+class QueryResponseAlternative52(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -26927,7 +27234,7 @@ class QueryResponseAlternative51(BaseModel):
)
-class QueryResponseAlternative52(BaseModel):
+class QueryResponseAlternative53(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -26984,8 +27291,8 @@ class QueryResponseAlternative(
| QueryResponseAlternative31
| QueryResponseAlternative32
| QueryResponseAlternative33
- | Any
| QueryResponseAlternative34
+ | Any
| QueryResponseAlternative35
| QueryResponseAlternative36
| QueryResponseAlternative37
@@ -27001,17 +27308,17 @@ class QueryResponseAlternative(
| QueryResponseAlternative47
| QueryResponseAlternative48
| QueryResponseAlternative49
- | QueryResponseAlternative51
+ | QueryResponseAlternative50
| QueryResponseAlternative52
| QueryResponseAlternative53
- | QueryResponseAlternative55
+ | QueryResponseAlternative54
| QueryResponseAlternative56
| QueryResponseAlternative57
| QueryResponseAlternative58
| QueryResponseAlternative59
| QueryResponseAlternative60
| QueryResponseAlternative61
- | QueryResponseAlternative63
+ | QueryResponseAlternative62
| QueryResponseAlternative64
| QueryResponseAlternative65
| QueryResponseAlternative66
@@ -27027,7 +27334,7 @@ class QueryResponseAlternative(
| QueryResponseAlternative76
| QueryResponseAlternative77
| QueryResponseAlternative78
- | QueryResponseAlternative81
+ | QueryResponseAlternative79
| QueryResponseAlternative82
| QueryResponseAlternative83
| QueryResponseAlternative84
@@ -27050,6 +27357,7 @@ class QueryResponseAlternative(
| QueryResponseAlternative101
| QueryResponseAlternative102
| QueryResponseAlternative103
+ | QueryResponseAlternative104
]
):
root: (
@@ -27087,8 +27395,8 @@ class QueryResponseAlternative(
| QueryResponseAlternative31
| QueryResponseAlternative32
| QueryResponseAlternative33
- | Any
| QueryResponseAlternative34
+ | Any
| QueryResponseAlternative35
| QueryResponseAlternative36
| QueryResponseAlternative37
@@ -27104,17 +27412,17 @@ class QueryResponseAlternative(
| QueryResponseAlternative47
| QueryResponseAlternative48
| QueryResponseAlternative49
- | QueryResponseAlternative51
+ | QueryResponseAlternative50
| QueryResponseAlternative52
| QueryResponseAlternative53
- | QueryResponseAlternative55
+ | QueryResponseAlternative54
| QueryResponseAlternative56
| QueryResponseAlternative57
| QueryResponseAlternative58
| QueryResponseAlternative59
| QueryResponseAlternative60
| QueryResponseAlternative61
- | QueryResponseAlternative63
+ | QueryResponseAlternative62
| QueryResponseAlternative64
| QueryResponseAlternative65
| QueryResponseAlternative66
@@ -27130,7 +27438,7 @@ class QueryResponseAlternative(
| QueryResponseAlternative76
| QueryResponseAlternative77
| QueryResponseAlternative78
- | QueryResponseAlternative81
+ | QueryResponseAlternative79
| QueryResponseAlternative82
| QueryResponseAlternative83
| QueryResponseAlternative84
@@ -27153,6 +27461,7 @@ class QueryResponseAlternative(
| QueryResponseAlternative101
| QueryResponseAlternative102
| QueryResponseAlternative103
+ | QueryResponseAlternative104
)
@@ -28060,6 +28369,7 @@ class HogQLAutocomplete(BaseModel):
| MarketingAnalyticsTableQuery
| MarketingAnalyticsAggregatedQuery
| MarketingAnalyticsAttributionQuery
+ | MarketingAnalyticsAttributionPathsQuery
| NonIntegratedConversionsTableQuery
| WebOverviewQuery
| WebStatsTableQuery
@@ -28165,6 +28475,7 @@ class HogQLMetadata(BaseModel):
| MarketingAnalyticsTableQuery
| MarketingAnalyticsAggregatedQuery
| MarketingAnalyticsAttributionQuery
+ | MarketingAnalyticsAttributionPathsQuery
| NonIntegratedConversionsTableQuery
| WebOverviewQuery
| WebStatsTableQuery
@@ -28304,6 +28615,7 @@ class MaxInsightContext(BaseModel):
| MarketingAnalyticsTableQuery
| MarketingAnalyticsAggregatedQuery
| MarketingAnalyticsAttributionQuery
+ | MarketingAnalyticsAttributionPathsQuery
| NonIntegratedConversionsTableQuery
| DataVisualizationNode
| DataTableNode
@@ -28437,6 +28749,7 @@ class QueryRequest(BaseModel):
| MarketingAnalyticsTableQuery
| MarketingAnalyticsAggregatedQuery
| MarketingAnalyticsAttributionQuery
+ | MarketingAnalyticsAttributionPathsQuery
| NonIntegratedConversionsTableQuery
| DataVisualizationNode
| DataTableNode
@@ -28562,6 +28875,7 @@ class QuerySchemaRoot(
| MarketingAnalyticsTableQuery
| MarketingAnalyticsAggregatedQuery
| MarketingAnalyticsAttributionQuery
+ | MarketingAnalyticsAttributionPathsQuery
| NonIntegratedConversionsTableQuery
| DataVisualizationNode
| DataTableNode
@@ -28657,6 +28971,7 @@ class QuerySchemaRoot(
| MarketingAnalyticsTableQuery
| MarketingAnalyticsAggregatedQuery
| MarketingAnalyticsAttributionQuery
+ | MarketingAnalyticsAttributionPathsQuery
| NonIntegratedConversionsTableQuery
| DataVisualizationNode
| DataTableNode
@@ -28757,6 +29072,7 @@ class QueryUpgradeRequest(BaseModel):
| MarketingAnalyticsTableQuery
| MarketingAnalyticsAggregatedQuery
| MarketingAnalyticsAttributionQuery
+ | MarketingAnalyticsAttributionPathsQuery
| NonIntegratedConversionsTableQuery
| DataVisualizationNode
| DataTableNode
@@ -28857,6 +29173,7 @@ class QueryUpgradeResponse(BaseModel):
| MarketingAnalyticsTableQuery
| MarketingAnalyticsAggregatedQuery
| MarketingAnalyticsAttributionQuery
+ | MarketingAnalyticsAttributionPathsQuery
| NonIntegratedConversionsTableQuery
| DataVisualizationNode
| DataTableNode
@@ -29139,6 +29456,7 @@ class VisualizationArtifactContent(BaseModel):
| MarketingAnalyticsTableQuery
| MarketingAnalyticsAggregatedQuery
| MarketingAnalyticsAttributionQuery
+ | MarketingAnalyticsAttributionPathsQuery
| NonIntegratedConversionsTableQuery
| DataVisualizationNode
| DataTableNode
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index 3f01856aaf4c..9fdb39b01f97 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -3228,6 +3228,7 @@ class NodeKind(StrEnum):
MARKETING_ANALYTICS_TABLE_QUERY = "MarketingAnalyticsTableQuery"
MARKETING_ANALYTICS_AGGREGATED_QUERY = "MarketingAnalyticsAggregatedQuery"
MARKETING_ANALYTICS_ATTRIBUTION_QUERY = "MarketingAnalyticsAttributionQuery"
+ MARKETING_ANALYTICS_ATTRIBUTION_PATHS_QUERY = "MarketingAnalyticsAttributionPathsQuery"
NON_INTEGRATED_CONVERSIONS_TABLE_QUERY = "NonIntegratedConversionsTableQuery"
EXPERIMENT_METRIC = "ExperimentMetric"
EXPERIMENT_QUERY = "ExperimentQuery"
diff --git a/products/marketing_analytics/backend/hogql_queries/attribution_base.py b/products/marketing_analytics/backend/hogql_queries/attribution_base.py
new file mode 100644
index 000000000000..f83082bfd89e
--- /dev/null
+++ b/products/marketing_analytics/backend/hogql_queries/attribution_base.py
@@ -0,0 +1,503 @@
+"""Shared machinery for the attribution runners: the table (all five models side by side) and the
+conversion paths (most common touchpoint sequences). Both define a touchpoint the same way — a pageview
+inside a real session, read through the `events.session` lazy join — and both collect per-converting-person
+arrays of conversions and touchpoints before diverging in how they aggregate them. Keeping the touchpoint
+definition, the exclusion options and the person-array collection here is what stops the two surfaces from
+drifting on what a journey is.
+"""
+
+from functools import cached_property
+from typing import Generic
+
+from posthog.schema import (
+ BaseMathType,
+ ConversionGoalFilter1,
+ ConversionGoalFilter2,
+ ConversionGoalFilter3,
+ MarketingAnalyticsAttributionBreakdown,
+ MarketingAnalyticsAttributionPathsQuery,
+ MarketingAnalyticsAttributionQuery,
+ PropertyMathType,
+)
+
+from posthog.hogql import ast
+
+from posthog.hogql_queries.utils.query_date_range import QueryDateRange
+from posthog.models.team.team_marketing_analytics_config import MAX_ATTRIBUTION_WINDOW_DAYS, MIN_ATTRIBUTION_WINDOW_DAYS
+
+from .attribution_weights import DAY_IN_SECONDS
+from .constants import DIRECT_REFERRING_DOMAIN, UNKNOWN_CHANNEL
+from .conversion_goal_conditions import conversion_goal_condition
+from .marketing_analytics_base_query_runner import MarketingAnalyticsBaseQueryRunner, ResponseType
+
+ConversionGoal = ConversionGoalFilter1 | ConversionGoalFilter2 | ConversionGoalFilter3
+
+# Session field backing each breakdown. Read through the events->sessions lazy join, so a team on
+# sessions v2 or v3 gets whichever version its modifiers select.
+BREAKDOWN_SESSION_FIELDS: dict[MarketingAnalyticsAttributionBreakdown, str] = {
+ MarketingAnalyticsAttributionBreakdown.CHANNEL: "$channel_type",
+ MarketingAnalyticsAttributionBreakdown.SOURCE: "$entry_utm_source",
+ MarketingAnalyticsAttributionBreakdown.CAMPAIGN: "$entry_utm_campaign",
+ MarketingAnalyticsAttributionBreakdown.MEDIUM: "$entry_utm_medium",
+ MarketingAnalyticsAttributionBreakdown.CONTENT: "$entry_utm_content",
+ MarketingAnalyticsAttributionBreakdown.TERM: "$entry_utm_term",
+ MarketingAnalyticsAttributionBreakdown.REFERRING_DOMAIN: "$entry_referring_domain",
+ MarketingAnalyticsAttributionBreakdown.LANDING_PAGE: "$entry_pathname",
+}
+
+# Values a breakdown's session field takes to mean "this session names nothing here", beyond an empty
+# value. Lives next to `BREAKDOWN_SESSION_FIELDS` and `_breakdown_expr` on purpose: "is this
+# unattributed?" and "what does this render as?" are the same question, and answering them in two
+# places is how a breakdown ends up excluding a row it displays under a real-looking name.
+UNATTRIBUTED_SESSION_VALUES: dict[MarketingAnalyticsAttributionBreakdown, tuple[str, ...]] = {
+ # The classifier's own sentinel for a session it couldn't place. Its other outputs (Organic
+ # Search, Direct, Referral) are real classifications and stay.
+ MarketingAnalyticsAttributionBreakdown.CHANNEL: (UNKNOWN_CHANNEL,),
+ MarketingAnalyticsAttributionBreakdown.REFERRING_DOMAIN: (DIRECT_REFERRING_DOMAIN,),
+}
+
+# Both runners collect per-person arrays under this name before diverging.
+PERSON_ARRAYS_CTE = "person_arrays"
+
+# Ceiling on how many sessions of one person can earn credit. Bots and shared devices would otherwise
+# fan out touchpoints x conversions far enough to dominate the query. Touchpoints are sorted before
+# truncating and the *most recent* are kept, because only touches within a lookback window of a
+# conversion can be credited and conversions sit at the end of the range. Keeping the oldest instead
+# would strand a heavy person's conversions with no eligible touchpoint at all, dropping them from the
+# table; this way they keep their credit, and only first touch becomes approximate for such a person.
+MAX_TOUCHPOINTS_PER_PERSON = 500
+
+
+class AttributionQueryRunnerBase(MarketingAnalyticsBaseQueryRunner[ResponseType], Generic[ResponseType]):
+ query: MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery
+
+ @property
+ def breakdown(self) -> MarketingAnalyticsAttributionBreakdown:
+ return self.query.breakdownBy or MarketingAnalyticsAttributionBreakdown.CHANNEL
+
+ @property
+ def lookback_window_days(self) -> int:
+ """The window this query attributes over, bounded the same way the team setting is.
+
+ The override widens the events scan, and the schema types it as a plain integer, so an
+ out-of-range value from a hand-built query would scan the team's whole event history.
+ """
+ override = self.query.lookbackWindowDays
+ if override is None:
+ return self.config.attribution_window_days
+ if override < MIN_ATTRIBUTION_WINDOW_DAYS or override > MAX_ATTRIBUTION_WINDOW_DAYS:
+ raise ValueError(
+ f"The attribution window must be between {MIN_ATTRIBUTION_WINDOW_DAYS} and "
+ f"{MAX_ATTRIBUTION_WINDOW_DAYS} days."
+ )
+ return override
+
+ @property
+ def attribution_window_seconds(self) -> int:
+ return self.lookback_window_days * DAY_IN_SECONDS
+
+ @cached_property
+ def goal(self) -> ConversionGoal:
+ """The requested goal, found among the team's configured goals.
+
+ Data warehouse goals are rejected rather than silently mis-attributed: their conversions live in
+ a warehouse table keyed by distinct_id, but this query collects conversions and touchpoints from
+ one `events` scan grouped by person_id, so there is nothing to join them on here.
+ """
+ all_goals = self._get_team_conversion_goals()
+ goals, skipped_goals = self._filter_invalid_conversion_goals(all_goals)
+ self._valid_conversion_goals_count = len(goals)
+
+ for goal in goals:
+ if goal.conversion_goal_id == self.query.conversionGoalId:
+ if goal.kind == "DataWarehouseNode":
+ raise ValueError(
+ f"Conversion goal '{goal.conversion_goal_name}' is backed by a data warehouse table, "
+ "which attribution doesn't support yet. Pick an event or action goal."
+ )
+ return goal
+
+ # Only one goal is queried at a time, so another goal being unusable is not this query's problem.
+ # Only report it when it's the goal that was actually asked for.
+ skipped = next((g for g in all_goals if g.conversion_goal_id == self.query.conversionGoalId), None)
+ if skipped is not None:
+ reason = next(
+ (s.message for s in skipped_goals if s.conversion_goal_id == self.query.conversionGoalId), None
+ )
+ raise ValueError(reason or f"Conversion goal '{skipped.conversion_goal_name}' can't be attributed")
+
+ raise ValueError(f"Conversion goal '{self.query.conversionGoalId}' not found for this team")
+
+ @cached_property
+ def conversion_condition(self) -> ast.Expr:
+ """True for an event row that counts as a conversion for this goal.
+
+ Shared with the Dashboard's pipeline so the two can't drift on what a conversion is, which
+ includes the goal's own property filters: a goal scoped to purchases over $100 has to mean that
+ here too, or this table reports a different number than the Dashboard for the same goal.
+
+ Cached because the query references it three times, and the action branch hits Postgres.
+ """
+ goal = self.goal
+ condition = conversion_goal_condition(goal, self.team)
+ if condition is None:
+ # Validation already rejected the goals with nothing to match on, so what's left is an
+ # action-based goal whose action was deleted.
+ raise ValueError(
+ f"Conversion goal '{goal.conversion_goal_name}' points to an action that no longer exists. "
+ "Update the goal in marketing analytics settings, or pick another goal."
+ )
+ return condition
+
+ @cached_property
+ def allows_multiple_conversions_per_visitor(self) -> bool:
+ """Whether a repeat converter contributes every conversion, or just one.
+
+ Unset follows the goal's own math: unique-users math already means one conversion per person
+ (mirroring `ConversionGoalProcessor`'s DAU branch, which counts persons rather than events), so
+ counting every event here would contradict the number the Dashboard reports for the same goal.
+ Count-based goals credit every conversion, which is why their rate columns can exceed 100% — a
+ person can convert more often than they visited.
+ """
+ if self.query.allowMultipleConversionsPerVisitor is not None:
+ return self.query.allowMultipleConversionsPerVisitor
+ return self.goal.math not in [BaseMathType.DAU, "dau"]
+
+ def _conversion_value_expr(self) -> ast.Expr:
+ """Value of one conversion: the goal's math property under SUM math, otherwise 1.
+
+ Mirrors `ConversionGoalProcessor._get_conversion_value_expr` — these must stay in lockstep, or
+ the same goal would report different revenue on the Dashboard and here.
+ """
+ goal = self.goal
+ math_type = goal.math
+ if math_type in ["sum", PropertyMathType.SUM] or str(math_type).endswith("_sum"):
+ if goal.math_property:
+ return ast.Call(
+ name="coalesce",
+ args=[
+ ast.Call(name="toFloat", args=[ast.Field(chain=["events", "properties", goal.math_property])]),
+ ast.Constant(value=0.0),
+ ],
+ )
+ return ast.Call(name="toFloat", args=[ast.Constant(value=1)])
+
+ def _breakdown_expr(self) -> ast.Expr:
+ """The dimension a touchpoint reports as, read off the session it belongs to.
+
+ Channel, source and campaign fall back to the same sentinels and normalization the rest of
+ marketing analytics uses, so rows line up with the cost side. The remaining breakdowns have no
+ team-configurable aliasing to collapse, so they pass the entry field straight through.
+ """
+ field = ast.Field(chain=["events", "session", BREAKDOWN_SESSION_FIELDS[self.breakdown]])
+
+ if self.breakdown == MarketingAnalyticsAttributionBreakdown.CHANNEL:
+ return self._non_empty_or(field, UNKNOWN_CHANNEL)
+ if self.breakdown == MarketingAnalyticsAttributionBreakdown.SOURCE:
+ return self._normalized_source_expr(field)
+ if self.breakdown == MarketingAnalyticsAttributionBreakdown.CAMPAIGN:
+ return self._normalized_campaign_expr(field)
+ return ast.Call(name="toString", args=[ast.Call(name="ifNull", args=[field, ast.Constant(value="")])])
+
+ def _normalized_source_expr(self, field: ast.Expr) -> ast.Expr:
+ """Collapse the team's custom UTM source aliases onto each adapter's canonical source name, or
+ the events side and the cost side disagree on the row key. Same treatment as `_build_sessions_select`.
+ """
+ from .adapters.factory import MarketingSourceFactory # noqa: PLC0415 — avoids an import cycle
+ from .utils import build_source_normalization_expr # noqa: PLC0415 — avoids an import cycle
+
+ source_mappings = MarketingSourceFactory.get_all_source_identifier_mappings(
+ team_config=self.team.marketing_analytics_config
+ )
+ return build_source_normalization_expr(
+ self._non_empty_or(field, self.config.organic_source),
+ source_mappings,
+ )
+
+ def _normalized_campaign_expr(self, field: ast.Expr) -> ast.Expr:
+ """Collapse the team's dirty utm_campaign spellings onto the clean name they're mapped to.
+
+ Without this a campaign whose UTMs vary lands as one row per spelling, and because the models
+ credit each row independently, first touch can name one spelling while last touch names another
+ — the comparison this table exists for then reads as a difference between campaigns that are
+ the same campaign. Scoped by source, so the mapping is applied the way the Dashboard applies it.
+ """
+ from .utils import build_campaign_display_normalization_expr # noqa: PLC0415 — avoids an import cycle
+
+ raw_campaign = ast.Call(name="toString", args=[ast.Call(name="ifNull", args=[field, ast.Constant(value="")])])
+ return build_campaign_display_normalization_expr(
+ raw_campaign,
+ ast.Field(chain=["events", "session", "$entry_utm_source"]),
+ self.team.marketing_analytics_config,
+ )
+
+ @staticmethod
+ def _non_empty_or(field: ast.Expr, fallback: str) -> ast.Expr:
+ return ast.Call(
+ name="if",
+ args=[
+ ast.Call(name="notEmpty", args=[ast.Call(name="ifNull", args=[field, ast.Constant(value="")])]),
+ field,
+ ast.Constant(value=fallback),
+ ],
+ )
+
+ def _pageview_condition(self) -> ast.Expr:
+ return ast.CompareOperation(
+ left=ast.Field(chain=["events", "event"]),
+ op=ast.CompareOperationOp.Eq,
+ right=ast.Constant(value="$pageview"),
+ )
+
+ def _touchpoint_condition(self) -> ast.Expr:
+ """A pageview inside a real session counts as a touchpoint.
+
+ Both exclusions are applied here — before the weights are computed — so the remaining
+ touchpoints renormalize to full credit instead of quietly losing the excluded share.
+ """
+ conditions: list[ast.Expr] = [
+ self._pageview_condition(),
+ ast.Call(name="notEmpty", args=[ast.Field(chain=["events", "$session_id"])]),
+ # A session id that resolves to no session row yields epoch zero rather than null, because the
+ # join fills a non-nullable column with its default. Test for a real timestamp rather than for
+ # null: 1970 can never satisfy the attribution window, so such a touchpoint earns nothing, and
+ # left in place it would sort to the very front and consume truncation slots. When a
+ # conversion's own session is one of these, dropping it here is what keeps the conversion out
+ # of the attributed count instead of silently crediting nobody.
+ ast.CompareOperation(
+ left=ast.Call(
+ name="toUnixTimestamp", args=[ast.Field(chain=["events", "session", "$start_timestamp"])]
+ ),
+ op=ast.CompareOperationOp.Gt,
+ right=ast.Constant(value=0),
+ ),
+ ]
+ if self.query.excludeDirectTraffic:
+ conditions.append(
+ ast.CompareOperation(
+ left=ast.Field(chain=["events", "session", "$channel_type"]),
+ op=ast.CompareOperationOp.NotEq,
+ right=ast.Constant(value="Direct"),
+ )
+ )
+ if self.query.excludeUnattributed:
+ # A touchpoint is unattributed when the session names nothing for the current breakdown:
+ # an empty value, or one of the sentinels that breakdown substitutes for "don't know".
+ # Judged on the raw session field rather than the display expression, so a friendly
+ # fallback label can't smuggle an empty value back in.
+ #
+ # Which is why channel and source deliberately part ways on the same untagged session:
+ # `$channel_type` runs a classifier that places it in a real bucket (Organic Search,
+ # Direct, Referral), so only the classifier's own `Unknown` counts as unattributed.
+ # `$entry_utm_source` has no classifier — an empty value there is the plain absence of a
+ # source, which `_breakdown_expr` merely *labels* `organic`, so it is excluded.
+ field = ast.Field(chain=["events", "session", BREAKDOWN_SESSION_FIELDS[self.breakdown]])
+ conditions.append(
+ ast.Call(name="notEmpty", args=[ast.Call(name="ifNull", args=[field, ast.Constant(value="")])])
+ )
+ for sentinel in UNATTRIBUTED_SESSION_VALUES.get(self.breakdown, ()):
+ conditions.append(
+ ast.CompareOperation(
+ left=field,
+ op=ast.CompareOperationOp.NotEq,
+ right=ast.Constant(value=sentinel),
+ )
+ )
+ return ast.And(exprs=conditions)
+
+ def _lookback_date_conditions(self, date_range: QueryDateRange) -> list[ast.Expr]:
+ """Pageview bounds extended back by the attribution window, so touches that predate the
+ display range can still be credited for a conversion inside it."""
+ return [
+ ast.CompareOperation(
+ left=ast.Field(chain=["events", "timestamp"]),
+ op=ast.CompareOperationOp.GtEq,
+ right=ast.ArithmeticOperation(
+ left=ast.Call(name="toDateTime", args=[ast.Constant(value=date_range.date_from_str)]),
+ op=ast.ArithmeticOperationOp.Sub,
+ right=ast.Call(name="toIntervalSecond", args=[ast.Constant(value=self.attribution_window_seconds)]),
+ ),
+ ),
+ ast.CompareOperation(
+ left=ast.Field(chain=["events", "timestamp"]),
+ op=ast.CompareOperationOp.LtEq,
+ right=ast.Call(name="toDateTime", args=[ast.Constant(value=date_range.date_to_str)]),
+ ),
+ ]
+
+ def _build_converters_select(self, date_range: QueryDateRange) -> ast.SelectQuery:
+ """Persons who converted in the window.
+
+ This is not an optimization — it is what makes the query affordable. Widening touchpoints from
+ "UTM-tagged pageviews" to "every session" multiplies the pageview side by roughly 10x; restricting
+ it to converters (typically low single-digit percent of persons) more than pays that back. Removing
+ this semi-join changes no results and costs one to two orders of magnitude more.
+ """
+ return ast.SelectQuery(
+ select=[ast.Field(chain=["events", "person_id"])],
+ select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),
+ where=ast.And(
+ exprs=[
+ self.conversion_condition,
+ *self._get_where_conditions(date_range, date_field="events.timestamp"),
+ ]
+ ),
+ group_by=[ast.Field(chain=["events", "person_id"])],
+ )
+
+ def _build_person_arrays_select(self, date_range: QueryDateRange) -> ast.SelectQuery:
+ """One row per converting person: its conversions, plus a deduped touchpoint set.
+
+ Both arrays hold (timestamp, payload) tuples rather than parallel arrays indexed together, since
+ `groupArray` gives no ordering guarantee and separate arrays could pair one conversion's timestamp
+ with another's value.
+
+ The `-If` combinators only append when the row qualifies, so neither array grows with the
+ person's unrelated events. `groupUniqArray` additionally collapses every pageview in a session to
+ one touchpoint during aggregation.
+ """
+ # Bounded to the display range, not the lookback-extended range the outer WHERE allows. The
+ # pageview branch of that WHERE reaches back a further lookback window to collect touchpoints, and
+ # without this bound every conversion in that older stretch would be credited too: the table would
+ # silently report a range far longer than the one asked for, and the extra conversions would mostly
+ # land as unattributed because touchpoint collection doesn't reach back a window before *them*.
+ conversions: ast.Expr = ast.Call(
+ name="groupArrayIf",
+ args=[
+ ast.Tuple(
+ exprs=[
+ ast.Call(name="toUnixTimestamp", args=[ast.Field(chain=["events", "timestamp"])]),
+ self._conversion_value_expr(),
+ ]
+ ),
+ ast.And(
+ exprs=[
+ self.conversion_condition,
+ *self._get_where_conditions(date_range, date_field="events.timestamp"),
+ ]
+ ),
+ ],
+ )
+
+ # Sorted before truncating: `groupUniqArray` is hash-backed, so its order is unrelated to time and
+ # slicing it raw would keep an arbitrary subset. The negative offset takes the tail of the sorted
+ # array, i.e. the most recent sessions — see MAX_TOUCHPOINTS_PER_PERSON for why that direction.
+ touchpoints = ast.Call(
+ name="arraySlice",
+ args=[
+ ast.Call(
+ name="arraySort",
+ args=[
+ ast.Call(
+ name="groupUniqArrayIf",
+ args=[
+ ast.Tuple(
+ exprs=[
+ ast.Call(
+ name="toUnixTimestamp",
+ args=[ast.Field(chain=["events", "session", "$start_timestamp"])],
+ ),
+ self._breakdown_expr(),
+ ]
+ ),
+ self._touchpoint_condition(),
+ ],
+ )
+ ],
+ ),
+ ast.Constant(value=-MAX_TOUCHPOINTS_PER_PERSON),
+ ],
+ )
+
+ if not self.allows_multiple_conversions_per_visitor:
+ # One conversion per person: keep the earliest in the window, so the models attribute the
+ # journey that led to them first converting rather than an arbitrary later repeat.
+ conversions = ast.Call(
+ name="arraySlice",
+ args=[
+ ast.Call(name="arraySort", args=[conversions]),
+ ast.Constant(value=1),
+ ast.Constant(value=1),
+ ],
+ )
+
+ return ast.SelectQuery(
+ select=[
+ ast.Field(chain=["events", "person_id"]),
+ ast.Alias(alias="conversions", expr=conversions),
+ ast.Alias(alias="touchpoints", expr=touchpoints),
+ ],
+ select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),
+ where=ast.And(
+ exprs=[
+ ast.CompareOperation(
+ left=ast.Field(chain=["events", "person_id"]),
+ op=ast.CompareOperationOp.In,
+ right=self._build_converters_select(date_range),
+ ),
+ ast.Or(
+ exprs=[
+ ast.And(
+ exprs=[
+ self.conversion_condition,
+ *self._get_where_conditions(date_range, date_field="events.timestamp"),
+ ]
+ ),
+ ast.And(
+ exprs=[
+ self._pageview_condition(),
+ *self._lookback_date_conditions(date_range),
+ ]
+ ),
+ ]
+ ),
+ ]
+ ),
+ group_by=[ast.Field(chain=["events", "person_id"])],
+ having=ast.CompareOperation(
+ left=ast.Call(name="length", args=[ast.Field(chain=["conversions"])]),
+ op=ast.CompareOperationOp.Gt,
+ right=ast.Constant(value=0),
+ ),
+ )
+
+ def _in_window_touchpoints_expr(self, conversion_time: ast.Expr) -> ast.Expr:
+ """The person's touchpoints that fall inside one conversion's attribution window.
+
+ Expects to be evaluated where `touchpoints` (from the person-arrays CTE) is in scope.
+ """
+ return ast.Call(
+ name="arrayFilter",
+ args=[
+ ast.Lambda(
+ args=["t"],
+ expr=ast.And(
+ exprs=[
+ ast.CompareOperation(
+ left=ast.TupleAccess(tuple=ast.Field(chain=["t"]), index=1),
+ op=ast.CompareOperationOp.LtEq,
+ right=conversion_time,
+ ),
+ ast.CompareOperation(
+ left=ast.TupleAccess(tuple=ast.Field(chain=["t"]), index=1),
+ op=ast.CompareOperationOp.GtEq,
+ right=ast.ArithmeticOperation(
+ left=conversion_time,
+ op=ast.ArithmeticOperationOp.Sub,
+ right=ast.Constant(value=self.attribution_window_seconds),
+ ),
+ ),
+ ]
+ ),
+ ),
+ ast.Field(chain=["touchpoints"]),
+ ],
+ )
+
+ def _build_main_select_query(self, conversion_aggregator) -> ast.SelectQuery:
+ """Not part of the attribution runners' shape.
+
+ The base hook exists to slot a SELECT into its ad-cost-joined table query; these runners override
+ `to_query` wholesale and build their own CTE chains, so there is nothing to hook.
+ """
+ raise NotImplementedError(f"{type(self).__name__} builds its query in to_query")
diff --git a/products/marketing_analytics/backend/hogql_queries/attribution_paths_query_runner.py b/products/marketing_analytics/backend/hogql_queries/attribution_paths_query_runner.py
new file mode 100644
index 000000000000..ba6b95c6a120
--- /dev/null
+++ b/products/marketing_analytics/backend/hogql_queries/attribution_paths_query_runner.py
@@ -0,0 +1,342 @@
+"""Conversion paths: the most common touchpoint sequences that end in a conversion.
+
+The attribution table answers "how much credit does each channel deserve"; this runner answers "what do
+the journeys actually look like". Each conversion contributes one path — its in-window touchpoints in
+time order, mapped to the selected breakdown dimension — and identical paths are grouped and ranked by
+how many conversions they produced.
+
+Consecutive repeats are deliberately preserved (a path of Direct, Direct is not the same journey as one
+Direct visit): the frontend collapses them to "Direct ×2" for display, but grouping happens on the raw
+sequence. Touchpoint definitions, exclusions and the person-array collection are shared with the
+attribution table via `AttributionQueryRunnerBase`, so a journey shown here is exactly the journey the
+models credited there.
+"""
+
+from typing import Any
+
+from posthog.schema import (
+ CachedMarketingAnalyticsAttributionPathsQueryResponse,
+ MarketingAnalyticsAttributionPathRow,
+ MarketingAnalyticsAttributionPathsQuery,
+ MarketingAnalyticsAttributionPathsQueryResponse,
+)
+
+from posthog.hogql import ast
+from posthog.hogql.constants import LimitContext
+from posthog.hogql.query import execute_hogql_query
+
+from .attribution_base import PERSON_ARRAYS_CTE, AttributionQueryRunnerBase
+from .constants import PAGINATION_EXTRA
+
+# Paths longer than this are grouped on their most recent steps — the same truncation direction as
+# MAX_TOUCHPOINTS_PER_PERSON, and for the same reason: the touches nearest the conversion are the ones
+# every model agrees matter. Untruncated grouping would also shatter heavy users' journeys into
+# hundreds of singleton rows that can never rank.
+PATH_MAX_LENGTH = 10
+
+# Fewer than the table's DEFAULT_LIMIT: paths are a long-tail distribution and row 51 is almost always
+# a singleton.
+PATHS_DEFAULT_LIMIT = 50
+
+# CTE names.
+_PER_CONVERSION_PATH_CTE = "per_conversion_path"
+_PATH_ROWS_CTE = "path_rows"
+_FOOTER_CTE = "paths_footer"
+
+_PATH = "path"
+_CONVERSIONS = "conversions"
+_CONVERSION_VALUE = "conversion_value"
+_PATH_TRUNCATED = "path_truncated"
+_TOTAL_CONVERSIONS = "total_conversions"
+_ATTRIBUTED_CONVERSIONS = "attributed_conversions"
+_JOIN_KEY = "footer_key"
+# ARRAY JOIN index identifying a conversion within its person.
+_CONVERSION_INDEX = "i"
+
+
+class MarketingAnalyticsAttributionPathsQueryRunner(
+ AttributionQueryRunnerBase[MarketingAnalyticsAttributionPathsQueryResponse]
+):
+ query: MarketingAnalyticsAttributionPathsQuery
+ response: MarketingAnalyticsAttributionPathsQueryResponse
+ cached_response: CachedMarketingAnalyticsAttributionPathsQueryResponse
+
+ def _validated_touchpoint_bounds(self) -> tuple[int | None, int | None]:
+ """The min/max filter, checked because the schema types them as plain integers.
+
+ Bounds are judged on the journey's original length, before truncation, so "4+" keeps meaning
+ what it says for a 30-touch journey.
+ """
+ minimum, maximum = self.query.minTouchpoints, self.query.maxTouchpoints
+ if minimum is not None and minimum < 1:
+ raise ValueError("minTouchpoints must be at least 1")
+ if maximum is not None and maximum < 1:
+ raise ValueError("maxTouchpoints must be at least 1")
+ if minimum is not None and maximum is not None and minimum > maximum:
+ raise ValueError("minTouchpoints can't exceed maxTouchpoints")
+ return minimum, maximum
+
+ # ------------------------------------------------------------------ CTEs
+
+ def _build_per_conversion_path_select(self) -> ast.SelectQuery:
+ """One row per conversion, carrying its path and pre-truncation length.
+
+ `orig_len` travels alongside the truncated path so both the touchpoint-count filter and the
+ footer can see the journey's true size after the path itself has been capped.
+ """
+ conversion = ast.ArrayAccess(
+ array=ast.Field(chain=["conversions"]), property=ast.Field(chain=[_CONVERSION_INDEX])
+ )
+
+ return ast.SelectQuery(
+ select=[
+ ast.Alias(alias="conv_value", expr=ast.TupleAccess(tuple=conversion, index=2)),
+ ast.Alias(
+ alias="tps",
+ expr=self._in_window_touchpoints_expr(ast.TupleAccess(tuple=conversion, index=1)),
+ ),
+ ast.Alias(
+ alias="path_full",
+ expr=ast.Call(
+ name="arrayMap",
+ args=[
+ ast.Lambda(args=["t"], expr=ast.TupleAccess(tuple=ast.Field(chain=["t"]), index=2)),
+ ast.Field(chain=["tps"]),
+ ],
+ ),
+ ),
+ ast.Alias(alias="orig_len", expr=ast.Call(name="length", args=[ast.Field(chain=["path_full"])])),
+ ast.Alias(
+ alias=_PATH,
+ expr=ast.Call(
+ name="arraySlice",
+ args=[ast.Field(chain=["path_full"]), ast.Constant(value=-PATH_MAX_LENGTH)],
+ ),
+ ),
+ ast.Alias(
+ alias="truncated",
+ expr=ast.CompareOperation(
+ left=ast.Field(chain=["orig_len"]),
+ op=ast.CompareOperationOp.Gt,
+ right=ast.Constant(value=PATH_MAX_LENGTH),
+ ),
+ ),
+ ],
+ select_from=ast.JoinExpr(table=ast.Field(chain=[PERSON_ARRAYS_CTE])),
+ array_join_op="ARRAY JOIN",
+ array_join_list=[
+ ast.Alias(
+ alias=_CONVERSION_INDEX,
+ expr=ast.Call(name="arrayEnumerate", args=[ast.Field(chain=["conversions"])]),
+ )
+ ],
+ )
+
+ def _build_path_rows_select(self) -> ast.SelectQuery:
+ """Group identical paths and count their conversions.
+
+ The touchpoint-count filter lives here and only here: the footer reads the unfiltered CTE, so
+ switching between "Any" and "exactly 2" re-ranks the rows without moving the share denominator.
+ """
+ minimum, maximum = self._validated_touchpoint_bounds()
+
+ conditions: list[ast.Expr] = [
+ # A conversion with no in-window touchpoint has no journey to show; it is still counted by
+ # the footer as unattributed.
+ ast.CompareOperation(
+ left=ast.Field(chain=["orig_len"]),
+ op=ast.CompareOperationOp.Gt,
+ right=ast.Constant(value=0),
+ )
+ ]
+ if minimum is not None:
+ conditions.append(
+ ast.CompareOperation(
+ left=ast.Field(chain=["orig_len"]),
+ op=ast.CompareOperationOp.GtEq,
+ right=ast.Constant(value=minimum),
+ )
+ )
+ if maximum is not None:
+ conditions.append(
+ ast.CompareOperation(
+ left=ast.Field(chain=["orig_len"]),
+ op=ast.CompareOperationOp.LtEq,
+ right=ast.Constant(value=maximum),
+ )
+ )
+
+ return ast.SelectQuery(
+ select=[
+ ast.Field(chain=[_PATH]),
+ ast.Alias(alias=_CONVERSIONS, expr=ast.Call(name="count", args=[])),
+ ast.Alias(alias=_CONVERSION_VALUE, expr=ast.Call(name="sum", args=[ast.Field(chain=["conv_value"])])),
+ # max() rather than any(): one truncated journey in the group is enough to warrant the
+ # "starts earlier" marker.
+ ast.Alias(alias=_PATH_TRUNCATED, expr=ast.Call(name="max", args=[ast.Field(chain=["truncated"])])),
+ ast.Alias(alias=_JOIN_KEY, expr=ast.Constant(value=1)),
+ ],
+ select_from=ast.JoinExpr(table=ast.Field(chain=[_PER_CONVERSION_PATH_CTE])),
+ where=ast.And(exprs=conditions),
+ group_by=[ast.Field(chain=[_PATH])],
+ )
+
+ def _build_footer_select(self) -> ast.SelectQuery:
+ """One row reconciling total against attributed conversions.
+
+ Same shape and reasoning as the attribution table's footer: its own CTE so a filter value that
+ matches no paths still reports "you have N conversions" rather than zeros.
+ """
+ return ast.SelectQuery(
+ select=[
+ ast.Alias(alias=_TOTAL_CONVERSIONS, expr=ast.Call(name="count", args=[])),
+ ast.Alias(
+ alias=_ATTRIBUTED_CONVERSIONS,
+ expr=ast.Call(
+ name="countIf",
+ args=[
+ ast.CompareOperation(
+ left=ast.Field(chain=["orig_len"]),
+ op=ast.CompareOperationOp.Gt,
+ right=ast.Constant(value=0),
+ )
+ ],
+ ),
+ ),
+ ast.Alias(alias=_JOIN_KEY, expr=ast.Constant(value=1)),
+ ],
+ select_from=ast.JoinExpr(table=ast.Field(chain=[_PER_CONVERSION_PATH_CTE])),
+ )
+
+ def _build_outer_select(self) -> ast.SelectQuery:
+ """Attach the footer counts to every row.
+
+ LEFT from the footer, which always has exactly one row, so the reconciliation survives a filter
+ that matched nothing. That leaves one placeholder row when there is nothing to show; `_JOIN_KEY`
+ is 0 on it, and `_calculate` drops it.
+ """
+ row_columns = [_PATH, _CONVERSIONS, _CONVERSION_VALUE, _PATH_TRUNCATED]
+ select: list[ast.Expr] = [
+ ast.Alias(alias=name, expr=ast.Field(chain=[_PATH_ROWS_CTE, name])) for name in row_columns
+ ]
+ select.extend(
+ [
+ ast.Alias(alias=_TOTAL_CONVERSIONS, expr=ast.Field(chain=[_FOOTER_CTE, _TOTAL_CONVERSIONS])),
+ ast.Alias(alias=_ATTRIBUTED_CONVERSIONS, expr=ast.Field(chain=[_FOOTER_CTE, _ATTRIBUTED_CONVERSIONS])),
+ ast.Alias(alias=_JOIN_KEY, expr=ast.Field(chain=[_PATH_ROWS_CTE, _JOIN_KEY])),
+ ]
+ )
+
+ return ast.SelectQuery(
+ select=select,
+ select_from=ast.JoinExpr(
+ table=ast.Field(chain=[_FOOTER_CTE]),
+ next_join=ast.JoinExpr(
+ join_type="LEFT JOIN",
+ table=ast.Field(chain=[_PATH_ROWS_CTE]),
+ constraint=ast.JoinConstraint(
+ expr=ast.CompareOperation(
+ left=ast.Field(chain=[_FOOTER_CTE, _JOIN_KEY]),
+ op=ast.CompareOperationOp.Eq,
+ right=ast.Field(chain=[_PATH_ROWS_CTE, _JOIN_KEY]),
+ ),
+ constraint_type="ON",
+ ),
+ ),
+ ),
+ # The path tie-break makes equal-count rows return in a stable order across refetches, so
+ # rows don't shuffle when the user toggles the touchpoint filter back and forth.
+ order_by=[
+ ast.OrderExpr(expr=ast.Field(chain=[_CONVERSIONS]), order="DESC"),
+ ast.OrderExpr(expr=ast.Field(chain=[_PATH]), order="ASC"),
+ ],
+ limit=ast.Constant(value=(self.query.limit or PATHS_DEFAULT_LIMIT) + PAGINATION_EXTRA),
+ offset=ast.Constant(value=self.query.offset or 0),
+ )
+
+ # ------------------------------------------------------------------ main query
+
+ def to_query(self) -> ast.SelectQuery:
+ date_range = self.query_date_range
+
+ ctes: dict[str, ast.CTE] = {}
+ with self.timings.measure("attribution_paths_person_arrays_cte"):
+ ctes[PERSON_ARRAYS_CTE] = ast.CTE(
+ name=PERSON_ARRAYS_CTE,
+ expr=self._build_person_arrays_select(date_range),
+ cte_type="subquery",
+ )
+ # Materialized because two CTEs read it, and ClickHouse otherwise re-evaluates a CTE at each
+ # reference: without this the events scan underneath it happens twice.
+ ctes[_PER_CONVERSION_PATH_CTE] = ast.CTE(
+ name=_PER_CONVERSION_PATH_CTE,
+ expr=self._build_per_conversion_path_select(),
+ cte_type="subquery",
+ materialized=True,
+ )
+ ctes[_PATH_ROWS_CTE] = ast.CTE(name=_PATH_ROWS_CTE, expr=self._build_path_rows_select(), cte_type="subquery")
+ ctes[_FOOTER_CTE] = ast.CTE(name=_FOOTER_CTE, expr=self._build_footer_select(), cte_type="subquery")
+
+ query = self._build_outer_select()
+ query.ctes = ctes
+ return query
+
+ # ------------------------------------------------------------------ execution
+
+ def _calculate(self) -> MarketingAnalyticsAttributionPathsQueryResponse:
+ query = self.to_query()
+
+ response = execute_hogql_query(
+ query_type="marketing_analytics_attribution_paths_query",
+ query=query,
+ team=self.team,
+ user=self.user,
+ timings=self.timings,
+ modifiers=self.modifiers,
+ limit_context=self.limit_context or LimitContext.QUERY,
+ context=self._shared_hogql_context,
+ )
+
+ # Mapped by column name, not tuple position, so adding a column can't shift every later one.
+ columns = response.columns or []
+ named_results = [dict(zip(columns, row)) for row in response.results or []]
+
+ # Every row carries the same reconciliation totals, so read them off the first one. Read before
+ # the placeholder row is dropped, since that row exists precisely to carry them when there are
+ # no path rows.
+ first = named_results[0] if named_results else {}
+ total_conversions = int(first.get(_TOTAL_CONVERSIONS) or 0)
+ attributed_conversions = int(first.get(_ATTRIBUTED_CONVERSIONS) or 0)
+
+ named_results = [row for row in named_results if row.get(_JOIN_KEY)]
+
+ requested_limit = self.query.limit or PATHS_DEFAULT_LIMIT
+ has_more = len(named_results) > requested_limit
+ if has_more:
+ named_results = named_results[:requested_limit]
+
+ has_value = bool(self.goal.counts_as_revenue)
+ rows = [self._build_row(row, has_value=has_value) for row in named_results]
+
+ return MarketingAnalyticsAttributionPathsQueryResponse(
+ results=rows,
+ totalConversions=total_conversions,
+ attributedConversions=attributed_conversions,
+ attributionWindowDays=self.lookback_window_days,
+ hasValue=has_value,
+ hogql=response.hogql,
+ timings=response.timings,
+ modifiers=self.modifiers,
+ hasMore=has_more,
+ limit=requested_limit,
+ offset=self.query.offset or 0,
+ )
+
+ @staticmethod
+ def _build_row(row: dict[str, Any], *, has_value: bool) -> MarketingAnalyticsAttributionPathRow:
+ return MarketingAnalyticsAttributionPathRow(
+ path=[str(step) for step in (row.get(_PATH) or [])],
+ conversions=int(row.get(_CONVERSIONS) or 0),
+ conversionValue=float(row.get(_CONVERSION_VALUE) or 0.0) if has_value else None,
+ pathTruncated=bool(row.get(_PATH_TRUNCATED)),
+ )
diff --git a/products/marketing_analytics/backend/hogql_queries/attribution_table_query_runner.py b/products/marketing_analytics/backend/hogql_queries/attribution_table_query_runner.py
index 1155bf30c90b..9ab5deff4abb 100644
--- a/products/marketing_analytics/backend/hogql_queries/attribution_table_query_runner.py
+++ b/products/marketing_analytics/backend/hogql_queries/attribution_table_query_runner.py
@@ -17,22 +17,15 @@ Consequence worth knowing: the Last touch column will not equal the Dashboard's
same goal and window, because the Dashboard only ever sees UTM-tagged pageviews.
"""
-from functools import cached_property
from typing import Any
from posthog.schema import (
AttributionMode,
- BaseMathType,
CachedMarketingAnalyticsAttributionQueryResponse,
- ConversionGoalFilter1,
- ConversionGoalFilter2,
- ConversionGoalFilter3,
- MarketingAnalyticsAttributionBreakdown,
MarketingAnalyticsAttributionModelCell,
MarketingAnalyticsAttributionQuery,
MarketingAnalyticsAttributionQueryResponse,
MarketingAnalyticsAttributionRow,
- PropertyMathType,
)
from posthog.hogql import ast
@@ -40,21 +33,16 @@ from posthog.hogql.constants import LimitContext
from posthog.hogql.query import execute_hogql_query
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
-from posthog.models.team.team_marketing_analytics_config import MAX_ATTRIBUTION_WINDOW_DAYS, MIN_ATTRIBUTION_WINDOW_DAYS
+from .attribution_base import PERSON_ARRAYS_CTE, AttributionQueryRunnerBase
from .attribution_weights import (
- DAY_IN_SECONDS,
build_first_touch_weights,
build_last_touch_weights,
build_linear_weights,
build_position_based_weights,
build_time_decay_weights,
)
-from .constants import DEFAULT_LIMIT, PAGINATION_EXTRA, UNKNOWN_CHANNEL
-from .conversion_goal_conditions import conversion_goal_condition
-from .marketing_analytics_base_query_runner import MarketingAnalyticsBaseQueryRunner
-
-ConversionGoal = ConversionGoalFilter1 | ConversionGoalFilter2 | ConversionGoalFilter3
+from .constants import DEFAULT_LIMIT, PAGINATION_EXTRA
# Column order for the table's model groups: single-touch first, then multi-touch, so the columns read
# left to right from the crudest split to the most nuanced.
@@ -75,22 +63,8 @@ _WEIGHT_ALIASES: dict[AttributionMode, str] = {
AttributionMode.POSITION_BASED: "w_position",
}
-# Session field backing each breakdown. Read through the events->sessions lazy join, so a team on
-# sessions v2 or v3 gets whichever version its modifiers select.
-_BREAKDOWN_SESSION_FIELDS: dict[MarketingAnalyticsAttributionBreakdown, str] = {
- MarketingAnalyticsAttributionBreakdown.CHANNEL: "$channel_type",
- MarketingAnalyticsAttributionBreakdown.SOURCE: "$entry_utm_source",
- MarketingAnalyticsAttributionBreakdown.CAMPAIGN: "$entry_utm_campaign",
- MarketingAnalyticsAttributionBreakdown.MEDIUM: "$entry_utm_medium",
- MarketingAnalyticsAttributionBreakdown.CONTENT: "$entry_utm_content",
- MarketingAnalyticsAttributionBreakdown.TERM: "$entry_utm_term",
- MarketingAnalyticsAttributionBreakdown.REFERRING_DOMAIN: "$entry_referring_domain",
- MarketingAnalyticsAttributionBreakdown.LANDING_PAGE: "$entry_pathname",
-}
-
# CTE names.
_REACH_CTE = "influenced_reach"
-_PERSON_ARRAYS_CTE = "person_arrays"
_PER_CONVERSION_CTE = "per_conversion"
_PER_TOUCHPOINT_CTE = "per_touchpoint"
_PER_CONVERSION_DIM_CTE = "per_conversion_dim"
@@ -98,14 +72,6 @@ _TOTALS_CTE = "attribution_totals"
_ROWS_CTE = "attribution_rows"
_FOOTER_CTE = "attribution_footer"
-# Ceiling on how many sessions of one person can earn credit. Bots and shared devices would otherwise
-# fan out touchpoints x conversions in (D) and (E) far enough to dominate the query. Touchpoints are
-# sorted before truncating and the *most recent* are kept, because only touches within a lookback window
-# of a conversion can be credited and conversions sit at the end of the range. Keeping the oldest instead
-# would strand a heavy person's conversions with no eligible touchpoint at all, dropping them from the
-# table; this way they keep their credit, and only first touch becomes approximate for such a person.
-MAX_TOUCHPOINTS_PER_PERSON = 500
-
_BREAKDOWN_VALUE = "breakdown_value"
_VISITORS = "visitors"
_INFLUENCED_CONVERSIONS = "influenced_conversions"
@@ -123,164 +89,11 @@ def _ordered_weight_aliases() -> list[str]:
return [_WEIGHT_ALIASES[model] for model in MODEL_ORDER]
-class MarketingAnalyticsAttributionQueryRunner(
- MarketingAnalyticsBaseQueryRunner[MarketingAnalyticsAttributionQueryResponse]
-):
+class MarketingAnalyticsAttributionQueryRunner(AttributionQueryRunnerBase[MarketingAnalyticsAttributionQueryResponse]):
query: MarketingAnalyticsAttributionQuery
response: MarketingAnalyticsAttributionQueryResponse
cached_response: CachedMarketingAnalyticsAttributionQueryResponse
- @property
- def breakdown(self) -> MarketingAnalyticsAttributionBreakdown:
- return self.query.breakdownBy or MarketingAnalyticsAttributionBreakdown.CHANNEL
-
- @property
- def lookback_window_days(self) -> int:
- """The window this query attributes over, bounded the same way the team setting is.
-
- The override widens the events scan, and the schema types it as a plain integer, so an
- out-of-range value from a hand-built query would scan the team's whole event history.
- """
- override = self.query.lookbackWindowDays
- if override is None:
- return self.config.attribution_window_days
- if override < MIN_ATTRIBUTION_WINDOW_DAYS or override > MAX_ATTRIBUTION_WINDOW_DAYS:
- raise ValueError(
- f"The attribution window must be between {MIN_ATTRIBUTION_WINDOW_DAYS} and "
- f"{MAX_ATTRIBUTION_WINDOW_DAYS} days."
- )
- return override
-
- @property
- def attribution_window_seconds(self) -> int:
- return self.lookback_window_days * DAY_IN_SECONDS
-
- @cached_property
- def goal(self) -> ConversionGoal:
- """The requested goal, found among the team's configured goals.
-
- Data warehouse goals are rejected rather than silently mis-attributed: their conversions live in
- a warehouse table keyed by distinct_id, but this query collects conversions and touchpoints from
- one `events` scan grouped by person_id, so there is nothing to join them on here.
- """
- all_goals = self._get_team_conversion_goals()
- goals, skipped_goals = self._filter_invalid_conversion_goals(all_goals)
- self._valid_conversion_goals_count = len(goals)
-
- for goal in goals:
- if goal.conversion_goal_id == self.query.conversionGoalId:
- if goal.kind == "DataWarehouseNode":
- raise ValueError(
- f"Conversion goal '{goal.conversion_goal_name}' is backed by a data warehouse table, "
- "which attribution doesn't support yet. Pick an event or action goal."
- )
- return goal
-
- # The table shows one goal at a time, so another goal being unusable is not this query's problem.
- # Only report it when it's the goal that was actually asked for.
- skipped = next((g for g in all_goals if g.conversion_goal_id == self.query.conversionGoalId), None)
- if skipped is not None:
- reason = next(
- (s.message for s in skipped_goals if s.conversion_goal_id == self.query.conversionGoalId), None
- )
- raise ValueError(reason or f"Conversion goal '{skipped.conversion_goal_name}' can't be attributed")
-
- raise ValueError(f"Conversion goal '{self.query.conversionGoalId}' not found for this team")
-
- @cached_property
- def conversion_condition(self) -> ast.Expr:
- """True for an event row that counts as a conversion for this goal.
-
- Shared with the Dashboard's pipeline so the two can't drift on what a conversion is, which
- includes the goal's own property filters: a goal scoped to purchases over $100 has to mean that
- here too, or this table reports a different number than the Dashboard for the same goal.
-
- Cached because the query references it three times, and the action branch hits Postgres.
- """
- goal = self.goal
- condition = conversion_goal_condition(goal, self.team)
- if condition is None:
- # Validation already rejected the goals with nothing to match on, so what's left is an
- # action-based goal whose action was deleted.
- raise ValueError(
- f"Conversion goal '{goal.conversion_goal_name}' points to an action that no longer exists. "
- "Update the goal in marketing analytics settings, or pick another goal."
- )
- return condition
-
- @cached_property
- def allows_multiple_conversions_per_visitor(self) -> bool:
- """Whether a repeat converter contributes every conversion, or just one.
-
- Unset follows the goal's own math: unique-users math already means one conversion per person
- (mirroring `ConversionGoalProcessor`'s DAU branch, which counts persons rather than events), so
- counting every event here would contradict the number the Dashboard reports for the same goal.
- Count-based goals credit every conversion, which is why their rate columns can exceed 100% — a
- person can convert more often than they visited.
- """
- if self.query.allowMultipleConversionsPerVisitor is not None:
- return self.query.allowMultipleConversionsPerVisitor
- return self.goal.math not in [BaseMathType.DAU, "dau"]
-
- def _conversion_value_expr(self) -> ast.Expr:
- """Value of one conversion: the goal's math property under SUM math, otherwise 1.
-
- Mirrors `ConversionGoalProcessor._get_conversion_value_expr` — these must stay in lockstep, or
- the same goal would report different revenue on the Dashboard and here.
- """
- goal = self.goal
- math_type = goal.math
- if math_type in ["sum", PropertyMathType.SUM] or str(math_type).endswith("_sum"):
- if goal.math_property:
- return ast.Call(
- name="coalesce",
- args=[
- ast.Call(name="toFloat", args=[ast.Field(chain=["events", "properties", goal.math_property])]),
- ast.Constant(value=0.0),
- ],
- )
- return ast.Call(name="toFloat", args=[ast.Constant(value=1)])
-
- def _breakdown_expr(self) -> ast.Expr:
- """The row dimension, read off the session a touchpoint belongs to.
-
- Channel and source fall back to the same sentinels the rest of marketing analytics uses, so rows
- line up with the cost side.
- """
- field = ast.Field(chain=["events", "session", _BREAKDOWN_SESSION_FIELDS[self.breakdown]])
-
- if self.breakdown == MarketingAnalyticsAttributionBreakdown.CHANNEL:
- return self._non_empty_or(field, UNKNOWN_CHANNEL)
- if self.breakdown == MarketingAnalyticsAttributionBreakdown.SOURCE:
- return self._normalized_source_expr(field)
- return ast.Call(name="toString", args=[ast.Call(name="ifNull", args=[field, ast.Constant(value="")])])
-
- def _normalized_source_expr(self, field: ast.Expr) -> ast.Expr:
- """Collapse the team's custom UTM source aliases onto each adapter's canonical source name, or
- the events side and the cost side disagree on the row key. Same treatment as `_build_sessions_select`.
- """
- from .adapters.factory import MarketingSourceFactory # noqa: PLC0415 — avoids an import cycle
- from .utils import build_source_normalization_expr # noqa: PLC0415 — avoids an import cycle
-
- source_mappings = MarketingSourceFactory.get_all_source_identifier_mappings(
- team_config=self.team.marketing_analytics_config
- )
- return build_source_normalization_expr(
- self._non_empty_or(field, self.config.organic_source),
- source_mappings,
- )
-
- @staticmethod
- def _non_empty_or(field: ast.Expr, fallback: str) -> ast.Expr:
- return ast.Call(
- name="if",
- args=[
- ast.Call(name="notEmpty", args=[ast.Call(name="ifNull", args=[field, ast.Constant(value="")])]),
- field,
- ast.Constant(value=fallback),
- ],
- )
-
# ------------------------------------------------------------------ CTEs
def _build_reach_select(self, date_range: QueryDateRange) -> ast.SelectQuery:
@@ -309,202 +122,6 @@ class MarketingAnalyticsAttributionQueryRunner(
group_by=[ast.Field(chain=[_BREAKDOWN_VALUE])],
)
- def _build_converters_select(self, date_range: QueryDateRange) -> ast.SelectQuery:
- """(B) Persons who converted in the window.
-
- This is not an optimization — it is what makes the query affordable. Widening touchpoints from
- "UTM-tagged pageviews" to "every session" multiplies the pageview side by roughly 10x; restricting
- it to converters (typically low single-digit percent of persons) more than pays that back. Removing
- this semi-join changes no results and costs one to two orders of magnitude more.
- """
- return ast.SelectQuery(
- select=[ast.Field(chain=["events", "person_id"])],
- select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),
- where=ast.And(
- exprs=[
- self.conversion_condition,
- *self._get_where_conditions(date_range, date_field="events.timestamp"),
- ]
- ),
- group_by=[ast.Field(chain=["events", "person_id"])],
- )
-
- def _build_person_arrays_select(self, date_range: QueryDateRange) -> ast.SelectQuery:
- """(C) One row per converting person: its conversions, plus a deduped touchpoint set.
-
- Both arrays hold (timestamp, payload) tuples rather than parallel arrays indexed together, since
- `groupArray` gives no ordering guarantee and separate arrays could pair one conversion's timestamp
- with another's value.
-
- The `-If` combinators only append when the row qualifies, so neither array grows with the
- person's unrelated events. `groupUniqArray` additionally collapses every pageview in a session to
- one touchpoint during aggregation.
- """
- # Bounded to the display range, not the lookback-extended range the outer WHERE allows. The
- # pageview branch of that WHERE reaches back a further lookback window to collect touchpoints, and
- # without this bound every conversion in that older stretch would be credited too: the table would
- # silently report a range far longer than the one asked for, and the extra conversions would mostly
- # land as unattributed because touchpoint collection doesn't reach back a window before *them*.
- conversions: ast.Expr = ast.Call(
- name="groupArrayIf",
- args=[
- ast.Tuple(
- exprs=[
- ast.Call(name="toUnixTimestamp", args=[ast.Field(chain=["events", "timestamp"])]),
- self._conversion_value_expr(),
- ]
- ),
- ast.And(
- exprs=[
- self.conversion_condition,
- *self._get_where_conditions(date_range, date_field="events.timestamp"),
- ]
- ),
- ],
- )
-
- # Sorted before truncating: `groupUniqArray` is hash-backed, so its order is unrelated to time and
- # slicing it raw would keep an arbitrary subset. The negative offset takes the tail of the sorted
- # array, i.e. the most recent sessions — see MAX_TOUCHPOINTS_PER_PERSON for why that direction.
- touchpoints = ast.Call(
- name="arraySlice",
- args=[
- ast.Call(
- name="arraySort",
- args=[
- ast.Call(
- name="groupUniqArrayIf",
- args=[
- ast.Tuple(
- exprs=[
- ast.Call(
- name="toUnixTimestamp",
- args=[ast.Field(chain=["events", "session", "$start_timestamp"])],
- ),
- self._breakdown_expr(),
- ]
- ),
- self._touchpoint_condition(),
- ],
- )
- ],
- ),
- ast.Constant(value=-MAX_TOUCHPOINTS_PER_PERSON),
- ],
- )
-
- if not self.allows_multiple_conversions_per_visitor:
- # One conversion per person: keep the earliest in the window, so the models attribute the
- # journey that led to them first converting rather than an arbitrary later repeat.
- conversions = ast.Call(
- name="arraySlice",
- args=[
- ast.Call(name="arraySort", args=[conversions]),
- ast.Constant(value=1),
- ast.Constant(value=1),
- ],
- )
-
- return ast.SelectQuery(
- select=[
- ast.Field(chain=["events", "person_id"]),
- ast.Alias(alias="conversions", expr=conversions),
- ast.Alias(alias="touchpoints", expr=touchpoints),
- ],
- select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),
- where=ast.And(
- exprs=[
- ast.CompareOperation(
- left=ast.Field(chain=["events", "person_id"]),
- op=ast.CompareOperationOp.In,
- right=self._build_converters_select(date_range),
- ),
- ast.Or(
- exprs=[
- ast.And(
- exprs=[
- self.conversion_condition,
- *self._get_where_conditions(date_range, date_field="events.timestamp"),
- ]
- ),
- ast.And(
- exprs=[
- self._pageview_condition(),
- *self._lookback_date_conditions(date_range),
- ]
- ),
- ]
- ),
- ]
- ),
- group_by=[ast.Field(chain=["events", "person_id"])],
- having=ast.CompareOperation(
- left=ast.Call(name="length", args=[ast.Field(chain=["conversions"])]),
- op=ast.CompareOperationOp.Gt,
- right=ast.Constant(value=0),
- ),
- )
-
- def _pageview_condition(self) -> ast.Expr:
- return ast.CompareOperation(
- left=ast.Field(chain=["events", "event"]),
- op=ast.CompareOperationOp.Eq,
- right=ast.Constant(value="$pageview"),
- )
-
- def _touchpoint_condition(self) -> ast.Expr:
- """A pageview inside a real session counts as a touchpoint.
-
- When direct traffic is excluded, drop it here — before the weights are computed — so the
- remaining touchpoints renormalize to full credit instead of quietly losing direct's share.
- """
- conditions: list[ast.Expr] = [
- self._pageview_condition(),
- ast.Call(name="notEmpty", args=[ast.Field(chain=["events", "$session_id"])]),
- # A session id that resolves to no session row yields epoch zero rather than null, because the
- # join fills a non-nullable column with its default. Test for a real timestamp rather than for
- # null: 1970 can never satisfy the attribution window, so such a touchpoint earns nothing, and
- # left in place it would sort to the very front and consume truncation slots. When a
- # conversion's own session is one of these, dropping it here is what keeps the conversion out
- # of the attributed count instead of silently crediting nobody.
- ast.CompareOperation(
- left=ast.Call(
- name="toUnixTimestamp", args=[ast.Field(chain=["events", "session", "$start_timestamp"])]
- ),
- op=ast.CompareOperationOp.Gt,
- right=ast.Constant(value=0),
- ),
- ]
- if self.query.excludeDirectTraffic:
- conditions.append(
- ast.CompareOperation(
- left=ast.Field(chain=["events", "session", "$channel_type"]),
- op=ast.CompareOperationOp.NotEq,
- right=ast.Constant(value="Direct"),
- )
- )
- return ast.And(exprs=conditions)
-
- def _lookback_date_conditions(self, date_range: QueryDateRange) -> list[ast.Expr]:
- """Pageview bounds extended back by the attribution window, so touches that predate the
- display range can still be credited for a conversion inside it."""
- return [
- ast.CompareOperation(
- left=ast.Field(chain=["events", "timestamp"]),
- op=ast.CompareOperationOp.GtEq,
- right=ast.ArithmeticOperation(
- left=ast.Call(name="toDateTime", args=[ast.Constant(value=date_range.date_from_str)]),
- op=ast.ArithmeticOperationOp.Sub,
- right=ast.Call(name="toIntervalSecond", args=[ast.Constant(value=self.attribution_window_seconds)]),
- ),
- ),
- ast.CompareOperation(
- left=ast.Field(chain=["events", "timestamp"]),
- op=ast.CompareOperationOp.LtEq,
- right=ast.Call(name="toDateTime", args=[ast.Constant(value=date_range.date_to_str)]),
- ),
- ]
-
def _build_per_conversion_select(self) -> ast.SelectQuery:
"""(D) One row per conversion, carrying all five weight arrays.
@@ -514,33 +131,7 @@ class MarketingAnalyticsAttributionQueryRunner(
conversion_time = ast.Field(chain=["conversion_time"])
ts = ast.Field(chain=["touch_ts"])
- in_window = ast.Call(
- name="arrayFilter",
- args=[
- ast.Lambda(
- args=["t"],
- expr=ast.And(
- exprs=[
- ast.CompareOperation(
- left=ast.TupleAccess(tuple=ast.Field(chain=["t"]), index=1),
- op=ast.CompareOperationOp.LtEq,
- right=conversion_time,
- ),
- ast.CompareOperation(
- left=ast.TupleAccess(tuple=ast.Field(chain=["t"]), index=1),
- op=ast.CompareOperationOp.GtEq,
- right=ast.ArithmeticOperation(
- left=conversion_time,
- op=ast.ArithmeticOperationOp.Sub,
- right=ast.Constant(value=self.attribution_window_seconds),
- ),
- ),
- ]
- ),
- ),
- ast.Field(chain=["touchpoints"]),
- ],
- )
+ in_window = self._in_window_touchpoints_expr(conversion_time)
conversion = ast.ArrayAccess(
array=ast.Field(chain=["conversions"]), property=ast.Field(chain=[_CONVERSION_INDEX])
@@ -590,7 +181,7 @@ class MarketingAnalyticsAttributionQueryRunner(
return ast.SelectQuery(
select=select,
- select_from=ast.JoinExpr(table=ast.Field(chain=[_PERSON_ARRAYS_CTE])),
+ select_from=ast.JoinExpr(table=ast.Field(chain=[PERSON_ARRAYS_CTE])),
array_join_op="ARRAY JOIN",
array_join_list=[
ast.Alias(
@@ -694,8 +285,8 @@ class MarketingAnalyticsAttributionQueryRunner(
with self.timings.measure("attribution_reach_cte"):
ctes[_REACH_CTE] = ast.CTE(name=_REACH_CTE, expr=self._build_reach_select(date_range), cte_type="subquery")
with self.timings.measure("attribution_person_arrays_cte"):
- ctes[_PERSON_ARRAYS_CTE] = ast.CTE(
- name=_PERSON_ARRAYS_CTE,
+ ctes[PERSON_ARRAYS_CTE] = ast.CTE(
+ name=PERSON_ARRAYS_CTE,
expr=self._build_person_arrays_select(date_range),
cte_type="subquery",
)
@@ -950,11 +541,3 @@ class MarketingAnalyticsAttributionQueryRunner(
influencedValue=float(row.get(_INFLUENCED_VALUE) or 0.0) if has_value else None,
models=models,
)
-
- def _build_main_select_query(self, conversion_aggregator) -> ast.SelectQuery:
- """Not part of this runner's shape.
-
- The base hook exists to slot a SELECT into its ad-cost-joined table query; this runner overrides
- `to_query` wholesale and builds its own CTE chain, so there is nothing to hook.
- """
- raise NotImplementedError("MarketingAnalyticsAttributionQueryRunner builds its query in to_query")
diff --git a/products/marketing_analytics/backend/hogql_queries/constants.py b/products/marketing_analytics/backend/hogql_queries/constants.py
index 010725fb19f8..d0380f04fcc2 100644
--- a/products/marketing_analytics/backend/hogql_queries/constants.py
+++ b/products/marketing_analytics/backend/hogql_queries/constants.py
@@ -104,6 +104,12 @@ SESSIONS_COLUMN_ALIAS = "Sessions"
# enum so the sides can't drift apart and split one row in two.
UNKNOWN_CHANNEL = DefaultChannelTypes.UNKNOWN.value
+# What `$entry_referring_domain` holds when a session arrived with no referrer at all. Stored as a
+# sentinel rather than an empty string, so anything asking "does this session name a referrer?" has
+# to test for it explicitly. Matches the literal the channel-type classifier keys off in
+# posthog/hogql/database/schema/channel_type.py.
+DIRECT_REFERRING_DOMAIN = "$direct"
+
# Field used for joining with conversion goals
MATCH_KEY_FIELD = "match_key"
diff --git a/products/marketing_analytics/backend/hogql_queries/test_attribution_paths_query_runner.py b/products/marketing_analytics/backend/hogql_queries/test_attribution_paths_query_runner.py
new file mode 100644
index 000000000000..25c0a2c4a1d1
--- /dev/null
+++ b/products/marketing_analytics/backend/hogql_queries/test_attribution_paths_query_runner.py
@@ -0,0 +1,397 @@
+from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
+
+from posthog.schema import (
+ BaseMathType,
+ ConversionGoalFilter1,
+ DateRange,
+ MarketingAnalyticsAttributionBreakdown,
+ MarketingAnalyticsAttributionPathsQuery,
+ PropertyMathType,
+)
+
+from posthog.models.utils import uuid7
+from posthog.test.persons import create_person
+
+from products.marketing_analytics.backend.hogql_queries.attribution_paths_query_runner import (
+ PATH_MAX_LENGTH,
+ MarketingAnalyticsAttributionPathsQueryRunner,
+)
+
+GOAL_ID = "goal-1"
+CONVERSION_EVENT = "purchase"
+WINDOW_DAYS = 4
+
+CONVERSION_AT = "2023-01-10T12:00:00Z"
+ONE_DAY_BEFORE = "2023-01-09T12:00:00Z"
+TWO_DAYS_BEFORE = "2023-01-08T12:00:00Z"
+THREE_DAYS_BEFORE = "2023-01-07T12:00:00Z"
+
+
+class TestMarketingAnalyticsAttributionPathsQueryRunner(ClickhouseTestMixin, BaseTest):
+ maxDiff = None
+ CLASS_DATA_LEVEL_SETUP = False
+
+ def setUp(self):
+ super().setUp()
+ self._configure_goal()
+
+ def _configure_goal(
+ self,
+ *,
+ counts_as_revenue: bool = True,
+ math: PropertyMathType | BaseMathType = PropertyMathType.SUM,
+ math_property: str | None = "revenue",
+ ) -> None:
+ config = self.team.marketing_analytics_config
+ config.attribution_window_days = WINDOW_DAYS
+ config.conversion_goals = [
+ ConversionGoalFilter1(
+ kind="EventsNode",
+ event=CONVERSION_EVENT,
+ name="Purchases",
+ conversion_goal_id=GOAL_ID,
+ conversion_goal_name="Purchases",
+ schema_map={},
+ math=math,
+ math_property=math_property,
+ counts_as_revenue=counts_as_revenue,
+ ).model_dump()
+ ]
+ config.save()
+
+ def _session(
+ self,
+ distinct_id: str,
+ started_at: str,
+ *,
+ utm_campaign: str | None = None,
+ utm_source: str | None = None,
+ utm_medium: str | None = None,
+ referring_domain: str = "$direct",
+ ) -> None:
+ """One session's worth of pageviews — same fixture semantics as the attribution table tests:
+ uuid7 seeds the session id so `$start_timestamp` lands on `started_at`, and `$referring_domain`
+ defaults to the `$direct` sentinel so untagged sessions classify as Direct."""
+ session_id = str(uuid7(started_at))
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id=distinct_id,
+ timestamp=started_at,
+ properties={
+ "$session_id": session_id,
+ "$current_url": "https://example.com/",
+ "$pathname": "/",
+ "$referring_domain": referring_domain,
+ **({"utm_campaign": utm_campaign} if utm_campaign else {}),
+ **({"utm_source": utm_source} if utm_source else {}),
+ **({"utm_medium": utm_medium} if utm_medium else {}),
+ },
+ )
+
+ def _conversion(self, distinct_id: str, at: str, revenue: float = 100.0) -> None:
+ _create_event(
+ team=self.team,
+ event=CONVERSION_EVENT,
+ distinct_id=distinct_id,
+ timestamp=at,
+ properties={"revenue": revenue},
+ )
+
+ def _run(
+ self,
+ breakdown: MarketingAnalyticsAttributionBreakdown = MarketingAnalyticsAttributionBreakdown.SOURCE,
+ *,
+ exclude_direct: bool = False,
+ exclude_unattributed: bool = False,
+ date_from: str = "2023-01-01",
+ date_to: str = "2023-01-31",
+ lookback_days: int | None = None,
+ allow_multiple_conversions: bool | None = None,
+ min_touchpoints: int | None = None,
+ max_touchpoints: int | None = None,
+ limit: int | None = None,
+ ):
+ flush_persons_and_events()
+ query = MarketingAnalyticsAttributionPathsQuery(
+ dateRange=DateRange(date_from=date_from, date_to=date_to),
+ breakdownBy=breakdown,
+ conversionGoalId=GOAL_ID,
+ excludeDirectTraffic=exclude_direct,
+ excludeUnattributed=exclude_unattributed,
+ lookbackWindowDays=lookback_days,
+ allowMultipleConversionsPerVisitor=allow_multiple_conversions,
+ minTouchpoints=min_touchpoints,
+ maxTouchpoints=max_touchpoints,
+ limit=limit,
+ properties=[],
+ )
+ return MarketingAnalyticsAttributionPathsQueryRunner(query=query, team=self.team).calculate()
+
+ @staticmethod
+ def _paths(response) -> dict[tuple[str, ...], int]:
+ """{path: conversions} — the shape most assertions need."""
+ return {tuple(row.path): row.conversions for row in response.results}
+
+ def test_single_touch_journey_is_a_one_step_path(self):
+ create_person(team=self.team, distinct_ids=["p1"])
+ self._session("p1", ONE_DAY_BEFORE, utm_source="google")
+ self._conversion("p1", CONVERSION_AT)
+
+ response = self._run()
+
+ self.assertEqual(self._paths(response), {("google",): 1})
+ self.assertEqual(response.totalConversions, 1)
+ self.assertEqual(response.attributedConversions, 1)
+ self.assertFalse(response.results[0].pathTruncated)
+
+ def test_touchpoints_appear_in_time_order(self):
+ # The person visited via google two days out and newsletter one day out, so the path must read
+ # google -> newsletter regardless of what order ClickHouse aggregated the rows in.
+ create_person(team=self.team, distinct_ids=["p1"])
+ self._session("p1", TWO_DAYS_BEFORE, utm_source="google")
+ self._session("p1", ONE_DAY_BEFORE, utm_source="newsletter")
+ self._conversion("p1", CONVERSION_AT)
+
+ response = self._run()
+
+ self.assertEqual(self._paths(response), {("google", "newsletter"): 1})
+
+ def test_consecutive_repeats_are_preserved_not_collapsed(self):
+ # Two google sessions then a conversion is a different journey than one google session, and the
+ # two must group separately. Collapsing repeats to "×2" is the frontend's display concern.
+ create_person(team=self.team, distinct_ids=["p1", "p2"])
+ create_person(team=self.team, distinct_ids=["q1"])
+ self._session("p1", TWO_DAYS_BEFORE, utm_source="google")
+ self._session("p1", ONE_DAY_BEFORE, utm_source="google")
+ self._conversion("p1", CONVERSION_AT)
+ self._session("q1", ONE_DAY_BEFORE, utm_source="google")
+ self._conversion("q1", CONVERSION_AT)
+
+ paths = self._paths(self._run())
+
+ self.assertEqual(paths, {("google", "google"): 1, ("google",): 1})
+
+ def test_identical_paths_group_and_rank_by_conversions(self):
+ # Two people with the same journey outrank one person with a different one, and the response
+ # comes back ranked most to least.
+ for person, source in [("p1", "google"), ("p2", "google"), ("p3", "bing")]:
+ create_person(team=self.team, distinct_ids=[person])
+ self._session(person, ONE_DAY_BEFORE, utm_source=source)
+ self._conversion(person, CONVERSION_AT)
+
+ response = self._run()
+
+ self.assertEqual([tuple(row.path) for row in response.results], [("google",), ("bing",)])
+ self.assertEqual(self._paths(response), {("google",): 2, ("bing",): 1})
+
+ def test_touchpoint_count_filter_selects_exact_lengths(self):
+ # p1 has a 1-touch journey, p2 a 2-touch one. The filter works on journey length, and the
+ # footer's denominator ignores it so shares stay comparable across filter values.
+ create_person(team=self.team, distinct_ids=["p1"])
+ create_person(team=self.team, distinct_ids=["p2"])
+ self._session("p1", ONE_DAY_BEFORE, utm_source="google")
+ self._conversion("p1", CONVERSION_AT)
+ self._session("p2", TWO_DAYS_BEFORE, utm_source="bing")
+ self._session("p2", ONE_DAY_BEFORE, utm_source="newsletter")
+ self._conversion("p2", CONVERSION_AT)
+
+ exactly_two = self._run(min_touchpoints=2, max_touchpoints=2)
+
+ self.assertEqual(self._paths(exactly_two), {("bing", "newsletter"): 1})
+ self.assertEqual(exactly_two.totalConversions, 2)
+ self.assertEqual(exactly_two.attributedConversions, 2)
+
+ def test_open_ended_minimum_keeps_longer_paths(self):
+ create_person(team=self.team, distinct_ids=["p1"])
+ create_person(team=self.team, distinct_ids=["p2"])
+ self._session("p1", ONE_DAY_BEFORE, utm_source="google")
+ self._conversion("p1", CONVERSION_AT)
+ for started_at, source in [
+ (THREE_DAYS_BEFORE, "bing"),
+ (TWO_DAYS_BEFORE, "google"),
+ (ONE_DAY_BEFORE, "newsletter"),
+ ]:
+ self._session("p2", started_at, utm_source=source)
+ self._conversion("p2", CONVERSION_AT)
+
+ response = self._run(min_touchpoints=2)
+
+ self.assertEqual(self._paths(response), {("bing", "google", "newsletter"): 1})
+
+ def test_invalid_touchpoint_bounds_are_rejected(self):
+ with self.assertRaises(ValueError):
+ self._run(min_touchpoints=0)
+ with self.assertRaises(ValueError):
+ self._run(min_touchpoints=3, max_touchpoints=2)
+
+ def test_excluding_direct_drops_direct_steps_from_the_path(self):
+ # The journey was google -> Direct -> conversion; with the exclusion the Direct step must
+ # disappear from the middle of the path, not just from a standalone row.
+ create_person(team=self.team, distinct_ids=["p1"])
+ self._session("p1", TWO_DAYS_BEFORE, utm_source="google", utm_medium="cpc")
+ self._session("p1", ONE_DAY_BEFORE) # Direct
+ self._conversion("p1", CONVERSION_AT)
+
+ with_direct = self._paths(self._run(MarketingAnalyticsAttributionBreakdown.CHANNEL))
+ self.assertEqual(len(with_direct), 1)
+ (path,) = with_direct
+ self.assertEqual(path[-1], "Direct")
+
+ without_direct = self._paths(self._run(MarketingAnalyticsAttributionBreakdown.CHANNEL, exclude_direct=True))
+ self.assertEqual(len(without_direct), 1)
+ (path,) = without_direct
+ self.assertEqual(len(path), 1)
+ self.assertNotIn("Direct", path)
+
+ def test_excluding_unattributed_drops_none_steps_from_the_path(self):
+ # Campaign breakdown: the untagged session renders as a "" step; excluded, the path shrinks to
+ # the tagged touch alone.
+ create_person(team=self.team, distinct_ids=["p1"])
+ self._session("p1", TWO_DAYS_BEFORE, utm_campaign="summer")
+ self._session("p1", ONE_DAY_BEFORE) # no utm_campaign
+ self._conversion("p1", CONVERSION_AT)
+
+ with_none = self._paths(self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN))
+ self.assertEqual(with_none, {("summer", ""): 1})
+
+ without_none = self._paths(
+ self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN, exclude_unattributed=True)
+ )
+ self.assertEqual(without_none, {("summer",): 1})
+
+ def test_campaign_name_mappings_collapse_dirty_spellings_into_one_step_label(self):
+ # Two spellings of one campaign are still two visits, so the path keeps two steps — but both must
+ # carry the mapped name, which is what lets the UI collapse them into "Spring Sale 2026 x2"
+ # instead of the journey reading as one campaign handing off to another.
+ config = self.team.marketing_analytics_config
+ config.campaign_name_mappings = {"GoogleAds": {"Spring Sale 2026": ["spring_sale_2026", "spring-sale-2026"]}}
+ config.save()
+
+ create_person(team=self.team, distinct_ids=["p1"])
+ self._session("p1", TWO_DAYS_BEFORE, utm_source="google", utm_campaign="spring_sale_2026")
+ self._session("p1", ONE_DAY_BEFORE, utm_source="google", utm_campaign="spring-sale-2026")
+ self._conversion("p1", CONVERSION_AT)
+
+ paths = self._paths(self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN))
+
+ self.assertEqual(paths, {("Spring Sale 2026", "Spring Sale 2026"): 1})
+
+ def test_excluding_unattributed_drops_organic_steps_from_the_path(self):
+ # Source breakdown, where the untagged step renders as "organic" rather than "". The paths section
+ # has to drop exactly what the table above it drops, or a journey shown here would contradict the
+ # weights shown there — which is the whole point of both surfaces sharing one touchpoint definition.
+ create_person(team=self.team, distinct_ids=["p1"])
+ self._session("p1", TWO_DAYS_BEFORE, utm_source="google")
+ self._session("p1", ONE_DAY_BEFORE) # no utm_source -> displayed as "organic"
+ self._conversion("p1", CONVERSION_AT)
+
+ with_organic = self._paths(self._run(MarketingAnalyticsAttributionBreakdown.SOURCE))
+ self.assertEqual(with_organic, {("google", "organic"): 1})
+
+ without_organic = self._paths(
+ self._run(MarketingAnalyticsAttributionBreakdown.SOURCE, exclude_unattributed=True)
+ )
+ self.assertEqual(without_organic, {("google",): 1})
+
+ def test_long_journeys_group_on_their_most_recent_steps(self):
+ # 12 sessions land within the window (hourly, so each is its own touchpoint); the path keeps the
+ # most recent PATH_MAX_LENGTH steps and flags the truncation.
+ create_person(team=self.team, distinct_ids=["p1"])
+ for hour in range(12):
+ self._session("p1", f"2023-01-10T{hour:02d}:30:00Z", utm_source=f"source_{hour}")
+ self._conversion("p1", "2023-01-10T23:00:00Z")
+
+ response = self._run()
+
+ self.assertEqual(len(response.results), 1)
+ row = response.results[0]
+ self.assertEqual(len(row.path), PATH_MAX_LENGTH)
+ self.assertEqual(row.path, [f"source_{hour}" for hour in range(2, 12)])
+ self.assertTrue(row.pathTruncated)
+
+ def test_touches_outside_the_window_are_not_part_of_the_path(self):
+ # WINDOW_DAYS is 4: a touch five days before the conversion belongs to no journey, and a
+ # conversion whose only touch is out-of-window counts as total but not attributed.
+ create_person(team=self.team, distinct_ids=["p1"])
+ create_person(team=self.team, distinct_ids=["p2"])
+ self._session("p1", "2023-01-05T12:00:00Z", utm_source="forgotten") # 5 days out
+ self._session("p1", ONE_DAY_BEFORE, utm_source="google")
+ self._conversion("p1", CONVERSION_AT)
+ self._session("p2", "2023-01-05T12:00:00Z", utm_source="forgotten")
+ self._conversion("p2", CONVERSION_AT)
+
+ response = self._run()
+
+ self.assertEqual(self._paths(response), {("google",): 1})
+ self.assertEqual(response.totalConversions, 2)
+ self.assertEqual(response.attributedConversions, 1)
+
+ def test_one_conversion_per_visitor_keeps_the_first_journey(self):
+ # With repeats disallowed, only the journey up to the person's first conversion counts: one
+ # path, ending at the google touch, even though a newsletter touch preceded the second purchase.
+ create_person(team=self.team, distinct_ids=["p1"])
+ self._session("p1", TWO_DAYS_BEFORE, utm_source="google")
+ self._conversion("p1", CONVERSION_AT)
+ self._session("p1", "2023-01-11T12:00:00Z", utm_source="newsletter")
+ self._conversion("p1", "2023-01-12T12:00:00Z")
+
+ response = self._run(allow_multiple_conversions=False)
+
+ self.assertEqual(self._paths(response), {("google",): 1})
+ self.assertEqual(response.totalConversions, 1)
+
+ def test_revenue_goal_sums_conversion_value_per_path(self):
+ create_person(team=self.team, distinct_ids=["p1"])
+ create_person(team=self.team, distinct_ids=["p2"])
+ for person, revenue in [("p1", 100.0), ("p2", 50.0)]:
+ self._session(person, ONE_DAY_BEFORE, utm_source="google")
+ self._conversion(person, CONVERSION_AT, revenue=revenue)
+
+ response = self._run()
+
+ self.assertTrue(response.hasValue)
+ self.assertEqual(response.results[0].conversionValue, 150.0)
+
+ def test_non_revenue_goal_reports_no_value(self):
+ self._configure_goal(counts_as_revenue=False, math=BaseMathType.TOTAL, math_property=None)
+ create_person(team=self.team, distinct_ids=["p1"])
+ self._session("p1", ONE_DAY_BEFORE, utm_source="google")
+ self._conversion("p1", CONVERSION_AT)
+
+ response = self._run()
+
+ self.assertFalse(response.hasValue)
+ self.assertIsNone(response.results[0].conversionValue)
+
+ def test_limit_marks_has_more(self):
+ for i in range(3):
+ person = f"p{i}"
+ create_person(team=self.team, distinct_ids=[person])
+ self._session(person, ONE_DAY_BEFORE, utm_source=f"source_{i}")
+ self._conversion(person, CONVERSION_AT)
+
+ response = self._run(limit=2)
+
+ self.assertEqual(len(response.results), 2)
+ self.assertTrue(response.hasMore)
+ self.assertEqual(response.totalConversions, 3)
+
+ def test_per_conversion_path_is_materialized_for_its_two_readers(self):
+ # path_rows and the footer both read per_conversion_path; without materialization ClickHouse
+ # would run the events scan underneath it twice.
+ create_person(team=self.team, distinct_ids=["p1"])
+ self._session("p1", ONE_DAY_BEFORE, utm_source="google")
+ self._conversion("p1", CONVERSION_AT)
+ flush_persons_and_events()
+
+ query = MarketingAnalyticsAttributionPathsQuery(
+ dateRange=DateRange(date_from="2023-01-01", date_to="2023-01-31"),
+ conversionGoalId=GOAL_ID,
+ properties=[],
+ )
+ runner = MarketingAnalyticsAttributionPathsQueryRunner(query=query, team=self.team)
+
+ ctes = runner.to_query().ctes
+ assert ctes is not None
+ self.assertTrue(ctes["per_conversion_path"].materialized)
diff --git a/products/marketing_analytics/backend/hogql_queries/test_attribution_table_query_runner.py b/products/marketing_analytics/backend/hogql_queries/test_attribution_table_query_runner.py
index 3f99b7be92f1..c14352c15165 100644
--- a/products/marketing_analytics/backend/hogql_queries/test_attribution_table_query_runner.py
+++ b/products/marketing_analytics/backend/hogql_queries/test_attribution_table_query_runner.py
@@ -83,7 +83,7 @@ class TestMarketingAnalyticsAttributionQueryRunner(ClickhouseTestMixin, BaseTest
utm_campaign: str | None = None,
utm_source: str | None = None,
utm_medium: str | None = None,
- referring_domain: str = "$direct",
+ referring_domain: str | None = "$direct",
pageviews: int = 1,
) -> None:
"""One session's worth of pageviews. uuid7 seeds the session id so `$start_timestamp` lands on
@@ -101,7 +101,7 @@ class TestMarketingAnalyticsAttributionQueryRunner(ClickhouseTestMixin, BaseTest
"$session_id": session_id,
"$current_url": "https://example.com/",
"$pathname": "/",
- "$referring_domain": referring_domain,
+ **({"$referring_domain": referring_domain} if referring_domain is not None else {}),
**({"utm_campaign": utm_campaign} if utm_campaign else {}),
**({"utm_source": utm_source} if utm_source else {}),
**({"utm_medium": utm_medium} if utm_medium else {}),
@@ -122,6 +122,7 @@ class TestMarketingAnalyticsAttributionQueryRunner(ClickhouseTestMixin, BaseTest
breakdown: MarketingAnalyticsAttributionBreakdown,
*,
exclude_direct: bool = False,
+ exclude_unattributed: bool = False,
date_from: str = "2023-01-01",
date_to: str = "2023-01-31",
lookback_days: int | None = None,
@@ -133,6 +134,7 @@ class TestMarketingAnalyticsAttributionQueryRunner(ClickhouseTestMixin, BaseTest
breakdownBy=breakdown,
conversionGoalId=GOAL_ID,
excludeDirectTraffic=exclude_direct,
+ excludeUnattributed=exclude_unattributed,
lookbackWindowDays=lookback_days,
allowMultipleConversionsPerVisitor=allow_multiple_conversions,
properties=[],
@@ -375,6 +377,159 @@ class TestMarketingAnalyticsAttributionQueryRunner(ClickhouseTestMixin, BaseTest
self.assertNotIn("Direct", without_direct)
self.assertAlmostEqual(without_direct[paid_channel][AttributionMode.LINEAR], 1.0, places=4)
+ def test_excluding_unattributed_redistributes_the_none_rows_credit(self):
+ # Same before-the-weights placement as the direct exclusion, judged on the breakdown's raw
+ # session field: a session with no utm_campaign renders as the "(none)" row, and excluding it
+ # hands its share to the campaigns that were actually tagged.
+ create_person(team=self.team, distinct_ids=["p1"])
+ self._session("p1", TWO_DAYS_BEFORE, utm_campaign="summer")
+ self._session("p1", ONE_DAY_BEFORE) # no utm_campaign -> the "(none)" row
+ self._conversion("p1", CONVERSION_AT)
+
+ with_none = self._by_breakdown(self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN))
+ self.assertIn("", with_none)
+ self.assertAlmostEqual(with_none["summer"][AttributionMode.LINEAR], 0.5, places=4)
+
+ without_none = self._by_breakdown(
+ self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN, exclude_unattributed=True)
+ )
+ self.assertNotIn("", without_none)
+ self.assertAlmostEqual(without_none["summer"][AttributionMode.LINEAR], 1.0, places=4)
+
+ def test_excluding_unattributed_drops_unknown_channels(self):
+ # Channel is special-cased: the classifier's raw value can literally be "Unknown" (a session with
+ # no referrer sentinel at all), which must be treated as unattributed alongside empty values.
+ create_person(team=self.team, distinct_ids=["p1"])
+ self._session("p1", TWO_DAYS_BEFORE, utm_source="google", utm_medium="cpc")
+ self._session("p1", ONE_DAY_BEFORE, referring_domain=None) # unclassifiable -> Unknown
+ self._conversion("p1", CONVERSION_AT)
+
+ with_unknown = self._by_breakdown(self._run(MarketingAnalyticsAttributionBreakdown.CHANNEL))
+ self.assertIn("Unknown", with_unknown)
+ paid_channel = next(channel for channel in with_unknown if channel != "Unknown")
+ self.assertAlmostEqual(with_unknown[paid_channel][AttributionMode.LINEAR], 0.5, places=4)
+
+ without_unknown = self._by_breakdown(
+ self._run(MarketingAnalyticsAttributionBreakdown.CHANNEL, exclude_unattributed=True)
+ )
+ self.assertNotIn("Unknown", without_unknown)
+ self.assertAlmostEqual(without_unknown[paid_channel][AttributionMode.LINEAR], 1.0, places=4)
+
+ def test_campaign_name_mappings_collapse_dirty_utm_spellings(self):
+ # The team's own mapping says these two spellings are one campaign, and the Dashboard reports
+ # them as one. Left unmapped here, each spelling is its own row and the models credit them
+ # independently — first touch names one spelling, last touch the other — so the model comparison
+ # this table exists for would read as a difference between campaigns that are the same campaign.
+ config = self.team.marketing_analytics_config
+ config.campaign_name_mappings = {"GoogleAds": {"Spring Sale 2026": ["spring_sale_2026", "spring-sale-2026"]}}
+ config.save()
+
+ create_person(team=self.team, distinct_ids=["p1"])
+ self._session("p1", TWO_DAYS_BEFORE, utm_source="google", utm_campaign="spring_sale_2026")
+ self._session("p1", ONE_DAY_BEFORE, utm_source="google", utm_campaign="spring-sale-2026")
+ self._conversion("p1", CONVERSION_AT)
+
+ rows = self._by_breakdown(self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN))
+
+ self.assertEqual(list(rows), ["Spring Sale 2026"])
+ # One campaign touched twice holds the whole conversion under every model.
+ for model in [AttributionMode.FIRST_TOUCH, AttributionMode.LAST_TOUCH, AttributionMode.LINEAR]:
+ self.assertAlmostEqual(rows["Spring Sale 2026"][model], 1.0, places=4)
+
+ def test_campaign_name_mappings_are_scoped_to_the_mapped_integration(self):
+ # The mapping keys off the touchpoint's source, so the same spelling arriving on a source that
+ # doesn't belong to the mapped integration must stay as it came.
+ config = self.team.marketing_analytics_config
+ config.campaign_name_mappings = {"GoogleAds": {"Spring Sale 2026": ["spring_sale_2026"]}}
+ config.save()
+
+ create_person(team=self.team, distinct_ids=["p1"])
+ self._session("p1", TWO_DAYS_BEFORE, utm_source="google", utm_campaign="spring_sale_2026")
+ self._session("p1", ONE_DAY_BEFORE, utm_source="newsletter", utm_campaign="spring_sale_2026")
+ self._conversion("p1", CONVERSION_AT)
+
+ rows = self._by_breakdown(self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN))
+
+ self.assertEqual(sorted(rows), ["Spring Sale 2026", "spring_sale_2026"])
+
+ def test_campaign_id_matching_preference_leaves_the_displayed_campaign_raw(self):
+ # With match_field=campaign_id the mapping's clean_name is an *id*, which the Dashboard uses to
+ # find the cost row while leaving the displayed campaign name untouched. There is no cost join
+ # here, so applying it would put a bare id in the campaign column.
+ config = self.team.marketing_analytics_config
+ config.campaign_name_mappings = {"GoogleAds": {"10042": ["spring_sale_2026"]}}
+ config.campaign_field_preferences = {"GoogleAds": {"match_field": "campaign_id"}}
+ config.save()
+
+ create_person(team=self.team, distinct_ids=["p1"])
+ self._session("p1", ONE_DAY_BEFORE, utm_source="google", utm_campaign="spring_sale_2026")
+ self._conversion("p1", CONVERSION_AT)
+
+ rows = self._by_breakdown(self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN))
+
+ self.assertEqual(list(rows), ["spring_sale_2026"])
+
+ def test_an_empty_campaign_is_never_mapped_onto_a_real_name(self):
+ # Nothing stops a team listing "" among a campaign's raw values, but an empty utm_campaign is the
+ # absence of a campaign rather than a misspelling of one. Mapping it would invent attribution and
+ # would leave "Exclude unattributed traffic" dropping a row labelled like a campaign that stayed.
+ config = self.team.marketing_analytics_config
+ config.campaign_name_mappings = {"GoogleAds": {"Spring Sale 2026": ["", "spring_sale_2026"]}}
+ config.save()
+
+ create_person(team=self.team, distinct_ids=["p1"])
+ self._session("p1", TWO_DAYS_BEFORE, utm_source="google", utm_campaign="spring_sale_2026")
+ self._session("p1", ONE_DAY_BEFORE, utm_source="google") # no utm_campaign
+ self._conversion("p1", CONVERSION_AT)
+
+ rows = self._by_breakdown(self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN))
+ self.assertEqual(sorted(rows), ["", "Spring Sale 2026"])
+
+ # ...and it stays the row the exclusion drops.
+ excluded = self._by_breakdown(
+ self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN, exclude_unattributed=True)
+ )
+ self.assertEqual(list(excluded), ["Spring Sale 2026"])
+
+ def test_excluding_unattributed_drops_the_organic_source_row(self):
+ # Source is the breakdown where "unattributed" is easiest to get wrong: an empty utm_source is
+ # *displayed* as "organic", a real-looking name, so it renders nothing like the "(none)" row the
+ # other UTM breakdowns produce. It is still the absence of a source, so it goes — and the credit
+ # it held renormalizes onto the sources that were actually tagged.
+ create_person(team=self.team, distinct_ids=["p1"])
+ self._session("p1", TWO_DAYS_BEFORE, utm_source="google")
+ self._session("p1", ONE_DAY_BEFORE) # no utm_source -> displayed as "organic"
+ self._conversion("p1", CONVERSION_AT)
+
+ with_organic = self._by_breakdown(self._run(MarketingAnalyticsAttributionBreakdown.SOURCE))
+ self.assertIn("organic", with_organic)
+ self.assertAlmostEqual(with_organic["google"][AttributionMode.LINEAR], 0.5, places=4)
+
+ without_organic = self._by_breakdown(
+ self._run(MarketingAnalyticsAttributionBreakdown.SOURCE, exclude_unattributed=True)
+ )
+ self.assertNotIn("organic", without_organic)
+ self.assertAlmostEqual(without_organic["google"][AttributionMode.LINEAR], 1.0, places=4)
+
+ def test_excluding_unattributed_drops_the_direct_referring_domain_sentinel(self):
+ # `$entry_referring_domain` holds the "$direct" sentinel rather than an empty value when a session
+ # arrived with no referrer, so an emptiness test alone would leave a raw sentinel in the results
+ # as if it were a real referrer.
+ create_person(team=self.team, distinct_ids=["p1"])
+ self._session("p1", TWO_DAYS_BEFORE, referring_domain="google.com")
+ self._session("p1", ONE_DAY_BEFORE) # defaults to the "$direct" sentinel
+ self._conversion("p1", CONVERSION_AT)
+
+ with_direct = self._by_breakdown(self._run(MarketingAnalyticsAttributionBreakdown.REFERRING_DOMAIN))
+ self.assertIn("$direct", with_direct)
+ self.assertAlmostEqual(with_direct["google.com"][AttributionMode.LINEAR], 0.5, places=4)
+
+ without_direct = self._by_breakdown(
+ self._run(MarketingAnalyticsAttributionBreakdown.REFERRING_DOMAIN, exclude_unattributed=True)
+ )
+ self.assertNotIn("$direct", without_direct)
+ self.assertAlmostEqual(without_direct["google.com"][AttributionMode.LINEAR], 1.0, places=4)
+
def test_repeat_touches_on_one_dimension_sum_their_weight(self):
# A dimension touched on three of four sessions should hold 0.75 of the linear credit as one row,
# not appear three times at 0.25. Guards the weight roll-up in the same collapse as the influenced
diff --git a/products/marketing_analytics/backend/hogql_queries/utils.py b/products/marketing_analytics/backend/hogql_queries/utils.py
index 450dfdd7c8f6..dea06a0c4a94 100644
--- a/products/marketing_analytics/backend/hogql_queries/utils.py
+++ b/products/marketing_analytics/backend/hogql_queries/utils.py
@@ -47,6 +47,83 @@ def build_source_normalization_expr(source_expr: ast.Expr, source_mappings: dict
return normalized_expr
+def build_campaign_display_normalization_expr(
+ campaign_expr: ast.Expr,
+ source_expr: ast.Expr,
+ team_config: Any,
+) -> ast.Expr:
+ """Collapse a team's dirty UTM campaign spellings onto the clean name they're mapped to
+ ('spring-sale-2026' -> 'Spring Sale 2026'), case-insensitively and scoped to the integration
+ whose sources the touchpoint arrived on.
+
+ This is the *display* subset of what `ConversionGoalsAggregator._apply_campaign_name_mappings`
+ does. That one also maps utm_campaign onto campaign_id for sources configured to match on id,
+ because it has to line the label up with a cost row; there is no cost join here, so sources with
+ a `campaign_id` preference are skipped — their clean_name is an id, and the dashboard leaves the
+ displayed campaign name raw for them too. Kept as one place so a team's mappings can't mean two
+ different things depending on which surface is reading them.
+ """
+ from .adapters.factory import MarketingSourceFactory # noqa: PLC0415 — avoids an import cycle
+
+ campaign_mappings = team_config.campaign_name_mappings if team_config else {}
+ if not campaign_mappings:
+ return campaign_expr
+
+ preferences = team_config.campaign_field_preferences or {}
+ lowercase_campaign = ast.Call(name="lower", args=[campaign_expr])
+ lowercase_source = ast.Call(name="lower", args=[source_expr])
+ conditions: list[ast.Expr] = []
+
+ for integration, clean_name_to_raw_values in campaign_mappings.items():
+ if not clean_name_to_raw_values:
+ continue
+ if preferences.get(integration, {}).get("match_field", "campaign_name") == "campaign_id":
+ continue
+
+ adapter_class = MarketingSourceFactory._adapter_registry.get(integration)
+ if not adapter_class:
+ continue
+ utm_sources = [
+ s for alternatives in adapter_class.get_source_identifier_mapping().values() for s in alternatives
+ ]
+ if not utm_sources:
+ continue
+
+ source_condition = ast.Call(
+ name="in",
+ args=[lowercase_source, ast.Array(exprs=[ast.Constant(value=s.lower()) for s in utm_sources])],
+ )
+
+ for clean_name, raw_values in clean_name_to_raw_values.items():
+ # An empty utm_campaign is the absence of a campaign, not a misspelling of one: mapping it
+ # onto a real name would invent attribution, and would put a session that "Exclude
+ # unattributed traffic" drops under a label that looks like a campaign that stayed.
+ raw_values = [v for v in raw_values if v]
+ if not raw_values:
+ continue
+ conditions.append(
+ ast.Call(
+ name="and",
+ args=[
+ source_condition,
+ ast.Call(
+ name="in",
+ args=[
+ lowercase_campaign,
+ ast.Array(exprs=[ast.Constant(value=v.lower()) for v in raw_values]),
+ ],
+ ),
+ ],
+ )
+ )
+ conditions.append(ast.Constant(value=clean_name))
+
+ if not conditions:
+ return campaign_expr
+
+ return ast.Call(name="multiIf", args=[*conditions, campaign_expr])
+
+
def _filter_to_model_fields(goal_dict: dict[str, Any], model: type[BaseModel]) -> dict[str, Any]:
"""Keep only keys the target pydantic model declares, so extra fields (e.g. data-warehouse-only
fields on a saved goal) don't trip the model's ``extra="forbid"`` validation."""
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 8d001d76c5a6..cb22b06a920c 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -36347,6 +36347,8 @@ export namespace Schemas {
doPathCleaning?: boolean | null;
/** Drop direct sessions from the touchpoint set before weights are computed, so the remaining touchpoints renormalize to full credit rather than losing direct's share. */
excludeDirectTraffic?: boolean | null;
+ /** Drop touchpoints whose current breakdown value is empty or unknown — the "(none)" row — before weights are computed, so the remaining touchpoints renormalize to full credit. */
+ excludeUnattributed?: boolean | null;
/** Filter test accounts */
filterTestAccounts?: boolean | null;
includeRevenue?: boolean | null;
@@ -36372,6 +36374,97 @@ export namespace Schemas {
version?: number | null;
}
+ export interface MarketingAnalyticsAttributionPathRow {
+ /** Null unless the goal is revenue-bearing. */
+ conversionValue: number | null;
+ /** Conversions whose in-window touchpoints form exactly this path. */
+ conversions: number;
+ /** Breakdown values in touch order, oldest first. Consecutive repeats are preserved — collapsing them to "×N" is a display concern. Truncated to the most recent steps when the journey is longer than the grouping cap. */
+ path: string[];
+ /** True when at least one grouped conversion had more touchpoints than the path shows. */
+ pathTruncated: boolean;
+ }
+
+ export interface MarketingAnalyticsAttributionPathsQueryResponse {
+ /** Conversions with at least one in-window touchpoint. The share denominator — deliberately unfiltered by min/maxTouchpoints so shares stay comparable across filter values. */
+ attributedConversions: number;
+ /** The attribution window actually used, for the tooltips. */
+ attributionWindowDays: number;
+ /** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
+ error?: string | null;
+ hasMore?: boolean | null;
+ /** Whether the goal is revenue-bearing, which gates the value column. */
+ hasValue: boolean;
+ /** Generated HogQL query. */
+ hogql?: string | null;
+ limit?: number | null;
+ /** Modifiers used when performing the query */
+ modifiers?: HogQLQueryModifiers | null;
+ offset?: number | null;
+ /** Query status indicates whether next to the provided data, a query is still running. */
+ query_status?: QueryStatus | null;
+ /** The resolved previous/comparison period date range, when comparing against another period */
+ resolved_compare_date_range?: ResolvedDateRangeResponse | null;
+ /** The date range used for the query */
+ resolved_date_range?: ResolvedDateRangeResponse | null;
+ results: MarketingAnalyticsAttributionPathRow[];
+ /** Measured timings for different parts of the query generation process */
+ timings?: QueryTiming[] | null;
+ /** All conversions in range, before the touchpoint-count filter. */
+ totalConversions: number;
+ /** Connector-synced data warehouse sources referenced by this query, if any. */
+ used_data_warehouse_sources?: DataWarehouseSourceUsage[] | null;
+ /** Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access. */
+ warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
+ }
+
+ export interface MarketingAnalyticsAttributionPathsQuery {
+ /** Groups aggregation - not used in Web Analytics but required for type compatibility */
+ aggregation_group_type_index?: number | null;
+ /** Whether one person converting repeatedly contributes one path or one per conversion. Null follows the goal's math. */
+ allowMultipleConversionsPerVisitor?: boolean | null;
+ /** Path step dimension. Defaults to channel. */
+ breakdownBy?: MarketingAnalyticsAttributionBreakdown | null;
+ conversionGoal?: ActionConversionGoal | CustomEventConversionGoal | null;
+ /** conversion_goal_id of the goal whose conversions the paths lead to. */
+ conversionGoalId: string;
+ /** Colors used in the insight's visualization - not used in Web Analytics but required for type compatibility */
+ dataColorTheme?: number | null;
+ dateRange?: DateRange | null;
+ doPathCleaning?: boolean | null;
+ /** Drop direct sessions from every path, mirroring the attribution table's option. */
+ excludeDirectTraffic?: boolean | null;
+ /** Drop touchpoints whose breakdown value is empty or unknown — the "(none)" steps. */
+ excludeUnattributed?: boolean | null;
+ /** Filter test accounts */
+ filterTestAccounts?: boolean | null;
+ includeRevenue?: boolean | null;
+ /** Interval for date range calculation (affects date_to rounding for hour vs day ranges) */
+ interval?: IntervalType | null;
+ kind?: 'MarketingAnalyticsAttributionPathsQuery';
+ /** Number of rows to return */
+ limit?: number | null;
+ /** How many days before each conversion a touchpoint can be part of its path, overriding the team's configured attribution window for this query only. */
+ lookbackWindowDays?: number | null;
+ /** Only paths with at most this many touchpoints, counted before truncation. */
+ maxTouchpoints?: number | null;
+ /** Only paths with at least this many touchpoints, counted before truncation. */
+ minTouchpoints?: number | null;
+ /** Modifiers used when performing the query */
+ modifiers?: HogQLQueryModifiers | null;
+ /** Number of rows to skip before returning rows */
+ offset?: number | null;
+ properties: (EventPropertyFilter | PersonPropertyFilter | SessionPropertyFilter | CohortPropertyFilter)[];
+ response?: MarketingAnalyticsAttributionPathsQueryResponse | null;
+ sampling?: WebAnalyticsSampling | null;
+ /** Sampling rate */
+ samplingFactor?: number | null;
+ tags?: QueryLogTags | null;
+ useSessionsTable?: boolean | null;
+ /** version of the node, used for schema migrations */
+ version?: number | null;
+ }
+
export interface PageURL {
url: string;
}
@@ -38116,7 +38209,7 @@ export namespace Schemas {
query: string;
response?: HogQLMetadataResponse | null;
/** Query within which "expr" and "template" are validated. Defaults to "select * from events" */
- sourceQuery?: EventsNode | ActionsNode | PersonsNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | NonIntegratedConversionsTableQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | CalendarHeatmapQuery | RecordingsQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | null;
+ sourceQuery?: EventsNode | ActionsNode | PersonsNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | NonIntegratedConversionsTableQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | CalendarHeatmapQuery | RecordingsQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | null;
tags?: QueryLogTags | null;
/** Variables to be subsituted into the query */
variables?: HogQLMetadataVariables;
@@ -38142,7 +38235,7 @@ export namespace Schemas {
query: string;
response?: HogQLAutocompleteResponse | null;
/** Query in whose context to validate. */
- sourceQuery?: EventsNode | ActionsNode | PersonsNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | NonIntegratedConversionsTableQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | CalendarHeatmapQuery | RecordingsQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | null;
+ sourceQuery?: EventsNode | ActionsNode | PersonsNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | NonIntegratedConversionsTableQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | CalendarHeatmapQuery | RecordingsQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | null;
/** Start position of the editor word */
startPosition: number;
tags?: QueryLogTags | null;
@@ -61086,7 +61179,7 @@ export namespace Schemas {
* ```
*
* For more details on HogQL queries, see the [PostHog HogQL documentation](/docs/hogql#api-access). */
- query: EventsNode | ActionsNode | PersonsNode | DataWarehouseNode | FunnelsDataWarehouseNode | LifecycleDataWarehouseNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | NonIntegratedConversionsTableQuery | DataVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | StickinessQuery | LifecycleQuery | FunnelCorrelationQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | PropertyValuesQuery;
+ query: EventsNode | ActionsNode | PersonsNode | DataWarehouseNode | FunnelsDataWarehouseNode | LifecycleDataWarehouseNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | NonIntegratedConversionsTableQuery | DataVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | StickinessQuery | LifecycleQuery | FunnelCorrelationQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | PropertyValuesQuery;
/** Whether results should be calculated sync or async, and how much to rely on the cache:
* - `'blocking'` - calculate synchronously (returning only when the query is done), UNLESS there are very fresh results in the cache
* - `'async'` - kick off background calculation (returning immediately with a query status), UNLESS there are very fresh results in the cache
@@ -61862,6 +61955,39 @@ export namespace Schemas {
}
export interface QueryResponseAlternative33 {
+ /** Conversions with at least one in-window touchpoint. The share denominator — deliberately unfiltered by min/maxTouchpoints so shares stay comparable across filter values. */
+ attributedConversions: number;
+ /** The attribution window actually used, for the tooltips. */
+ attributionWindowDays: number;
+ /** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
+ error?: string | null;
+ hasMore?: boolean | null;
+ /** Whether the goal is revenue-bearing, which gates the value column. */
+ hasValue: boolean;
+ /** Generated HogQL query. */
+ hogql?: string | null;
+ limit?: number | null;
+ /** Modifiers used when performing the query */
+ modifiers?: HogQLQueryModifiers | null;
+ offset?: number | null;
+ /** Query status indicates whether next to the provided data, a query is still running. */
+ query_status?: QueryStatus | null;
+ /** The resolved previous/comparison period date range, when comparing against another period */
+ resolved_compare_date_range?: ResolvedDateRangeResponse | null;
+ /** The date range used for the query */
+ resolved_date_range?: ResolvedDateRangeResponse | null;
+ results: MarketingAnalyticsAttributionPathRow[];
+ /** Measured timings for different parts of the query generation process */
+ timings?: QueryTiming[] | null;
+ /** All conversions in range, before the touchpoint-count filter. */
+ totalConversions: number;
+ /** Connector-synced data warehouse sources referenced by this query, if any. */
+ used_data_warehouse_sources?: DataWarehouseSourceUsage[] | null;
+ /** Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access. */
+ warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
+ }
+
+ export interface QueryResponseAlternative34 {
columns?: unknown[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -61889,7 +62015,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative34 {
+ export interface QueryResponseAlternative35 {
columns: unknown[];
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -61918,7 +62044,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative35 {
+ export interface QueryResponseAlternative36 {
columns: unknown[];
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -61946,7 +62072,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative36 {
+ export interface QueryResponseAlternative37 {
columns: unknown[];
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -61974,7 +62100,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative37 {
+ export interface QueryResponseAlternative38 {
/** Executed ClickHouse query */
clickhouse?: string | null;
/** Returned columns */
@@ -62011,7 +62137,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative38 {
+ export interface QueryResponseAlternative39 {
dateFrom?: string | null;
dateTo?: string | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
@@ -62037,7 +62163,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative39 {
+ export interface QueryResponseAlternative40 {
columns?: unknown[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -62068,7 +62194,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative40 {
+ export interface QueryResponseAlternative41 {
columns?: unknown[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -62096,7 +62222,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative41 {
+ export interface QueryResponseAlternative42 {
columns?: unknown[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -62123,7 +62249,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative42 {
+ export interface QueryResponseAlternative43 {
columns?: unknown[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -62152,7 +62278,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative43 {
+ export interface QueryResponseAlternative44 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -62179,7 +62305,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative44 {
+ export interface QueryResponseAlternative45 {
columns?: unknown[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -62206,7 +62332,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative45 {
+ export interface QueryResponseAlternative46 {
columns: unknown[];
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -62233,7 +62359,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative46 {
+ export interface QueryResponseAlternative47 {
columns?: unknown[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -62261,9 +62387,9 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export type QueryResponseAlternative47Results = {[key: string]: MarketingAnalyticsItem};
+ export type QueryResponseAlternative48Results = {[key: string]: MarketingAnalyticsItem};
- export interface QueryResponseAlternative47 {
+ export interface QueryResponseAlternative48 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -62276,7 +62402,7 @@ export namespace Schemas {
resolved_compare_date_range?: ResolvedDateRangeResponse | null;
/** The date range used for the query */
resolved_date_range?: ResolvedDateRangeResponse | null;
- results: QueryResponseAlternative47Results;
+ results: QueryResponseAlternative48Results;
samplingRate?: SamplingRate | null;
/** Measured timings for different parts of the query generation process */
timings?: QueryTiming[] | null;
@@ -62286,7 +62412,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative48 {
+ export interface QueryResponseAlternative49 {
columns?: unknown[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -62314,7 +62440,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative49 {
+ export interface QueryResponseAlternative50 {
columns?: string[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -62340,19 +62466,19 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export type QueryResponseAlternative51CredibleIntervals = {[key: string]: number[]};
+ export type QueryResponseAlternative52CredibleIntervals = {[key: string]: number[]};
- export type QueryResponseAlternative51InsightItemItem = { [key: string]: unknown };
+ export type QueryResponseAlternative52InsightItemItem = { [key: string]: unknown };
- export type QueryResponseAlternative51Probability = {[key: string]: number};
+ export type QueryResponseAlternative52Probability = {[key: string]: number};
- export interface QueryResponseAlternative51 {
- credible_intervals: QueryResponseAlternative51CredibleIntervals;
+ export interface QueryResponseAlternative52 {
+ credible_intervals: QueryResponseAlternative52CredibleIntervals;
expected_loss: number;
funnels_query?: FunnelsQuery | null;
- insight: QueryResponseAlternative51InsightItemItem[][];
+ insight: QueryResponseAlternative52InsightItemItem[][];
kind?: 'ExperimentFunnelsQuery';
- probability: QueryResponseAlternative51Probability;
+ probability: QueryResponseAlternative52Probability;
significance_code: ExperimentSignificanceCode;
significant: boolean;
stats_version?: number | null;
@@ -62361,20 +62487,20 @@ export namespace Schemas {
warnings?: DataWarehouseSyncWarning[] | null;
}
- export type QueryResponseAlternative52CredibleIntervals = {[key: string]: number[]};
+ export type QueryResponseAlternative53CredibleIntervals = {[key: string]: number[]};
- export type QueryResponseAlternative52InsightItem = { [key: string]: unknown };
+ export type QueryResponseAlternative53InsightItem = { [key: string]: unknown };
- export type QueryResponseAlternative52Probability = {[key: string]: number};
+ export type QueryResponseAlternative53Probability = {[key: string]: number};
- export interface QueryResponseAlternative52 {
+ export interface QueryResponseAlternative53 {
count_query?: TrendsQuery | null;
- credible_intervals: QueryResponseAlternative52CredibleIntervals;
+ credible_intervals: QueryResponseAlternative53CredibleIntervals;
exposure_query?: TrendsQuery | null;
- insight: QueryResponseAlternative52InsightItem[];
+ insight: QueryResponseAlternative53InsightItem[];
kind?: 'ExperimentTrendsQuery';
p_value: number;
- probability: QueryResponseAlternative52Probability;
+ probability: QueryResponseAlternative53Probability;
significance_code: ExperimentSignificanceCode;
significant: boolean;
stats_version?: number | null;
@@ -62383,7 +62509,7 @@ export namespace Schemas {
warnings?: DataWarehouseSyncWarning[] | null;
}
- export interface QueryResponseAlternative53 {
+ export interface QueryResponseAlternative54 {
columns?: string[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -62409,7 +62535,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative55 {
+ export interface QueryResponseAlternative56 {
columns?: unknown[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -62436,7 +62562,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative56 {
+ export interface QueryResponseAlternative57 {
columns: unknown[];
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -62466,9 +62592,9 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export type QueryResponseAlternative57ResultsItem = { [key: string]: unknown };
+ export type QueryResponseAlternative58ResultsItem = { [key: string]: unknown };
- export interface QueryResponseAlternative57 {
+ export interface QueryResponseAlternative58 {
boxplot_data?: BoxPlotDatum[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -62484,7 +62610,7 @@ export namespace Schemas {
resolved_compare_date_range?: ResolvedDateRangeResponse | null;
/** The date range used for the query */
resolved_date_range?: ResolvedDateRangeResponse | null;
- results: QueryResponseAlternative57ResultsItem[];
+ results: QueryResponseAlternative58ResultsItem[];
/** Measured timings for different parts of the query generation process */
timings?: QueryTiming[] | null;
/** Connector-synced data warehouse sources referenced by this query, if any. */
@@ -62493,7 +62619,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative58 {
+ export interface QueryResponseAlternative59 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -62517,7 +62643,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative59 {
+ export interface QueryResponseAlternative60 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -62539,7 +62665,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative60 {
+ export interface QueryResponseAlternative61 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -62561,9 +62687,9 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export type QueryResponseAlternative61ResultsItem = { [key: string]: unknown };
+ export type QueryResponseAlternative62ResultsItem = { [key: string]: unknown };
- export interface QueryResponseAlternative61 {
+ export interface QueryResponseAlternative62 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -62576,7 +62702,7 @@ export namespace Schemas {
resolved_compare_date_range?: ResolvedDateRangeResponse | null;
/** The date range used for the query */
resolved_date_range?: ResolvedDateRangeResponse | null;
- results: QueryResponseAlternative61ResultsItem[];
+ results: QueryResponseAlternative62ResultsItem[];
/** Measured timings for different parts of the query generation process */
timings?: QueryTiming[] | null;
/** Connector-synced data warehouse sources referenced by this query, if any. */
@@ -62585,7 +62711,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative63 {
+ export interface QueryResponseAlternative64 {
columns?: unknown[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -62612,14 +62738,14 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export type QueryResponseAlternative64Tables = {[key: string]: DatabaseSchemaPostHogTable | DatabaseSchemaSystemTable | DatabaseSchemaDataWarehouseTable | DatabaseSchemaViewTable | DatabaseSchemaManagedViewTable | DatabaseSchemaBatchExportTable | DatabaseSchemaMaterializedViewTable | DatabaseSchemaEndpointTable};
+ export type QueryResponseAlternative65Tables = {[key: string]: DatabaseSchemaPostHogTable | DatabaseSchemaSystemTable | DatabaseSchemaDataWarehouseTable | DatabaseSchemaViewTable | DatabaseSchemaManagedViewTable | DatabaseSchemaBatchExportTable | DatabaseSchemaMaterializedViewTable | DatabaseSchemaEndpointTable};
- export interface QueryResponseAlternative64 {
+ export interface QueryResponseAlternative65 {
joins: DataWarehouseViewLink[];
- tables: QueryResponseAlternative64Tables;
+ tables: QueryResponseAlternative65Tables;
}
- export interface QueryResponseAlternative65 {
+ export interface QueryResponseAlternative66 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
has_next: boolean;
@@ -62644,7 +62770,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative66 {
+ export interface QueryResponseAlternative67 {
columns?: string[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -62672,7 +62798,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative67 {
+ export interface QueryResponseAlternative68 {
count: number;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -62695,7 +62821,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative68 {
+ export interface QueryResponseAlternative69 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -62717,7 +62843,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative69 {
+ export interface QueryResponseAlternative70 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -62739,7 +62865,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative70 {
+ export interface QueryResponseAlternative71 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
hasMore?: boolean | null;
@@ -62766,7 +62892,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative71 {
+ export interface QueryResponseAlternative72 {
/** Result rows for the comparison period when `compareFilter.compare` is true. */
compare?: AggregatedSpanRow[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
@@ -62790,7 +62916,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative72 {
+ export interface QueryResponseAlternative73 {
/** Result rows for the comparison period when `compareFilter.compare` is true. */
compare?: SpanTreeNode[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
@@ -62814,7 +62940,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative73 {
+ export interface QueryResponseAlternative74 {
/** Result rows for the comparison period when `compareFilter.compare` is true. */
compare?: AttributeBreakdownRow[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
@@ -62838,13 +62964,13 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative74 {
+ export interface QueryResponseAlternative75 {
questions: string[];
/** Data warehouse sync warnings — see AnalyticsQueryResponseBase.warnings for semantics. */
warnings?: DataWarehouseSyncWarning[] | null;
}
- export interface QueryResponseAlternative75 {
+ export interface QueryResponseAlternative76 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
hasMore?: boolean | null;
@@ -62869,7 +62995,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative76 {
+ export interface QueryResponseAlternative77 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
hasMore?: boolean | null;
@@ -62894,7 +63020,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative77 {
+ export interface QueryResponseAlternative78 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -62916,7 +63042,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative78 {
+ export interface QueryResponseAlternative79 {
columns?: string[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -62942,7 +63068,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative81 {
+ export interface QueryResponseAlternative82 {
/** Timestamp of the newer trace */
newerTimestamp?: string | null;
/** ID of the newer trace (chronologically after current) */
@@ -62957,7 +63083,7 @@ export namespace Schemas {
warnings?: DataWarehouseSyncWarning[] | null;
}
- export interface QueryResponseAlternative82 {
+ export interface QueryResponseAlternative83 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -62979,7 +63105,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative83 {
+ export interface QueryResponseAlternative84 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -63001,7 +63127,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative84 {
+ export interface QueryResponseAlternative85 {
columns: unknown[];
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -63031,7 +63157,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative85 {
+ export interface QueryResponseAlternative86 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -63053,7 +63179,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative86 {
+ export interface QueryResponseAlternative87 {
columns?: unknown[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -63080,9 +63206,9 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export type QueryResponseAlternative87ResultsItem = { [key: string]: unknown };
+ export type QueryResponseAlternative88ResultsItem = { [key: string]: unknown };
- export interface QueryResponseAlternative87 {
+ export interface QueryResponseAlternative88 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -63095,7 +63221,7 @@ export namespace Schemas {
resolved_compare_date_range?: ResolvedDateRangeResponse | null;
/** The date range used for the query */
resolved_date_range?: ResolvedDateRangeResponse | null;
- results: QueryResponseAlternative87ResultsItem[];
+ results: QueryResponseAlternative88ResultsItem[];
/** Measured timings for different parts of the query generation process */
timings?: QueryTiming[] | null;
/** Connector-synced data warehouse sources referenced by this query, if any. */
@@ -63104,7 +63230,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative88 {
+ export interface QueryResponseAlternative89 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -63126,7 +63252,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative89 {
+ export interface QueryResponseAlternative90 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -63148,7 +63274,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative90 {
+ export interface QueryResponseAlternative91 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -63170,7 +63296,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative91 {
+ export interface QueryResponseAlternative92 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -63192,7 +63318,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative92 {
+ export interface QueryResponseAlternative93 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -63214,7 +63340,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative93 {
+ export interface QueryResponseAlternative94 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -63236,7 +63362,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative94 {
+ export interface QueryResponseAlternative95 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -63259,7 +63385,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative95 {
+ export interface QueryResponseAlternative96 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -63281,7 +63407,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative96 {
+ export interface QueryResponseAlternative97 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -63303,7 +63429,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative97 {
+ export interface QueryResponseAlternative98 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -63325,7 +63451,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative98 {
+ export interface QueryResponseAlternative99 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -63347,7 +63473,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative99 {
+ export interface QueryResponseAlternative100 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -63369,7 +63495,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative100 {
+ export interface QueryResponseAlternative101 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -63391,7 +63517,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative101 {
+ export interface QueryResponseAlternative102 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -63413,7 +63539,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative102 {
+ export interface QueryResponseAlternative103 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -63435,7 +63561,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative103 {
+ export interface QueryResponseAlternative104 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -63457,18 +63583,18 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export type QueryResponseAlternative = { [key: string]: unknown } | QueryResponseAlternative1 | QueryResponseAlternative2 | QueryResponseAlternative3 | QueryResponseAlternative4 | QueryResponseAlternative5 | QueryResponseAlternative6 | QueryResponseAlternative7 | QueryResponseAlternative8 | QueryResponseAlternative9 | QueryResponseAlternative10 | QueryResponseAlternative11 | QueryResponseAlternative12 | QueryResponseAlternative13 | QueryResponseAlternative14 | QueryResponseAlternative15 | QueryResponseAlternative16 | QueryResponseAlternative17 | QueryResponseAlternative18 | QueryResponseAlternative19 | QueryResponseAlternative20 | QueryResponseAlternative21 | QueryResponseAlternative22 | QueryResponseAlternative23 | QueryResponseAlternative24 | QueryResponseAlternative25 | QueryResponseAlternative26 | QueryResponseAlternative27 | QueryResponseAlternative28 | QueryResponseAlternative29 | QueryResponseAlternative30 | QueryResponseAlternative31 | QueryResponseAlternative32 | QueryResponseAlternative33 | unknown | QueryResponseAlternative34 | QueryResponseAlternative35 | QueryResponseAlternative36 | QueryResponseAlternative37 | QueryResponseAlternative38 | QueryResponseAlternative39 | QueryResponseAlternative40 | QueryResponseAlternative41 | QueryResponseAlternative42 | QueryResponseAlternative43 | QueryResponseAlternative44 | QueryResponseAlternative45 | QueryResponseAlternative46 | QueryResponseAlternative47 | QueryResponseAlternative48 | QueryResponseAlternative49 | QueryResponseAlternative51 | QueryResponseAlternative52 | QueryResponseAlternative53 | QueryResponseAlternative55 | QueryResponseAlternative56 | QueryResponseAlternative57 | QueryResponseAlternative58 | QueryResponseAlternative59 | QueryResponseAlternative60 | QueryResponseAlternative61 | QueryResponseAlternative63 | QueryResponseAlternative64 | QueryResponseAlternative65 | QueryResponseAlternative66 | QueryResponseAlternative67 | QueryResponseAlternative68 | QueryResponseAlternative69 | QueryResponseAlternative70 | QueryResponseAlternative71 | QueryResponseAlternative72 | QueryResponseAlternative73 | QueryResponseAlternative74 | QueryResponseAlternative75 | QueryResponseAlternative76 | QueryResponseAlternative77 | QueryResponseAlternative78 | QueryResponseAlternative81 | QueryResponseAlternative82 | QueryResponseAlternative83 | QueryResponseAlternative84 | QueryResponseAlternative85 | QueryResponseAlternative86 | QueryResponseAlternative87 | QueryResponseAlternative88 | QueryResponseAlternative89 | QueryResponseAlternative90 | QueryResponseAlternative91 | QueryResponseAlternative92 | QueryResponseAlternative93 | QueryResponseAlternative94 | QueryResponseAlternative95 | QueryResponseAlternative96 | QueryResponseAlternative97 | QueryResponseAlternative98 | QueryResponseAlternative99 | QueryResponseAlternative100 | QueryResponseAlternative101 | QueryResponseAlternative102 | QueryResponseAlternative103;
+ export type QueryResponseAlternative = { [key: string]: unknown } | QueryResponseAlternative1 | QueryResponseAlternative2 | QueryResponseAlternative3 | QueryResponseAlternative4 | QueryResponseAlternative5 | QueryResponseAlternative6 | QueryResponseAlternative7 | QueryResponseAlternative8 | QueryResponseAlternative9 | QueryResponseAlternative10 | QueryResponseAlternative11 | QueryResponseAlternative12 | QueryResponseAlternative13 | QueryResponseAlternative14 | QueryResponseAlternative15 | QueryResponseAlternative16 | QueryResponseAlternative17 | QueryResponseAlternative18 | QueryResponseAlternative19 | QueryResponseAlternative20 | QueryResponseAlternative21 | QueryResponseAlternative22 | QueryResponseAlternative23 | QueryResponseAlternative24 | QueryResponseAlternative25 | QueryResponseAlternative26 | QueryResponseAlternative27 | QueryResponseAlternative28 | QueryResponseAlternative29 | QueryResponseAlternative30 | QueryResponseAlternative31 | QueryResponseAlternative32 | QueryResponseAlternative33 | QueryResponseAlternative34 | unknown | QueryResponseAlternative35 | QueryResponseAlternative36 | QueryResponseAlternative37 | QueryResponseAlternative38 | QueryResponseAlternative39 | QueryResponseAlternative40 | QueryResponseAlternative41 | QueryResponseAlternative42 | QueryResponseAlternative43 | QueryResponseAlternative44 | QueryResponseAlternative45 | QueryResponseAlternative46 | QueryResponseAlternative47 | QueryResponseAlternative48 | QueryResponseAlternative49 | QueryResponseAlternative50 | QueryResponseAlternative52 | QueryResponseAlternative53 | QueryResponseAlternative54 | QueryResponseAlternative56 | QueryResponseAlternative57 | QueryResponseAlternative58 | QueryResponseAlternative59 | QueryResponseAlternative60 | QueryResponseAlternative61 | QueryResponseAlternative62 | QueryResponseAlternative64 | QueryResponseAlternative65 | QueryResponseAlternative66 | QueryResponseAlternative67 | QueryResponseAlternative68 | QueryResponseAlternative69 | QueryResponseAlternative70 | QueryResponseAlternative71 | QueryResponseAlternative72 | QueryResponseAlternative73 | QueryResponseAlternative74 | QueryResponseAlternative75 | QueryResponseAlternative76 | QueryResponseAlternative77 | QueryResponseAlternative78 | QueryResponseAlternative79 | QueryResponseAlternative82 | QueryResponseAlternative83 | QueryResponseAlternative84 | QueryResponseAlternative85 | QueryResponseAlternative86 | QueryResponseAlternative87 | QueryResponseAlternative88 | QueryResponseAlternative89 | QueryResponseAlternative90 | QueryResponseAlternative91 | QueryResponseAlternative92 | QueryResponseAlternative93 | QueryResponseAlternative94 | QueryResponseAlternative95 | QueryResponseAlternative96 | QueryResponseAlternative97 | QueryResponseAlternative98 | QueryResponseAlternative99 | QueryResponseAlternative100 | QueryResponseAlternative101 | QueryResponseAlternative102 | QueryResponseAlternative103 | QueryResponseAlternative104;
export interface QueryStatusResponse {
query_status: QueryStatus;
}
export interface QueryUpgradeRequest {
- query: EventsNode | ActionsNode | PersonsNode | DataWarehouseNode | FunnelsDataWarehouseNode | LifecycleDataWarehouseNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | NonIntegratedConversionsTableQuery | DataVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | StickinessQuery | LifecycleQuery | FunnelCorrelationQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | PropertyValuesQuery;
+ query: EventsNode | ActionsNode | PersonsNode | DataWarehouseNode | FunnelsDataWarehouseNode | LifecycleDataWarehouseNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | NonIntegratedConversionsTableQuery | DataVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | StickinessQuery | LifecycleQuery | FunnelCorrelationQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | PropertyValuesQuery;
}
export interface QueryUpgradeResponse {
- query: EventsNode | ActionsNode | PersonsNode | DataWarehouseNode | FunnelsDataWarehouseNode | LifecycleDataWarehouseNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | NonIntegratedConversionsTableQuery | DataVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | StickinessQuery | LifecycleQuery | FunnelCorrelationQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | PropertyValuesQuery;
+ query: EventsNode | ActionsNode | PersonsNode | DataWarehouseNode | FunnelsDataWarehouseNode | LifecycleDataWarehouseNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | NonIntegratedConversionsTableQuery | DataVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | StickinessQuery | LifecycleQuery | FunnelCorrelationQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | PropertyValuesQuery;
}
export interface QuotaResourceLimit {