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): add attribution explorer comparing all five models side by side (#74333)

Mike Warrenb618788d9e18
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 9a8f31694824..d501f4d35252 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -375,6 +375,7 @@ export const FEATURE_FLAGS = {
MANAGED_MIGRATIONS_TRIAL_RUNS: 'managed-migrations-trial-runs', // owner: #team-ingestion, gates trial runs for managed migrations
MANAGED_VIEWSETS: 'managed-viewsets', // owner: @rafaeelaudibert #team-revenue-analytics
MARKETING_ANALYTICS_AI: 'marketing-analytics-ai', // owner: @jabahamondes #team-web-analytics
+ MARKETING_ANALYTICS_ATTRIBUTION: 'marketing-analytics-attribution', // owner: @jabahamondes #team-web-analytics — gates the Attribution tab
MARKETING_ANALYTICS_COSTS_PRECOMPUTATION: 'marketing-analytics-costs-precomputation', // owner: @jabahamondes #team-web-analytics — gates reading the native cost precompute table
MARKETING_ANALYTICS_DRILL_DOWN: 'marketing-analytics-drill-down', // owner: @jabahamondes #team-web-analytics
MARKETING_ANALYTICS_EXTENDED_DRILL_DOWN: 'marketing-analytics-extended-drill-down', // owner: @jabahamondes #team-web-analytics
diff --git a/frontend/src/lib/lemon-ui/LemonTable/LemonTable.test.tsx b/frontend/src/lib/lemon-ui/LemonTable/LemonTable.test.tsx
index 18e70f09f34e..e7a91d521ae3 100644
--- a/frontend/src/lib/lemon-ui/LemonTable/LemonTable.test.tsx
+++ b/frontend/src/lib/lemon-ui/LemonTable/LemonTable.test.tsx
@@ -52,4 +52,30 @@ describe('LemonTable', () => {
)
expect(renderedOrder()).toEqual(expectedOrder)
})
+
+ it('keeps group headers aligned when the sticky first group has a single column', () => {
+ // The sticky-first-group header is rendered as a title cell plus a filler cell. With one child
+ // the filler's colSpan would be 0, which the DOM clamps to 1, adding a phantom column that
+ // shifts every following group title one column to the right.
+ render(
+ <LemonTable
+ rowKey="id"
+ dataSource={DATA}
+ firstColumnSticky
+ columns={[
+ { children: [{ title: 'Name', key: 'name', dataIndex: 'name' as keyof Row }] },
+ {
+ title: 'Metrics',
+ children: [
+ { title: 'Value', key: 'value', dataIndex: 'value' as keyof Row },
+ { title: 'Id', key: 'id', dataIndex: 'id' as keyof Row },
+ ],
+ },
+ ]}
+ />
+ )
+ const groupingRow = document.querySelector('tr.LemonTable__row--grouping')!
+ const spannedColumns = Array.from(groupingRow.querySelectorAll('th')).reduce((sum, th) => sum + th.colSpan, 0)
+ expect(spannedColumns).toBe(3)
+ })
})
diff --git a/frontend/src/lib/lemon-ui/LemonTable/LemonTable.tsx b/frontend/src/lib/lemon-ui/LemonTable/LemonTable.tsx
index 94da99b4ed79..69abd6c92093 100644
--- a/frontend/src/lib/lemon-ui/LemonTable/LemonTable.tsx
+++ b/frontend/src/lib/lemon-ui/LemonTable/LemonTable.tsx
@@ -439,7 +439,13 @@ export function LemonTable<T extends Record<string, any>, K extends BulkSelectio
>
{columnGroup.title}
</th>
- <th colSpan={columnGroup.children.length - 1} />
+ {/* The DOM clamps colSpan 0 up to 1, so a single-child
+ group must not render the filler at all: the phantom
+ column shifts every group title after it one column
+ to the right. */}
+ {columnGroup.children.length > 1 && (
+ <th colSpan={columnGroup.children.length - 1} />
+ )}
</React.Fragment>
) : (
<th
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index b79d023567bc..1d8bf09fb3c0 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -906,6 +906,9 @@
{
"$ref": "#/definitions/MarketingAnalyticsAggregatedQuery"
},
+ {
+ "$ref": "#/definitions/MarketingAnalyticsAttributionQuery"
+ },
{
"$ref": "#/definitions/NonIntegratedConversionsTableQuery"
},
@@ -10029,6 +10032,148 @@
],
"type": "object"
},
+ "CachedMarketingAnalyticsAttributionQueryResponse": {
+ "additionalProperties": false,
+ "properties": {
+ "allowsMultipleConversionsPerVisitor": {
+ "description": "Whether this result counted a repeat converter's every conversion, after resolving the query's null against the goal's math. The rate columns are a true share only when this is false, so the table reads it to label them.",
+ "type": "boolean"
+ },
+ "attributionWindowDays": {
+ "$ref": "#/definitions/integer",
+ "description": "The team's configured attribution window, 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 columns.",
+ "type": "boolean"
+ },
+ "hogql": {
+ "description": "Generated HogQL query.",
+ "type": "string"
+ },
+ "is_cached": {
+ "type": "boolean"
+ },
+ "last_refresh": {
+ "format": "date-time",
+ "type": "string"
+ },
+ "limit": {
+ "$ref": "#/definitions/integer"
+ },
+ "models": {
+ "description": "Model order for the column groups.",
+ "items": {
+ "$ref": "#/definitions/AttributionMode"
+ },
+ "type": "array"
+ },
+ "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/MarketingAnalyticsAttributionRow"
+ },
+ "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": "Total conversions in range, so the footer can say \"N of M\"."
+ },
+ "unattributedConversions": {
+ "$ref": "#/definitions/integer",
+ "description": "Conversions with no touchpoint in the window. Reported in the footer, not in any row."
+ },
+ "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": [
+ "allowsMultipleConversionsPerVisitor",
+ "attributionWindowDays",
+ "cache_key",
+ "hasValue",
+ "is_cached",
+ "last_refresh",
+ "models",
+ "next_allowed_client_refresh",
+ "results",
+ "timezone",
+ "totalConversions",
+ "unattributedConversions"
+ ],
+ "type": "object"
+ },
"CachedMarketingAnalyticsTableQueryResponse": {
"additionalProperties": false,
"properties": {
@@ -31461,6 +31606,282 @@
"required": ["results"],
"type": "object"
},
+ "MarketingAnalyticsAttributionBreakdown": {
+ "description": "Row dimension for the Attribution table. String values match MarketingAnalyticsDrillDownLevel for the levels they share, so both surfaces speak the same vocabulary. It's a separate enum because `ad_group`/`ad` can't be attributed to events at all (no ad identifier reaches the events table), while `referring_domain`/`landing_page` have no cost-side expression and so don't belong in the drill-down.",
+ "enum": ["channel", "source", "campaign", "medium", "content", "term", "referring_domain", "landing_page"],
+ "type": "string"
+ },
+ "MarketingAnalyticsAttributionModelCell": {
+ "additionalProperties": false,
+ "description": "One attribution model's credit for one breakdown row.",
+ "properties": {
+ "conversionRate": {
+ "description": "conversions / visitors. Null when the row has no visitors.",
+ "type": ["number", "null"]
+ },
+ "conversionValue": {
+ "description": "Null unless the goal is revenue-bearing.",
+ "type": ["number", "null"]
+ },
+ "conversions": {
+ "description": "Fractional for multi-touch models: each conversion's credit is split across its touchpoints.",
+ "type": "number"
+ },
+ "model": {
+ "$ref": "#/definitions/AttributionMode"
+ }
+ },
+ "required": ["model", "conversions", "conversionRate", "conversionValue"],
+ "type": "object"
+ },
+ "MarketingAnalyticsAttributionQuery": {
+ "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 counts once or every time. Null follows the goal's own math: unique-users goals count each person once, count-based goals count every conversion. Set explicitly to override. Counting every conversion makes the rate columns exceed 100%, since a person can convert more times than they visited.",
+ "type": "boolean"
+ },
+ "breakdownBy": {
+ "$ref": "#/definitions/MarketingAnalyticsAttributionBreakdown",
+ "description": "Row dimension. Defaults to channel."
+ },
+ "conversionGoal": {
+ "anyOf": [
+ {
+ "$ref": "#/definitions/WebAnalyticsConversionGoal"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "conversionGoalId": {
+ "description": "conversion_goal_id of the goal to attribute. The table is meaningless without one.",
+ "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 the touchpoint set before weights are computed, so the remaining touchpoints renormalize to full credit rather than losing direct's share.",
+ "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": "MarketingAnalyticsAttributionQuery",
+ "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 earn credit, overriding the team's configured attribution window for this query only."
+ },
+ "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/MarketingAnalyticsAttributionQueryResponse"
+ },
+ "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"
+ },
+ "MarketingAnalyticsAttributionQueryResponse": {
+ "additionalProperties": false,
+ "properties": {
+ "allowsMultipleConversionsPerVisitor": {
+ "description": "Whether this result counted a repeat converter's every conversion, after resolving the query's null against the goal's math. The rate columns are a true share only when this is false, so the table reads it to label them.",
+ "type": "boolean"
+ },
+ "attributionWindowDays": {
+ "$ref": "#/definitions/integer",
+ "description": "The team's configured attribution window, 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 columns.",
+ "type": "boolean"
+ },
+ "hogql": {
+ "description": "Generated HogQL query.",
+ "type": "string"
+ },
+ "limit": {
+ "$ref": "#/definitions/integer"
+ },
+ "models": {
+ "description": "Model order for the column groups.",
+ "items": {
+ "$ref": "#/definitions/AttributionMode"
+ },
+ "type": "array"
+ },
+ "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/MarketingAnalyticsAttributionRow"
+ },
+ "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": "Total conversions in range, so the footer can say \"N of M\"."
+ },
+ "unattributedConversions": {
+ "$ref": "#/definitions/integer",
+ "description": "Conversions with no touchpoint in the window. Reported in the footer, not in any row."
+ },
+ "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": [
+ "allowsMultipleConversionsPerVisitor",
+ "attributionWindowDays",
+ "hasValue",
+ "models",
+ "results",
+ "totalConversions",
+ "unattributedConversions"
+ ],
+ "type": "object"
+ },
+ "MarketingAnalyticsAttributionRow": {
+ "additionalProperties": false,
+ "properties": {
+ "breakdownValue": {
+ "type": "string"
+ },
+ "influencedConversions": {
+ "$ref": "#/definitions/integer",
+ "description": "Conversions with at least one touchpoint on this dimension. Counted once per conversion, so a conversion influenced by several dimensions is counted in each of their rows. These deliberately sum to more than the total, unlike the per-model columns."
+ },
+ "influencedValue": {
+ "type": ["number", "null"]
+ },
+ "models": {
+ "description": "One cell per model, always in the order given by the response's `models`.",
+ "items": {
+ "$ref": "#/definitions/MarketingAnalyticsAttributionModelCell"
+ },
+ "type": "array"
+ },
+ "visitors": {
+ "$ref": "#/definitions/integer",
+ "description": "Unique persons who arrived via this dimension in the date range, converters or not."
+ }
+ },
+ "required": ["breakdownValue", "visitors", "influencedConversions", "influencedValue", "models"],
+ "type": "object"
+ },
"MarketingAnalyticsBaseColumns": {
"enum": [
"ID",
@@ -34544,6 +34965,7 @@
"WebNotableChangesQuery",
"MarketingAnalyticsTableQuery",
"MarketingAnalyticsAggregatedQuery",
+ "MarketingAnalyticsAttributionQuery",
"NonIntegratedConversionsTableQuery",
"ExperimentMetric",
"ExperimentQuery",
@@ -38441,6 +38863,115 @@
"required": ["results"],
"type": "object"
},
+ {
+ "additionalProperties": false,
+ "properties": {
+ "allowsMultipleConversionsPerVisitor": {
+ "description": "Whether this result counted a repeat converter's every conversion, after resolving the query's null against the goal's math. The rate columns are a true share only when this is false, so the table reads it to label them.",
+ "type": "boolean"
+ },
+ "attributionWindowDays": {
+ "$ref": "#/definitions/integer",
+ "description": "The team's configured attribution window, 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 columns.",
+ "type": "boolean"
+ },
+ "hogql": {
+ "description": "Generated HogQL query.",
+ "type": "string"
+ },
+ "limit": {
+ "$ref": "#/definitions/integer"
+ },
+ "models": {
+ "description": "Model order for the column groups.",
+ "items": {
+ "$ref": "#/definitions/AttributionMode"
+ },
+ "type": "array"
+ },
+ "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/MarketingAnalyticsAttributionRow"
+ },
+ "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": "Total conversions in range, so the footer can say \"N of M\"."
+ },
+ "unattributedConversions": {
+ "$ref": "#/definitions/integer",
+ "description": "Conversions with no touchpoint in the window. Reported in the footer, not in any row."
+ },
+ "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": [
+ "allowsMultipleConversionsPerVisitor",
+ "attributionWindowDays",
+ "hasValue",
+ "models",
+ "results",
+ "totalConversions",
+ "unattributedConversions"
+ ],
+ "type": "object"
+ },
{
"additionalProperties": false,
"properties": {
@@ -43683,6 +44214,9 @@
{
"$ref": "#/definitions/MarketingAnalyticsAggregatedQuery"
},
+ {
+ "$ref": "#/definitions/MarketingAnalyticsAttributionQuery"
+ },
{
"$ref": "#/definitions/NonIntegratedConversionsTableQuery"
},
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index f7e0b01e912a..48b0e592d40e 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -150,6 +150,7 @@ export enum NodeKind {
// Marketing analytics queries
MarketingAnalyticsTableQuery = 'MarketingAnalyticsTableQuery',
MarketingAnalyticsAggregatedQuery = 'MarketingAnalyticsAggregatedQuery',
+ MarketingAnalyticsAttributionQuery = 'MarketingAnalyticsAttributionQuery',
NonIntegratedConversionsTableQuery = 'NonIntegratedConversionsTableQuery',
// Experiment queries
@@ -227,6 +228,7 @@ export type AnyDataNode =
| HogQLAutocomplete
| MarketingAnalyticsTableQuery
| MarketingAnalyticsAggregatedQuery
+ | MarketingAnalyticsAttributionQuery
| NonIntegratedConversionsTableQuery
| WebOverviewQuery
| WebStatsTableQuery
@@ -331,6 +333,7 @@ export type QuerySchema =
// Marketing analytics
| MarketingAnalyticsTableQuery
| MarketingAnalyticsAggregatedQuery
+ | MarketingAnalyticsAttributionQuery
| NonIntegratedConversionsTableQuery
// Interface nodes
@@ -6387,6 +6390,110 @@ export interface MarketingAnalyticsAggregatedQuery extends Omit<
drillDownLevel?: MarketingAnalyticsDrillDownLevel
}
+/**
+ * Row dimension for the Attribution table. String values match MarketingAnalyticsDrillDownLevel for the
+ * levels they share, so both surfaces speak the same vocabulary. It's a separate enum because
+ * `ad_group`/`ad` can't be attributed to events at all (no ad identifier reaches the events table), while
+ * `referring_domain`/`landing_page` have no cost-side expression and so don't belong in the drill-down.
+ */
+export enum MarketingAnalyticsAttributionBreakdown {
+ Channel = 'channel',
+ Source = 'source',
+ Campaign = 'campaign',
+ Medium = 'medium',
+ Content = 'content',
+ Term = 'term',
+ ReferringDomain = 'referring_domain',
+ LandingPage = 'landing_page',
+}
+
+export interface MarketingAnalyticsAttributionQuery extends Omit<
+ WebAnalyticsQueryBase<MarketingAnalyticsAttributionQueryResponse>,
+ 'orderBy' | 'compareFilter'
+> {
+ kind: NodeKind.MarketingAnalyticsAttributionQuery
+ /** Row dimension. Defaults to channel. */
+ breakdownBy?: MarketingAnalyticsAttributionBreakdown
+ /** conversion_goal_id of the goal to attribute. The table is meaningless without one. */
+ conversionGoalId: string
+ /**
+ * 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
+ /**
+ * How many days before each conversion a touchpoint can earn credit, overriding the team's
+ * configured attribution window for this query only.
+ */
+ lookbackWindowDays?: integer
+ /**
+ * Whether one person converting repeatedly counts once or every time. Null follows the goal's own
+ * math: unique-users goals count each person once, count-based goals count every conversion. Set
+ * explicitly to override. Counting every conversion makes the rate columns exceed 100%, since a
+ * person can convert more times than they visited.
+ */
+ allowMultipleConversionsPerVisitor?: boolean
+ /** Number of rows to return */
+ limit?: integer
+ /** Number of rows to skip before returning rows */
+ offset?: integer
+ /** Filter test accounts */
+ filterTestAccounts?: boolean
+}
+
+/** One attribution model's credit for one breakdown row. */
+export interface MarketingAnalyticsAttributionModelCell {
+ model: AttributionMode
+ /** Fractional for multi-touch models: each conversion's credit is split across its touchpoints. */
+ conversions: number
+ /** conversions / visitors. Null when the row has no visitors. */
+ conversionRate: number | null
+ /** Null unless the goal is revenue-bearing. */
+ conversionValue: number | null
+}
+
+export interface MarketingAnalyticsAttributionRow {
+ breakdownValue: string
+ /** Unique persons who arrived via this dimension in the date range, converters or not. */
+ visitors: integer
+ /**
+ * Conversions with at least one touchpoint on this dimension. Counted once per conversion, so a
+ * conversion influenced by several dimensions is counted in each of their rows. These
+ * deliberately sum to more than the total, unlike the per-model columns.
+ */
+ influencedConversions: integer
+ influencedValue: number | null
+ /** One cell per model, always in the order given by the response's `models`. */
+ models: MarketingAnalyticsAttributionModelCell[]
+}
+
+export interface MarketingAnalyticsAttributionQueryResponse extends AnalyticsQueryResponseBase {
+ results: MarketingAnalyticsAttributionRow[]
+ /** Model order for the column groups. */
+ models: AttributionMode[]
+ /** Whether the goal is revenue-bearing, which gates the value columns. */
+ hasValue: boolean
+ /** The team's configured attribution window, for the tooltips. */
+ attributionWindowDays: integer
+ /**
+ * Whether this result counted a repeat converter's every conversion, after resolving the query's
+ * null against the goal's math. The rate columns are a true share only when this is false, so the
+ * table reads it to label them.
+ */
+ allowsMultipleConversionsPerVisitor: boolean
+ /** Conversions with no touchpoint in the window. Reported in the footer, not in any row. */
+ unattributedConversions: integer
+ /** Total conversions in range, so the footer can say "N of M". */
+ totalConversions: integer
+ hogql?: string
+ hasMore?: boolean
+ limit?: integer
+ offset?: integer
+}
+
+export type CachedMarketingAnalyticsAttributionQueryResponse =
+ CachedQueryResponse<MarketingAnalyticsAttributionQueryResponse>
+
/** Columns for non-integrated conversions table */
export enum NonIntegratedConversionsColumnsSchemaNames {
Source = 'Source',
diff --git a/frontend/src/scenes/marketing-analytics/MarketingAnalyticsScene.tsx b/frontend/src/scenes/marketing-analytics/MarketingAnalyticsScene.tsx
index 097e20ed9cb3..793e4bf37714 100644
--- a/frontend/src/scenes/marketing-analytics/MarketingAnalyticsScene.tsx
+++ b/frontend/src/scenes/marketing-analytics/MarketingAnalyticsScene.tsx
@@ -13,6 +13,7 @@ import { sceneConfigurations } from 'scenes/scenes'
import { Scene, SceneExport } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
import { QueryTile } from 'scenes/web-analytics/common'
+import { AttributionTab } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/AttributionTab'
import { NonIntegratedConversionsTable } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/components/NonIntegratedConversionsTable/NonIntegratedConversionsTable'
import { UtmAuditTab } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/components/UtmAuditTab/UtmAuditTab'
import { WebQuery } from 'scenes/web-analytics/tiles/WebAnalyticsTile'
@@ -222,6 +223,15 @@ const MarketingAnalyticsContent = (): JSX.Element => {
const tabs = [
{ key: MarketingAnalyticsTab.DASHBOARD, label: 'Dashboard', content: dashboard },
+ ...(featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_ATTRIBUTION]
+ ? [
+ {
+ key: MarketingAnalyticsTab.ATTRIBUTION,
+ label: 'Attribution explorer',
+ content: <AttributionTab />,
+ },
+ ]
+ : []),
...(featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_UTM_AUDIT]
? [
{
@@ -246,6 +256,8 @@ const MarketingAnalyticsContent = (): JSX.Element => {
const TAB_DESCRIPTIONS: Record<string, string> = {
[MarketingAnalyticsTab.DASHBOARD]:
'Analyze your marketing performance across integrations: spend, impressions, conversions, ROAS, and more metrics.',
+ [MarketingAnalyticsTab.ATTRIBUTION]:
+ 'Compare how each attribution model credits your conversions, to see which marketing you might be over or under valuing.',
[MarketingAnalyticsTab.INTEGRATION_HEALTH]:
'Check that your ad platform campaigns are properly linked to UTM tracking in PostHog.',
}
diff --git a/frontend/src/scenes/saved-insights/insightTypesMetadata.tsx b/frontend/src/scenes/saved-insights/insightTypesMetadata.tsx
index e7af8c6b58db..e2338eec22fb 100644
--- a/frontend/src/scenes/saved-insights/insightTypesMetadata.tsx
+++ b/frontend/src/scenes/saved-insights/insightTypesMetadata.tsx
@@ -508,6 +508,11 @@ export const QUERY_TYPES_METADATA: Record<NodeKind, InsightTypeMetadata> = {
icon: IconHogQL,
inMenu: false,
},
+ [NodeKind.MarketingAnalyticsAttributionQuery]: {
+ name: 'Marketing Analytics Attribution',
+ 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/AttributionChart.tsx b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/AttributionChart.tsx
new file mode 100644
index 000000000000..d84524adcb27
--- /dev/null
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/AttributionChart.tsx
@@ -0,0 +1,118 @@
+import clsx from 'clsx'
+import { useMemo } from 'react'
+
+import { LemonSkeleton } from '@posthog/lemon-ui'
+import type { Series } from '@posthog/quill-charts'
+import { BarChart, useChartTheme } from '@posthog/quill-charts'
+
+import { humanFriendlyNumber } from 'lib/utils/numbers'
+
+import { AttributionMode, MarketingAnalyticsAttributionRow } from '~/queries/schema/schema-general'
+
+import { MODEL_LABELS } from '../../logic/marketingAttributionLogic'
+
+// A landing-page breakdown can have hundreds of values; the table below still has every row.
+const MAX_CHART_ROWS = 30
+
+// Below this, five grouped bars squish into unreadable slivers, so the chart scrolls instead.
+const MIN_BAND_WIDTH_PX = 96
+
+const SKELETON_BAR_HEIGHTS = ['h-48', 'h-40', 'h-32', 'h-28', 'h-20', 'h-16', 'h-12', 'h-8']
+
+// The response carries the model list, so a first load has nothing to count yet.
+const SKELETON_SERIES_COUNT = 5
+
+function ChartSkeleton({ modelCount }: { modelCount: number }): JSX.Element {
+ return (
+ <div className="flex h-full flex-col gap-3" aria-busy="true">
+ <div className="flex items-center justify-center gap-4">
+ {Array.from({ length: modelCount }, (_, i) => (
+ <LemonSkeleton key={i} className="h-3 w-16" />
+ ))}
+ </div>
+ <div className="flex flex-1 items-end justify-around gap-4 pb-5">
+ {SKELETON_BAR_HEIGHTS.map((height, band) => (
+ <div key={band} className="flex items-end gap-1">
+ {Array.from({ length: modelCount }, (_, i) => (
+ <LemonSkeleton key={i} className={clsx('w-2.5', height)} />
+ ))}
+ </div>
+ ))}
+ </div>
+ </div>
+ )
+}
+
+export function AttributionChart({
+ rows,
+ models,
+ dimensionLabel,
+ loading,
+}: {
+ rows: MarketingAnalyticsAttributionRow[]
+ models: AttributionMode[]
+ dimensionLabel: string
+ loading?: boolean
+}): JSX.Element | null {
+ const theme = useChartTheme()
+
+ // Rows arrive server-ordered by influenced conversions, so the slice is the top slice.
+ const chartRows = useMemo(() => rows.slice(0, MAX_CHART_ROWS), [rows])
+
+ const series: Series[] = useMemo(
+ () =>
+ models.map((model, index) => ({
+ key: model,
+ label: MODEL_LABELS[model],
+ data: chartRows.map((row) => row.models[index]?.conversions ?? 0),
+ })),
+ [models, chartRows]
+ )
+
+ // Only a settled empty result hides the card: collapsing while loading shoves the table upward.
+ if (!loading && !chartRows.length) {
+ return null
+ }
+
+ return (
+ <div className="rounded border bg-surface-primary p-4">
+ <h3 className="mb-0 text-base font-semibold">Conversions by attribution model</h3>
+ <p className="mb-2 text-secondary">
+ Each bar is the number of conversions a model credits to a {dimensionLabel.toLowerCase()}. Bars of equal
+ height mean the models agree; different heights show where credit moves when the model changes.
+ {rows.length > MAX_CHART_ROWS
+ ? ` Showing the top ${MAX_CHART_ROWS} of ${rows.length} rows. The table below has all of them.`
+ : ''}
+ </p>
+ {/* Flex column, not a plain block: with a legend the chart root is a `flex-1 min-h-0`
+ layout, which only resolves to a real height inside a flex parent. */}
+ <div className="h-80 overflow-x-auto">
+ {chartRows.length ? (
+ <div
+ // A refetch fades the previous bars rather than replacing a readable chart with
+ // a placeholder.
+ className={clsx('flex h-full flex-col', loading && 'opacity-50 transition-opacity')}
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ minWidth: `max(100%, ${chartRows.length * MIN_BAND_WIDTH_PX}px)` }}
+ >
+ <BarChart
+ series={series}
+ labels={chartRows.map((row) => row.breakdownValue || '(none)')}
+ theme={theme}
+ config={{
+ barLayout: 'grouped',
+ legend: { show: true, position: 'top' },
+ tooltip: {
+ valueFormatter: (value: number) => humanFriendlyNumber(value, 1),
+ sortedByValue: true,
+ },
+ }}
+ />
+ </div>
+ ) : (
+ <ChartSkeleton modelCount={models.length || SKELETON_SERIES_COUNT} />
+ )}
+ </div>
+ </div>
+ )
+}
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
new file mode 100644
index 000000000000..e354c8d5e454
--- /dev/null
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/AttributionTab.tsx
@@ -0,0 +1,180 @@
+import { useActions, useValues } from 'kea'
+
+import { IconGear } from '@posthog/icons'
+import { LemonBanner, LemonButton, LemonDivider, LemonSelect, LemonSwitch, Popover } from '@posthog/lemon-ui'
+
+import { DateFilter } from 'lib/components/DateFilter/DateFilter'
+import { FilterBar } from 'lib/components/FilterBar'
+import { urls } from 'scenes/urls'
+
+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 { AttributionTable } from './AttributionTable'
+
+// 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.
+const UNATTRIBUTABLE_LEVELS = [
+ { value: 'ad_group', label: 'Ad group' },
+ { value: 'ad', label: 'Ad' },
+]
+
+const UNATTRIBUTABLE_REASON =
+ "Ad platforms report cost per ad, but events don't carry an ad identifier, so conversions can't be credited to a specific ad."
+
+const LOOKBACK_PRESETS_DAYS = [7, 14, 30, 60, 90, 180]
+
+export function AttributionTab(): JSX.Element {
+ const {
+ breakdownBy,
+ excludeDirectTraffic,
+ attributableGoals,
+ selectedGoalId,
+ query,
+ attribution_window_days,
+ effectiveLookbackDays,
+ effectiveAllowMultipleConversions,
+ optionsOpen,
+ } = useValues(marketingAttributionLogic)
+ const {
+ setBreakdownBy,
+ setConversionGoalId,
+ setExcludeDirectTraffic,
+ setLookbackWindowDays,
+ setAllowMultipleConversionsPerVisitor,
+ setOptionsOpen,
+ } = useActions(marketingAttributionLogic)
+ const { conversion_goals } = useValues(marketingAnalyticsSettingsLogic)
+ const { dateFilter } = useValues(marketingAnalyticsLogic)
+ const { setDates } = useActions(marketingAnalyticsLogic)
+
+ const settingsUrl = urls.settings('environment-marketing-analytics', 'marketing-settings')
+
+ if (!attributableGoals.length) {
+ return (
+ <LemonBanner type="info" className="mt-4" action={{ children: 'Add a conversion goal', to: settingsUrl }}>
+ {conversion_goals?.length
+ ? "Your conversion goals all read from data warehouse tables, which attribution doesn't support yet. Add a goal based on an event or an action to compare attribution models."
+ : 'Attribution needs a conversion goal to credit. Add one to see how each model splits credit across your marketing.'}
+ </LemonBanner>
+ )
+ }
+
+ const lookbackOptions = [...new Set([...LOOKBACK_PRESETS_DAYS, attribution_window_days])]
+ .sort((a, b) => a - b)
+ .map((days) => ({
+ value: days,
+ label: days === attribution_window_days ? `${days} days (default)` : `${days} days`,
+ }))
+
+ const optionsContent = (
+ <div className="flex w-80 max-w-[90vw] flex-col gap-4 p-3">
+ <div>
+ <div className="text-muted mb-2 text-xs font-semibold uppercase">Conversion period</div>
+ <DateFilter dateFrom={dateFilter.dateFrom} dateTo={dateFilter.dateTo} onChange={setDates} />
+ <div className="text-muted mt-1 text-xs">
+ Conversions in this period get credited. Their touchpoints can come from earlier.
+ </div>
+ </div>
+ <div>
+ <div className="text-muted mb-2 text-xs font-semibold uppercase">Lookback window</div>
+ <LemonSelect
+ fullWidth
+ value={effectiveLookbackDays}
+ onChange={(value) =>
+ // Picking the default stores null, so a later settings change flows through.
+ value && setLookbackWindowDays(value === attribution_window_days ? null : value)
+ }
+ options={lookbackOptions}
+ />
+ <div className="text-muted mt-1 text-xs">
+ How far back before each conversion a touchpoint can earn credit. The default comes from your
+ marketing settings.
+ </div>
+ </div>
+ <LemonDivider className="my-0" />
+ <LemonSwitch
+ fullWidth
+ checked={excludeDirectTraffic}
+ onChange={setExcludeDirectTraffic}
+ label="Exclude direct traffic"
+ 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={effectiveAllowMultipleConversions}
+ onChange={setAllowMultipleConversionsPerVisitor}
+ label="Count repeat conversions"
+ tooltip="Count every conversion a person makes, not just their first. Turning this on can push the rate columns above one conversion per visitor, so they're shown as a ratio instead of a percentage."
+ data-attr="marketing-attribution-allow-multiple-conversions"
+ />
+ </div>
+ )
+
+ 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,
+ }))}
+ />
+ </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={
+ <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>
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/AttributionTable.scss b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/AttributionTable.scss
new file mode 100644
index 000000000000..4cb8d033f549
--- /dev/null
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/AttributionTable.scss
@@ -0,0 +1,22 @@
+// Magnitude bars behind every conversions column, the same affordance DataTable gives web analytics
+// tables. Painted as the cell's own background rather than an absolutely positioned overlay: the table
+// collapses borders, so an overlay wide enough to reach the cell edge paints over the column-group
+// separator line, while a background clipped to the padding box can never touch a border.
+.AttributionTable {
+ td.AttributionTable__magnitude-cell {
+ background-image: linear-gradient(
+ to right,
+ color-mix(in sRGB, var(--color-bg-fill-info-secondary) 50%, transparent) var(--attribution-fill, 0%),
+ transparent var(--attribution-fill, 0%)
+ );
+ background-clip: padding-box;
+ }
+
+ // Column-group separators, drawn on the first cell of each group. LemonTable draws these with a
+ // collapsed border-left, but collapsed borders paint unreliably in the body once the table scrolls
+ // horizontally past a sticky column. An inset shadow moves with the cell and paints above its
+ // background, so it stays visible over the magnitude fill too.
+ td.AttributionTable__group-boundary {
+ box-shadow: inset 1px 0 0 var(--color-border-primary);
+ }
+}
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
new file mode 100644
index 000000000000..91cfde9e5114
--- /dev/null
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/AttributionTable.tsx
@@ -0,0 +1,289 @@
+import './AttributionTable.scss'
+
+import clsx from 'clsx'
+import { BuiltLogic, LogicWrapper, useActions, useValues } from 'kea'
+import { useState } from 'react'
+
+import { LemonBanner, LemonTable, LemonTableColumn, LemonTableColumnGroup, Tooltip } from '@posthog/lemon-ui'
+
+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 {
+ AttributionMode,
+ MarketingAnalyticsAttributionQuery,
+ MarketingAnalyticsAttributionQueryResponse,
+ MarketingAnalyticsAttributionRow,
+} from '~/queries/schema/schema-general'
+
+import {
+ ATTRIBUTION_ROW_LIMIT,
+ BREAKDOWN_LABELS,
+ MODEL_LABELS,
+ marketingAttributionLogic,
+} from '../../logic/marketingAttributionLogic'
+import { AttributionChart } from './AttributionChart'
+
+const modelTooltip = (model: AttributionMode, windowDays: number): string => {
+ switch (model) {
+ case AttributionMode.FirstTouch:
+ return 'All credit goes to the earliest touchpoint in the attribution window.'
+ case AttributionMode.LastTouch:
+ return 'All credit goes to the most recent touchpoint before the conversion.'
+ case AttributionMode.Linear:
+ return 'Credit is split equally across every touchpoint.'
+ case AttributionMode.TimeDecay:
+ return `Touchpoints closer to the conversion get more credit. A touchpoint from ${Math.max(
+ Math.round(windowDays / 4),
+ 1
+ )} days before the conversion gets half the credit of one at conversion time.`
+ case AttributionMode.PositionBased:
+ return '40% of the credit goes to the first touchpoint, 40% to the last, and the remaining 20% is split across the rest.'
+ }
+}
+
+let uniqueNode = 0
+
+export function AttributionTable({
+ query,
+ attachTo,
+}: {
+ query: MarketingAnalyticsAttributionQuery
+ attachTo?: LogicWrapper | BuiltLogic
+}): JSX.Element {
+ const [key] = useState(() => `MarketingAttribution.${uniqueNode++}`)
+ const logic = dataNodeLogic({ query, key, dataNodeCollectionId: key })
+ const { response, responseLoading, responseError } = useValues(logic)
+ const { loadData } = useActions(logic)
+ const { breakdownBy, effectiveLookbackDays } = useValues(marketingAttributionLogic)
+ const { baseCurrency } = useValues(teamLogic)
+ useAttachedLogic(logic, attachTo)
+
+ const attributionResponse = response as MarketingAnalyticsAttributionQueryResponse | undefined
+ const rows = attributionResponse?.results ?? []
+ const models = attributionResponse?.models ?? []
+ const hasValue = attributionResponse?.hasValue ?? false
+ const windowDays = attributionResponse?.attributionWindowDays ?? effectiveLookbackDays
+ const dimensionLabel = BREAKDOWN_LABELS[breakdownBy]
+
+ // With repeat conversions counted, conversions-over-visitors is a ratio rather than a share, so it
+ // must not be formatted as a percentage.
+ const countsRepeatConversions = attributionResponse?.allowsMultipleConversionsPerVisitor ?? false
+ const rateLabel = countsRepeatConversions ? 'Per visitor' : 'Conv. rate'
+ const formatRate = (value: number): string =>
+ countsRepeatConversions ? `${humanFriendlyNumber(value, 2)}x` : percentage(value, 2)
+
+ // One scale across every conversions column is what makes bar lengths comparable between models.
+ const maxInfluenced = Math.max(0, ...rows.map((row) => row.influencedConversions))
+
+ const buildColumns = (): LemonTableColumnGroup<MarketingAnalyticsAttributionRow>[] => {
+ const numericColumn = (
+ title: string,
+ tooltip: string,
+ value: (row: MarketingAnalyticsAttributionRow) => number | null,
+ format: (value: number) => string,
+ key: string,
+ options?: { withMagnitudeBar?: boolean; groupBoundary?: boolean }
+ ): LemonTableColumn<MarketingAnalyticsAttributionRow, keyof MarketingAnalyticsAttributionRow | undefined> => ({
+ title,
+ tooltip,
+ key,
+ align: 'right',
+ render: (_, row) => {
+ const raw = value(row)
+ return raw === null ? <span className="text-secondary">-</span> : format(raw)
+ },
+ sorter: (a, b) => (value(a) ?? -1) - (value(b) ?? -1),
+ className: clsx(
+ options?.withMagnitudeBar && 'AttributionTable__magnitude-cell',
+ options?.groupBoundary && 'AttributionTable__group-boundary'
+ ),
+ ...(options?.withMagnitudeBar
+ ? {
+ style: (_, row) =>
+ ({
+ '--attribution-fill': `${
+ maxInfluenced > 0 ? Math.round(((value(row) ?? 0) / maxInfluenced) * 100) : 0
+ }%`,
+ }) as React.CSSProperties,
+ }
+ : {}),
+ })
+
+ return [
+ {
+ children: [
+ {
+ title: dimensionLabel,
+ key: 'breakdown_value',
+ render: (_, row) => (
+ <span className="font-medium">
+ {row.breakdownValue || <span className="text-secondary">(none)</span>}
+ </span>
+ ),
+ sorter: (a, b) => a.breakdownValue.localeCompare(b.breakdownValue),
+ },
+ ],
+ },
+ {
+ title: (
+ <Tooltip
+ title={`Every visitor and conversion that touched this ${dimensionLabel.toLowerCase()} at least once inside the ${windowDays}-day attribution window. One conversion can be influenced by several of them, so these columns add up to more than your total conversions.`}
+ >
+ <span>Influenced</span>
+ </Tooltip>
+ ),
+ children: [
+ numericColumn(
+ 'Visitors',
+ `People who arrived via this ${dimensionLabel.toLowerCase()}, whether or not they converted. Counts arrivals up to ${windowDays} days before the date range, since those visits can still earn credit for conversions in it.`,
+ (row) => row.visitors,
+ (value) => humanFriendlyNumber(value),
+ 'visitors',
+ { groupBoundary: true }
+ ),
+ numericColumn(
+ 'Conversions',
+ 'Conversions with at least one touchpoint here. Counted once per conversion.',
+ (row) => row.influencedConversions,
+ (value) => humanFriendlyNumber(value),
+ 'influenced_conversions',
+ { withMagnitudeBar: true }
+ ),
+ numericColumn(
+ rateLabel,
+ countsRepeatConversions
+ ? `Conversions this ${dimensionLabel.toLowerCase()} influenced, per visitor it brought. Above 1x when people convert more than once.`
+ : `The share of this ${dimensionLabel.toLowerCase()}'s visitors who went on to convert, whichever touchpoint gets the credit.`,
+ (row) => (row.visitors > 0 ? row.influencedConversions / row.visitors : null),
+ formatRate,
+ 'influenced_rate'
+ ),
+ ...(hasValue
+ ? [
+ numericColumn(
+ 'Value',
+ 'Full value of every influenced conversion, also counted in full against the other rows that influenced it.',
+ (row) => row.influencedValue,
+ (value) => formatCurrency(value, baseCurrency),
+ 'influenced_value'
+ ),
+ ]
+ : []),
+ ],
+ },
+ ...models.map((model, index) => ({
+ title: (
+ <Tooltip title={modelTooltip(model, windowDays)}>
+ <span>{MODEL_LABELS[model]}</span>
+ </Tooltip>
+ ),
+ children: [
+ numericColumn(
+ 'Conversions',
+ `Conversions credited to this ${dimensionLabel.toLowerCase()} by the ${MODEL_LABELS[
+ model
+ ].toLowerCase()} model. Fractional when credit is shared across touchpoints.`,
+ (row) => row.models[index]?.conversions ?? null,
+ // Multi-touch credit is fractional; whole numbers make linear look identical to
+ // last touch at low volumes.
+ (value) => humanFriendlyNumber(value, 1),
+ `${model}_conversions`,
+ { withMagnitudeBar: true, groupBoundary: true }
+ ),
+ numericColumn(
+ rateLabel,
+ 'Conversions credited by this model, divided by visitors. The denominator is the same for every model, so the columns are directly comparable.',
+ (row) => row.models[index]?.conversionRate ?? null,
+ formatRate,
+ `${model}_rate`
+ ),
+ ...(hasValue
+ ? [
+ numericColumn(
+ 'Value',
+ `Conversion value credited to this ${dimensionLabel.toLowerCase()} by the ${MODEL_LABELS[
+ model
+ ].toLowerCase()} model.`,
+ (row) => row.models[index]?.conversionValue ?? null,
+ (value) => formatCurrency(value, baseCurrency),
+ `${model}_value`
+ ),
+ ]
+ : []),
+ ],
+ })),
+ ]
+ }
+
+ const columns = buildColumns()
+
+ if (responseError) {
+ return (
+ <InsightErrorState
+ query={query}
+ excludeDetail
+ title={responseError}
+ onRetry={() => loadData('force_blocking')}
+ />
+ )
+ }
+
+ const unattributed = attributionResponse?.unattributedConversions ?? 0
+ const totalConversions = attributionResponse?.totalConversions ?? 0
+
+ // Models only differ when a conversion has more than one touchpoint, so identical numbers across the
+ // board almost always means the goal converts on the visitor's first session.
+ const allModelsAgree =
+ rows.length > 0 &&
+ rows.every((row) => {
+ const conversions = row.models.map((cell) => cell.conversions)
+ return Math.max(...conversions) - Math.min(...conversions) < 0.05
+ })
+
+ return (
+ <div className="flex flex-col gap-4">
+ {!responseLoading && allModelsAgree && (
+ <LemonBanner type="info" dismissKey="marketing-attribution-models-identical">
+ Every model reports the same credit for this goal. That usually means people convert in their first
+ session, so each conversion has a single touchpoint and there is nothing to split. Goals that happen
+ later in the journey, like signing up or paying, show how the models differ.
+ </LemonBanner>
+ )}
+ <AttributionChart rows={rows} models={models} dimensionLabel={dimensionLabel} loading={responseLoading} />
+ <LemonTable
+ className="AttributionTable"
+ columns={columns}
+ dataSource={rows}
+ loading={responseLoading}
+ rowKey="breakdownValue"
+ firstColumnSticky
+ defaultSorting={{ columnKey: 'influenced_conversions', order: -1 }}
+ emptyState={`No conversions were influenced by any ${dimensionLabel.toLowerCase()} in this date range.`}
+ footer={
+ unattributed > 0 || rows.length >= ATTRIBUTION_ROW_LIMIT ? (
+ <div className="flex flex-col gap-1 px-2 py-2 text-secondary">
+ {unattributed > 0 && (
+ <span>
+ {humanFriendlyNumber(unattributed)} of {humanFriendlyNumber(totalConversions)}{' '}
+ conversions had no touchpoints inside the {windowDays}-day window, so they aren't
+ credited to any row.
+ </span>
+ )}
+ {rows.length >= ATTRIBUTION_ROW_LIMIT && (
+ <span>
+ Showing the top {ATTRIBUTION_ROW_LIMIT} by influenced conversions. Sorting reorders
+ these rows.
+ </span>
+ )}
+ </div>
+ ) : undefined
+ }
+ />
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.ts
index cadb70dc5744..1d54014ab0ac 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.ts
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.ts
@@ -67,6 +67,7 @@ export type NativeSourceHierarchyStatus = {
export enum MarketingAnalyticsTab {
DASHBOARD = 'dashboard',
+ ATTRIBUTION = 'attribution',
INTEGRATION_HEALTH = 'integration-health',
}
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
new file mode 100644
index 000000000000..74dd944c9b62
--- /dev/null
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAttributionLogic.ts
@@ -0,0 +1,246 @@
+import { MakeLogicType, actions, connect, kea, path, reducers, selectors } from 'kea'
+
+import {
+ AttributionMode,
+ ConversionGoalFilter,
+ MarketingAnalyticsAttributionBreakdown,
+ MarketingAnalyticsAttributionQuery,
+ NodeKind,
+} from '~/queries/schema/schema-general'
+import { BaseMathType, IntervalType } from '~/types'
+
+import { marketingAnalyticsLogic } from './marketingAnalyticsLogic'
+import { marketingAnalyticsSettingsLogic } from './marketingAnalyticsSettingsLogic'
+
+/** 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
+
+export const BREAKDOWN_LABELS: Record<MarketingAnalyticsAttributionBreakdown, string> = {
+ [MarketingAnalyticsAttributionBreakdown.Channel]: 'Channel',
+ [MarketingAnalyticsAttributionBreakdown.Source]: 'Source',
+ [MarketingAnalyticsAttributionBreakdown.Campaign]: 'Campaign',
+ [MarketingAnalyticsAttributionBreakdown.Medium]: 'Medium',
+ [MarketingAnalyticsAttributionBreakdown.Content]: 'Content',
+ [MarketingAnalyticsAttributionBreakdown.Term]: 'Term',
+ [MarketingAnalyticsAttributionBreakdown.ReferringDomain]: 'Referring domain',
+ [MarketingAnalyticsAttributionBreakdown.LandingPage]: 'Landing page',
+}
+
+export const MODEL_LABELS: Record<AttributionMode, string> = {
+ [AttributionMode.FirstTouch]: 'First touch',
+ [AttributionMode.LastTouch]: 'Last touch',
+ [AttributionMode.Linear]: 'Linear',
+ [AttributionMode.TimeDecay]: 'Time decay',
+ [AttributionMode.PositionBased]: 'Position based',
+}
+
+interface DateFilter {
+ dateFrom: string | null
+ dateTo: string | null
+ interval: IntervalType
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface marketingAttributionLogicValues {
+ dateFilter: {
+ dateFrom: string | null
+ dateTo: string | null
+ interval: IntervalType
+ } // marketingAnalyticsLogic
+ attribution_window_days: number // marketingAnalyticsSettingsLogic
+ conversion_goals: ConversionGoalFilter[] // marketingAnalyticsSettingsLogic
+ allowMultipleConversionsPerVisitor: boolean | null
+ attributableGoals: ConversionGoalFilter[]
+ breakdownBy: MarketingAnalyticsAttributionBreakdown
+ conversionGoalId: string | null
+ effectiveAllowMultipleConversions: boolean
+ effectiveLookbackDays: number
+ excludeDirectTraffic: boolean
+ lookbackWindowDays: number | null
+ optionsOpen: boolean
+ query: MarketingAnalyticsAttributionQuery | null
+ selectedGoalId: string | null
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface marketingAttributionLogicActions {
+ setAllowMultipleConversionsPerVisitor: (allowMultipleConversionsPerVisitor: boolean) => {
+ allowMultipleConversionsPerVisitor: boolean
+ }
+ setBreakdownBy: (breakdownBy: MarketingAnalyticsAttributionBreakdown) => {
+ breakdownBy: MarketingAnalyticsAttributionBreakdown
+ }
+ setConversionGoalId: (conversionGoalId: string) => {
+ conversionGoalId: string
+ }
+ setExcludeDirectTraffic: (excludeDirectTraffic: boolean) => {
+ excludeDirectTraffic: boolean
+ }
+ setLookbackWindowDays: (lookbackWindowDays: number | null) => {
+ lookbackWindowDays: number | null
+ }
+ setOptionsOpen: (optionsOpen: boolean) => {
+ optionsOpen: boolean
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface marketingAttributionLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ attributableGoals: (conversion_goals: ConversionGoalFilter[]) => ConversionGoalFilter[]
+ selectedGoalId: (conversionGoalId: string | null, attributableGoals: ConversionGoalFilter[]) => string | null
+ effectiveLookbackDays: (lookbackWindowDays: number | null, attribution_window_days: number) => number
+ effectiveAllowMultipleConversions: (
+ allowMultipleConversionsPerVisitor: boolean | null,
+ selectedGoalId: string | null,
+ attributableGoals: ConversionGoalFilter[]
+ ) => boolean
+ query: (
+ selectedGoalId: string | null,
+ breakdownBy: MarketingAnalyticsAttributionBreakdown,
+ excludeDirectTraffic: boolean,
+ lookbackWindowDays: number | null,
+ allowMultipleConversionsPerVisitor: boolean | null,
+ dateFilter: {
+ dateFrom: string | null
+ dateTo: string | null
+ interval: IntervalType
+ }
+ ) => MarketingAnalyticsAttributionQuery | null
+ }
+}
+
+export type marketingAttributionLogicType = MakeLogicType<
+ marketingAttributionLogicValues,
+ marketingAttributionLogicActions,
+ Record<string, any>,
+ marketingAttributionLogicMeta
+>
+
+export const marketingAttributionLogic = kea<marketingAttributionLogicType>([
+ path(['scenes', 'webAnalytics', 'marketingAttributionLogic']),
+ connect(() => ({
+ values: [
+ // The tab renders under the scene's shared filter bar, so it reuses that date range rather
+ // than owning a second date control the user would have to keep in sync.
+ marketingAnalyticsLogic,
+ ['dateFilter'],
+ marketingAnalyticsSettingsLogic,
+ ['conversion_goals', 'attribution_window_days'],
+ ],
+ })),
+ actions({
+ setBreakdownBy: (breakdownBy: MarketingAnalyticsAttributionBreakdown) => ({ breakdownBy }),
+ setConversionGoalId: (conversionGoalId: string) => ({ conversionGoalId }),
+ setExcludeDirectTraffic: (excludeDirectTraffic: boolean) => ({ excludeDirectTraffic }),
+ setLookbackWindowDays: (lookbackWindowDays: number | null) => ({ lookbackWindowDays }),
+ setAllowMultipleConversionsPerVisitor: (allowMultipleConversionsPerVisitor: boolean) => ({
+ allowMultipleConversionsPerVisitor,
+ }),
+ setOptionsOpen: (optionsOpen: boolean) => ({ optionsOpen }),
+ }),
+ reducers({
+ breakdownBy: [
+ MarketingAnalyticsAttributionBreakdown.Channel as MarketingAnalyticsAttributionBreakdown,
+ { setBreakdownBy: (_, { breakdownBy }) => breakdownBy },
+ ],
+ conversionGoalId: [
+ null as string | null,
+ { setConversionGoalId: (_, { conversionGoalId }) => conversionGoalId },
+ ],
+ excludeDirectTraffic: [
+ false,
+ { setExcludeDirectTraffic: (_, { excludeDirectTraffic }) => excludeDirectTraffic },
+ ],
+ // null means "use the team's configured window", so a later settings change flows through.
+ lookbackWindowDays: [
+ null as number | null,
+ { setLookbackWindowDays: (_, { lookbackWindowDays }) => lookbackWindowDays },
+ ],
+ optionsOpen: [false, { setOptionsOpen: (_, { optionsOpen }) => optionsOpen }],
+ // null means "follow the goal's own math", so a unique-users goal dedupes without being asked.
+ allowMultipleConversionsPerVisitor: [
+ null as boolean | null,
+ {
+ setAllowMultipleConversionsPerVisitor: (_, { allowMultipleConversionsPerVisitor }) =>
+ allowMultipleConversionsPerVisitor,
+ // A different goal brings different math, so an override chosen for the old one shouldn't stick.
+ setConversionGoalId: () => null,
+ },
+ ],
+ }),
+ selectors({
+ attributableGoals: [
+ (s) => [s.conversion_goals],
+ // Data warehouse goals are excluded: their conversions live in a warehouse table keyed by
+ // distinct id, so the events-based touchpoint query has nothing to join them on.
+ (conversion_goals: ConversionGoalFilter[]): ConversionGoalFilter[] =>
+ (conversion_goals || []).filter((goal) => goal.kind !== NodeKind.DataWarehouseNode),
+ ],
+ selectedGoalId: [
+ (s) => [s.conversionGoalId, s.attributableGoals],
+ (conversionGoalId: string | null, attributableGoals: ConversionGoalFilter[]): string | null => {
+ const stillAvailable = attributableGoals.some((goal) => goal.conversion_goal_id === conversionGoalId)
+ if (conversionGoalId && stillAvailable) {
+ return conversionGoalId
+ }
+ return attributableGoals[0]?.conversion_goal_id ?? null
+ },
+ ],
+ effectiveLookbackDays: [
+ (s) => [s.lookbackWindowDays, s.attribution_window_days],
+ (lookbackWindowDays: number | null, attribution_window_days: number): number =>
+ lookbackWindowDays ?? attribution_window_days,
+ ],
+ effectiveAllowMultipleConversions: [
+ (s) => [s.allowMultipleConversionsPerVisitor, s.selectedGoalId, s.attributableGoals],
+ // Mirrors the runner's default so the checkbox shows what the query will actually do: a
+ // unique-users goal already counts each person once, anything else counts every conversion.
+ (
+ allowMultipleConversionsPerVisitor: boolean | null,
+ selectedGoalId: string | null,
+ attributableGoals: ConversionGoalFilter[]
+ ): boolean => {
+ if (allowMultipleConversionsPerVisitor !== null) {
+ return allowMultipleConversionsPerVisitor
+ }
+ const goal = attributableGoals.find((g) => g.conversion_goal_id === selectedGoalId)
+ return goal?.math !== BaseMathType.UniqueUsers
+ },
+ ],
+ query: [
+ (s) => [
+ s.selectedGoalId,
+ s.breakdownBy,
+ s.excludeDirectTraffic,
+ s.lookbackWindowDays,
+ s.allowMultipleConversionsPerVisitor,
+ s.dateFilter,
+ ],
+ (
+ selectedGoalId: string | null,
+ breakdownBy: MarketingAnalyticsAttributionBreakdown,
+ excludeDirectTraffic: boolean,
+ lookbackWindowDays: number | null,
+ allowMultipleConversionsPerVisitor: boolean | null,
+ dateFilter: DateFilter
+ ): MarketingAnalyticsAttributionQuery | null => {
+ if (!selectedGoalId) {
+ return null
+ }
+ return {
+ kind: NodeKind.MarketingAnalyticsAttributionQuery,
+ dateRange: { date_from: dateFilter.dateFrom, date_to: dateFilter.dateTo },
+ breakdownBy,
+ conversionGoalId: selectedGoalId,
+ excludeDirectTraffic,
+ ...(lookbackWindowDays ? { lookbackWindowDays } : {}),
+ // Omitted when null so the backend applies the goal's own math.
+ ...(allowMultipleConversionsPerVisitor !== null ? { allowMultipleConversionsPerVisitor } : {}),
+ limit: ATTRIBUTION_ROW_LIMIT,
+ properties: [],
+ }
+ },
+ ],
+ }),
+])
diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.py
index be761bb6c9c7..a8a523be5cb2 100644
--- a/posthog/clickhouse/query_tagging.py
+++ b/posthog/clickhouse/query_tagging.py
@@ -263,6 +263,7 @@ def kind_fallback_tags(kind: NodeKind) -> FallbackTags | None:
case (
NodeKind.MARKETING_ANALYTICS_TABLE_QUERY
| NodeKind.MARKETING_ANALYTICS_AGGREGATED_QUERY
+ | NodeKind.MARKETING_ANALYTICS_ATTRIBUTION_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 79152ee03778..7d13816fbe46 100644
--- a/posthog/hogql_queries/query_runner.py
+++ b/posthog/hogql_queries/query_runner.py
@@ -1164,6 +1164,20 @@ def get_query_runner(
user=user,
)
+ if kind == NodeKind.MARKETING_ANALYTICS_ATTRIBUTION_QUERY:
+ from products.marketing_analytics.backend.hogql_queries.attribution_table_query_runner import (
+ MarketingAnalyticsAttributionQueryRunner,
+ )
+
+ return MarketingAnalyticsAttributionQueryRunner(
+ 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/models/team/team_marketing_analytics_config.py b/posthog/models/team/team_marketing_analytics_config.py
index d271ff975c20..e90cc5a5fddd 100644
--- a/posthog/models/team/team_marketing_analytics_config.py
+++ b/posthog/models/team/team_marketing_analytics_config.py
@@ -44,12 +44,20 @@ def validate_sources_map(sources_map: dict) -> None:
)
+# Bounds on how far back attribution may look. Named so query runners taking a per-request window
+# override can enforce the same ceiling as this setting instead of restating the numbers.
+MIN_ATTRIBUTION_WINDOW_DAYS = 1
+MAX_ATTRIBUTION_WINDOW_DAYS = 90
+
+
def validate_attribution_window_days(days: int) -> None:
"""Validate attribution window days is between 1 and 90."""
if not isinstance(days, int):
raise ValidationError("attribution_window_days must be an integer")
- if days < 1 or days > 90:
- raise ValidationError("attribution_window_days must be between 1 and 90")
+ if days < MIN_ATTRIBUTION_WINDOW_DAYS or days > MAX_ATTRIBUTION_WINDOW_DAYS:
+ raise ValidationError(
+ f"attribution_window_days must be between {MIN_ATTRIBUTION_WINDOW_DAYS} and {MAX_ATTRIBUTION_WINDOW_DAYS}"
+ )
def validate_attribution_mode(mode: str) -> None:
diff --git a/posthog/schema.py b/posthog/schema.py
index a7ee2d665a98..ae32924e484d 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -154,6 +154,7 @@ from posthog.schema_enums import (
LogsOrderBy as LogsOrderBy,
LogsSparklineBreakdownBy as LogsSparklineBreakdownBy,
ManualMetricType as ManualMetricType,
+ MarketingAnalyticsAttributionBreakdown as MarketingAnalyticsAttributionBreakdown,
MarketingAnalyticsBaseColumns as MarketingAnalyticsBaseColumns,
MarketingAnalyticsColumnsSchemaNames as MarketingAnalyticsColumnsSchemaNames,
MarketingAnalyticsConstants as MarketingAnalyticsConstants,
@@ -1664,6 +1665,19 @@ class MarkdownBlock(BaseModel):
type: Literal["markdown"] = "markdown"
+class MarketingAnalyticsAttributionModelCell(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ conversionRate: float | None = Field(..., description="conversions / visitors. Null when the row has no visitors.")
+ conversionValue: float | None = Field(..., description="Null unless the goal is revenue-bearing.")
+ conversions: float = Field(
+ ...,
+ description=("Fractional for multi-touch models: each conversion's credit is split across its touchpoints."),
+ )
+ model: AttributionMode
+
+
class MarketingAnalyticsDrillDownConfig(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -2280,7 +2294,7 @@ class QueryResponseAlternative7(BaseModel):
stdout: str | None = None
-class QueryResponseAlternative73(BaseModel):
+class QueryResponseAlternative74(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -5481,6 +5495,31 @@ class MCPToolTopUserItem(BaseModel):
)
+class MarketingAnalyticsAttributionRow(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ breakdownValue: str
+ influencedConversions: int = Field(
+ ...,
+ description=(
+ "Conversions with at least one touchpoint on this dimension. Counted once"
+ " per conversion, so a conversion influenced by several dimensions is"
+ " counted in each of their rows. These deliberately sum to more than the"
+ " total, unlike the per-model columns."
+ ),
+ )
+ influencedValue: float | None = None
+ models: list[MarketingAnalyticsAttributionModelCell] = Field(
+ ...,
+ description=("One cell per model, always in the order given by the response's `models`."),
+ )
+ visitors: int = Field(
+ ...,
+ description=("Unique persons who arrived via this dimension in the date range, converters or not."),
+ )
+
+
class MarketingAnalyticsItem(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -5858,7 +5897,7 @@ class QueryResponseAlternative28(BaseModel):
status: ExternalQueryStatus
-class QueryResponseAlternative80(BaseModel):
+class QueryResponseAlternative81(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -11822,6 +11861,87 @@ class CachedMarketingAnalyticsAggregatedQueryResponse(BaseModel):
)
+class CachedMarketingAnalyticsAttributionQueryResponse(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ allowsMultipleConversionsPerVisitor: bool = Field(
+ ...,
+ description=(
+ "Whether this result counted a repeat converter's every conversion, after"
+ " resolving the query's null against the goal's math. The rate columns are"
+ " a true share only when this is false, so the table reads it to label"
+ " them."
+ ),
+ )
+ attributionWindowDays: int = Field(..., description="The team's configured attribution window, 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 columns."),
+ )
+ hogql: str | None = Field(default=None, description="Generated HogQL query.")
+ is_cached: bool
+ last_refresh: AwareDatetime
+ limit: int | None = None
+ models: list[AttributionMode] = Field(..., description="Model order for the column groups.")
+ 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[MarketingAnalyticsAttributionRow]
+ timezone: str
+ timings: list[QueryTiming] | None = Field(
+ default=None,
+ description=("Measured timings for different parts of the query generation process"),
+ )
+ totalConversions: int = Field(..., description='Total conversions in range, so the footer can say "N of M".')
+ unattributedConversions: int = Field(
+ ...,
+ description=("Conversions with no touchpoint in the window. Reported in the footer, not in any row."),
+ )
+ 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 CachedMarketingAnalyticsTableQueryResponse(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -17483,6 +17603,76 @@ class MarketingAnalyticsAggregatedQueryResponse(BaseModel):
)
+class MarketingAnalyticsAttributionQueryResponse(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ allowsMultipleConversionsPerVisitor: bool = Field(
+ ...,
+ description=(
+ "Whether this result counted a repeat converter's every conversion, after"
+ " resolving the query's null against the goal's math. The rate columns are"
+ " a true share only when this is false, so the table reads it to label"
+ " them."
+ ),
+ )
+ attributionWindowDays: int = Field(..., description="The team's configured attribution window, 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 columns."),
+ )
+ hogql: str | None = Field(default=None, description="Generated HogQL query.")
+ limit: int | None = None
+ models: list[AttributionMode] = Field(..., description="Model order for the column groups.")
+ 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[MarketingAnalyticsAttributionRow]
+ timings: list[QueryTiming] | None = Field(
+ default=None,
+ description=("Measured timings for different parts of the query generation process"),
+ )
+ totalConversions: int = Field(..., description='Total conversions in range, so the footer can say "N of M".')
+ unattributedConversions: int = Field(
+ ...,
+ description=("Conversions with no touchpoint in the window. Reported in the footer, not in any row."),
+ )
+ 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 MarketingAnalyticsConfig(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -19009,6 +19199,76 @@ class QueryResponseAlternative31(BaseModel):
class QueryResponseAlternative32(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ allowsMultipleConversionsPerVisitor: bool = Field(
+ ...,
+ description=(
+ "Whether this result counted a repeat converter's every conversion, after"
+ " resolving the query's null against the goal's math. The rate columns are"
+ " a true share only when this is false, so the table reads it to label"
+ " them."
+ ),
+ )
+ attributionWindowDays: int = Field(..., description="The team's configured attribution window, 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 columns."),
+ )
+ hogql: str | None = Field(default=None, description="Generated HogQL query.")
+ limit: int | None = None
+ models: list[AttributionMode] = Field(..., description="Model order for the column groups.")
+ 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[MarketingAnalyticsAttributionRow]
+ timings: list[QueryTiming] | None = Field(
+ default=None,
+ description=("Measured timings for different parts of the query generation process"),
+ )
+ totalConversions: int = Field(..., description='Total conversions in range, so the footer can say "N of M".')
+ unattributedConversions: int = Field(
+ ...,
+ description=("Conversions with no touchpoint in the window. Reported in the footer, not in any row."),
+ )
+ 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 QueryResponseAlternative33(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -19061,7 +19321,7 @@ class QueryResponseAlternative32(BaseModel):
)
-class QueryResponseAlternative33(BaseModel):
+class QueryResponseAlternative34(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -19114,7 +19374,7 @@ class QueryResponseAlternative33(BaseModel):
)
-class QueryResponseAlternative34(BaseModel):
+class QueryResponseAlternative35(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -19167,7 +19427,7 @@ class QueryResponseAlternative34(BaseModel):
)
-class QueryResponseAlternative35(BaseModel):
+class QueryResponseAlternative36(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -19220,7 +19480,7 @@ class QueryResponseAlternative35(BaseModel):
)
-class QueryResponseAlternative36(BaseModel):
+class QueryResponseAlternative37(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -19273,7 +19533,7 @@ class QueryResponseAlternative36(BaseModel):
)
-class QueryResponseAlternative37(BaseModel):
+class QueryResponseAlternative38(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -19324,7 +19584,7 @@ class QueryResponseAlternative37(BaseModel):
)
-class QueryResponseAlternative38(BaseModel):
+class QueryResponseAlternative39(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -19385,7 +19645,7 @@ class QueryResponseAlternative38(BaseModel):
)
-class QueryResponseAlternative39(BaseModel):
+class QueryResponseAlternative40(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -19438,7 +19698,7 @@ class QueryResponseAlternative39(BaseModel):
)
-class QueryResponseAlternative40(BaseModel):
+class QueryResponseAlternative41(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -19490,7 +19750,7 @@ class QueryResponseAlternative40(BaseModel):
)
-class QueryResponseAlternative41(BaseModel):
+class QueryResponseAlternative42(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -19544,7 +19804,7 @@ class QueryResponseAlternative41(BaseModel):
)
-class QueryResponseAlternative42(BaseModel):
+class QueryResponseAlternative43(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -19592,7 +19852,7 @@ class QueryResponseAlternative42(BaseModel):
)
-class QueryResponseAlternative43(BaseModel):
+class QueryResponseAlternative44(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -19644,7 +19904,7 @@ class QueryResponseAlternative43(BaseModel):
)
-class QueryResponseAlternative44(BaseModel):
+class QueryResponseAlternative45(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -19696,7 +19956,7 @@ class QueryResponseAlternative44(BaseModel):
)
-class QueryResponseAlternative45(BaseModel):
+class QueryResponseAlternative46(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -19749,7 +20009,7 @@ class QueryResponseAlternative45(BaseModel):
)
-class QueryResponseAlternative46(BaseModel):
+class QueryResponseAlternative47(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -19797,7 +20057,7 @@ class QueryResponseAlternative46(BaseModel):
)
-class QueryResponseAlternative47(BaseModel):
+class QueryResponseAlternative48(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -19850,7 +20110,7 @@ class QueryResponseAlternative47(BaseModel):
)
-class QueryResponseAlternative48(BaseModel):
+class QueryResponseAlternative49(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -19901,7 +20161,7 @@ class QueryResponseAlternative48(BaseModel):
)
-class QueryResponseAlternative52(BaseModel):
+class QueryResponseAlternative53(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -19952,7 +20212,7 @@ class QueryResponseAlternative52(BaseModel):
)
-class QueryResponseAlternative54(BaseModel):
+class QueryResponseAlternative55(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20004,7 +20264,7 @@ class QueryResponseAlternative54(BaseModel):
)
-class QueryResponseAlternative55(BaseModel):
+class QueryResponseAlternative56(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20061,7 +20321,7 @@ class QueryResponseAlternative55(BaseModel):
)
-class QueryResponseAlternative56(BaseModel):
+class QueryResponseAlternative57(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20110,7 +20370,7 @@ class QueryResponseAlternative56(BaseModel):
)
-class QueryResponseAlternative57(BaseModel):
+class QueryResponseAlternative58(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20164,7 +20424,7 @@ class QueryResponseAlternative57(BaseModel):
)
-class QueryResponseAlternative58(BaseModel):
+class QueryResponseAlternative59(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20211,7 +20471,7 @@ class QueryResponseAlternative58(BaseModel):
)
-class QueryResponseAlternative59(BaseModel):
+class QueryResponseAlternative60(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20258,7 +20518,7 @@ class QueryResponseAlternative59(BaseModel):
)
-class QueryResponseAlternative60(BaseModel):
+class QueryResponseAlternative61(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20305,7 +20565,7 @@ class QueryResponseAlternative60(BaseModel):
)
-class QueryResponseAlternative62(BaseModel):
+class QueryResponseAlternative63(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20357,7 +20617,7 @@ class QueryResponseAlternative62(BaseModel):
)
-class QueryResponseAlternative64(BaseModel):
+class QueryResponseAlternative65(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20409,7 +20669,7 @@ class QueryResponseAlternative64(BaseModel):
)
-class QueryResponseAlternative65(BaseModel):
+class QueryResponseAlternative66(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20461,7 +20721,7 @@ class QueryResponseAlternative65(BaseModel):
)
-class QueryResponseAlternative66(BaseModel):
+class QueryResponseAlternative67(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20509,7 +20769,7 @@ class QueryResponseAlternative66(BaseModel):
)
-class QueryResponseAlternative67(BaseModel):
+class QueryResponseAlternative68(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20556,7 +20816,7 @@ class QueryResponseAlternative67(BaseModel):
)
-class QueryResponseAlternative68(BaseModel):
+class QueryResponseAlternative69(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20603,7 +20863,7 @@ class QueryResponseAlternative68(BaseModel):
)
-class QueryResponseAlternative69(BaseModel):
+class QueryResponseAlternative70(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20654,7 +20914,7 @@ class QueryResponseAlternative69(BaseModel):
)
-class QueryResponseAlternative70(BaseModel):
+class QueryResponseAlternative71(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20705,7 +20965,7 @@ class QueryResponseAlternative70(BaseModel):
)
-class QueryResponseAlternative71(BaseModel):
+class QueryResponseAlternative72(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20756,7 +21016,7 @@ class QueryResponseAlternative71(BaseModel):
)
-class QueryResponseAlternative72(BaseModel):
+class QueryResponseAlternative73(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20807,7 +21067,7 @@ class QueryResponseAlternative72(BaseModel):
)
-class QueryResponseAlternative74(BaseModel):
+class QueryResponseAlternative75(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20857,7 +21117,7 @@ class QueryResponseAlternative74(BaseModel):
)
-class QueryResponseAlternative75(BaseModel):
+class QueryResponseAlternative76(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20907,7 +21167,7 @@ class QueryResponseAlternative75(BaseModel):
)
-class QueryResponseAlternative76(BaseModel):
+class QueryResponseAlternative77(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20954,7 +21214,7 @@ class QueryResponseAlternative76(BaseModel):
)
-class QueryResponseAlternative77(BaseModel):
+class QueryResponseAlternative78(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21005,7 +21265,7 @@ class QueryResponseAlternative77(BaseModel):
)
-class QueryResponseAlternative81(BaseModel):
+class QueryResponseAlternative82(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21052,7 +21312,7 @@ class QueryResponseAlternative81(BaseModel):
)
-class QueryResponseAlternative82(BaseModel):
+class QueryResponseAlternative83(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21099,7 +21359,7 @@ class QueryResponseAlternative82(BaseModel):
)
-class QueryResponseAlternative83(BaseModel):
+class QueryResponseAlternative84(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21156,7 +21416,7 @@ class QueryResponseAlternative83(BaseModel):
)
-class QueryResponseAlternative84(BaseModel):
+class QueryResponseAlternative85(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21203,7 +21463,7 @@ class QueryResponseAlternative84(BaseModel):
)
-class QueryResponseAlternative85(BaseModel):
+class QueryResponseAlternative86(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21255,7 +21515,7 @@ class QueryResponseAlternative85(BaseModel):
)
-class QueryResponseAlternative86(BaseModel):
+class QueryResponseAlternative87(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21302,7 +21562,7 @@ class QueryResponseAlternative86(BaseModel):
)
-class QueryResponseAlternative87(BaseModel):
+class QueryResponseAlternative88(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21349,7 +21609,7 @@ class QueryResponseAlternative87(BaseModel):
)
-class QueryResponseAlternative88(BaseModel):
+class QueryResponseAlternative89(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21396,7 +21656,7 @@ class QueryResponseAlternative88(BaseModel):
)
-class QueryResponseAlternative89(BaseModel):
+class QueryResponseAlternative90(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21443,7 +21703,7 @@ class QueryResponseAlternative89(BaseModel):
)
-class QueryResponseAlternative90(BaseModel):
+class QueryResponseAlternative91(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21490,7 +21750,7 @@ class QueryResponseAlternative90(BaseModel):
)
-class QueryResponseAlternative91(BaseModel):
+class QueryResponseAlternative92(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21537,7 +21797,7 @@ class QueryResponseAlternative91(BaseModel):
)
-class QueryResponseAlternative92(BaseModel):
+class QueryResponseAlternative93(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21584,7 +21844,7 @@ class QueryResponseAlternative92(BaseModel):
)
-class QueryResponseAlternative93(BaseModel):
+class QueryResponseAlternative94(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21634,7 +21894,7 @@ class QueryResponseAlternative93(BaseModel):
)
-class QueryResponseAlternative94(BaseModel):
+class QueryResponseAlternative95(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21681,7 +21941,7 @@ class QueryResponseAlternative94(BaseModel):
)
-class QueryResponseAlternative95(BaseModel):
+class QueryResponseAlternative96(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21728,7 +21988,7 @@ class QueryResponseAlternative95(BaseModel):
)
-class QueryResponseAlternative96(BaseModel):
+class QueryResponseAlternative97(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21775,7 +22035,7 @@ class QueryResponseAlternative96(BaseModel):
)
-class QueryResponseAlternative97(BaseModel):
+class QueryResponseAlternative98(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21822,7 +22082,7 @@ class QueryResponseAlternative97(BaseModel):
)
-class QueryResponseAlternative98(BaseModel):
+class QueryResponseAlternative99(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21869,7 +22129,7 @@ class QueryResponseAlternative98(BaseModel):
)
-class QueryResponseAlternative99(BaseModel):
+class QueryResponseAlternative100(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21916,7 +22176,7 @@ class QueryResponseAlternative99(BaseModel):
)
-class QueryResponseAlternative100(BaseModel):
+class QueryResponseAlternative101(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21963,7 +22223,7 @@ class QueryResponseAlternative100(BaseModel):
)
-class QueryResponseAlternative101(BaseModel):
+class QueryResponseAlternative102(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22010,7 +22270,7 @@ class QueryResponseAlternative101(BaseModel):
)
-class QueryResponseAlternative102(BaseModel):
+class QueryResponseAlternative103(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -24498,6 +24758,74 @@ class MarketingAnalyticsAggregatedQuery(BaseModel):
version: float | None = Field(default=None, description="version of the node, used for schema migrations")
+class MarketingAnalyticsAttributionQuery(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 counts once or every time. Null"
+ " follows the goal's own math: unique-users goals count each person once,"
+ " count-based goals count every conversion. Set explicitly to override."
+ " Counting every conversion makes the rate columns exceed 100%, since a"
+ " person can convert more times than they visited."
+ ),
+ )
+ breakdownBy: MarketingAnalyticsAttributionBreakdown | None = Field(
+ default=None, description="Row dimension. Defaults to channel."
+ )
+ conversionGoal: ActionConversionGoal | CustomEventConversionGoal | None = None
+ conversionGoalId: str = Field(
+ ...,
+ description=("conversion_goal_id of the goal to attribute. The table is meaningless without one."),
+ )
+ 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 the touchpoint set before weights are computed,"
+ " so the remaining touchpoints renormalize to full credit rather than"
+ " losing direct's share."
+ ),
+ )
+ 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["MarketingAnalyticsAttributionQuery"] = "MarketingAnalyticsAttributionQuery"
+ 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 earn credit,"
+ " overriding the team's configured attribution window for this query only."
+ ),
+ )
+ 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: MarketingAnalyticsAttributionQueryResponse | 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 MarketingAnalyticsTableQuery(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -25988,7 +26316,7 @@ class LifecycleQuery(BaseModel):
version: float | None = Field(default=None, description="version of the node, used for schema migrations")
-class QueryResponseAlternative63(BaseModel):
+class QueryResponseAlternative64(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -26583,7 +26911,7 @@ class QueryResponseAlternative17(BaseModel):
)
-class QueryResponseAlternative50(BaseModel):
+class QueryResponseAlternative51(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -26603,7 +26931,7 @@ class QueryResponseAlternative50(BaseModel):
)
-class QueryResponseAlternative51(BaseModel):
+class QueryResponseAlternative52(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -26659,8 +26987,8 @@ class QueryResponseAlternative(
| QueryResponseAlternative30
| QueryResponseAlternative31
| QueryResponseAlternative32
- | Any
| QueryResponseAlternative33
+ | Any
| QueryResponseAlternative34
| QueryResponseAlternative35
| QueryResponseAlternative36
@@ -26676,17 +27004,17 @@ class QueryResponseAlternative(
| QueryResponseAlternative46
| QueryResponseAlternative47
| QueryResponseAlternative48
- | QueryResponseAlternative50
+ | QueryResponseAlternative49
| QueryResponseAlternative51
| QueryResponseAlternative52
- | QueryResponseAlternative54
+ | QueryResponseAlternative53
| QueryResponseAlternative55
| QueryResponseAlternative56
| QueryResponseAlternative57
| QueryResponseAlternative58
| QueryResponseAlternative59
| QueryResponseAlternative60
- | QueryResponseAlternative62
+ | QueryResponseAlternative61
| QueryResponseAlternative63
| QueryResponseAlternative64
| QueryResponseAlternative65
@@ -26702,7 +27030,7 @@ class QueryResponseAlternative(
| QueryResponseAlternative75
| QueryResponseAlternative76
| QueryResponseAlternative77
- | QueryResponseAlternative80
+ | QueryResponseAlternative78
| QueryResponseAlternative81
| QueryResponseAlternative82
| QueryResponseAlternative83
@@ -26725,6 +27053,7 @@ class QueryResponseAlternative(
| QueryResponseAlternative100
| QueryResponseAlternative101
| QueryResponseAlternative102
+ | QueryResponseAlternative103
]
):
root: (
@@ -26761,8 +27090,8 @@ class QueryResponseAlternative(
| QueryResponseAlternative30
| QueryResponseAlternative31
| QueryResponseAlternative32
- | Any
| QueryResponseAlternative33
+ | Any
| QueryResponseAlternative34
| QueryResponseAlternative35
| QueryResponseAlternative36
@@ -26778,17 +27107,17 @@ class QueryResponseAlternative(
| QueryResponseAlternative46
| QueryResponseAlternative47
| QueryResponseAlternative48
- | QueryResponseAlternative50
+ | QueryResponseAlternative49
| QueryResponseAlternative51
| QueryResponseAlternative52
- | QueryResponseAlternative54
+ | QueryResponseAlternative53
| QueryResponseAlternative55
| QueryResponseAlternative56
| QueryResponseAlternative57
| QueryResponseAlternative58
| QueryResponseAlternative59
| QueryResponseAlternative60
- | QueryResponseAlternative62
+ | QueryResponseAlternative61
| QueryResponseAlternative63
| QueryResponseAlternative64
| QueryResponseAlternative65
@@ -26804,7 +27133,7 @@ class QueryResponseAlternative(
| QueryResponseAlternative75
| QueryResponseAlternative76
| QueryResponseAlternative77
- | QueryResponseAlternative80
+ | QueryResponseAlternative78
| QueryResponseAlternative81
| QueryResponseAlternative82
| QueryResponseAlternative83
@@ -26827,6 +27156,7 @@ class QueryResponseAlternative(
| QueryResponseAlternative100
| QueryResponseAlternative101
| QueryResponseAlternative102
+ | QueryResponseAlternative103
)
@@ -27733,6 +28063,7 @@ class HogQLAutocomplete(BaseModel):
| HogQLAutocomplete
| MarketingAnalyticsTableQuery
| MarketingAnalyticsAggregatedQuery
+ | MarketingAnalyticsAttributionQuery
| NonIntegratedConversionsTableQuery
| WebOverviewQuery
| WebStatsTableQuery
@@ -27837,6 +28168,7 @@ class HogQLMetadata(BaseModel):
| HogQLAutocomplete
| MarketingAnalyticsTableQuery
| MarketingAnalyticsAggregatedQuery
+ | MarketingAnalyticsAttributionQuery
| NonIntegratedConversionsTableQuery
| WebOverviewQuery
| WebStatsTableQuery
@@ -27975,6 +28307,7 @@ class MaxInsightContext(BaseModel):
| WebNotableChangesQuery
| MarketingAnalyticsTableQuery
| MarketingAnalyticsAggregatedQuery
+ | MarketingAnalyticsAttributionQuery
| NonIntegratedConversionsTableQuery
| DataVisualizationNode
| DataTableNode
@@ -28107,6 +28440,7 @@ class QueryRequest(BaseModel):
| WebNotableChangesQuery
| MarketingAnalyticsTableQuery
| MarketingAnalyticsAggregatedQuery
+ | MarketingAnalyticsAttributionQuery
| NonIntegratedConversionsTableQuery
| DataVisualizationNode
| DataTableNode
@@ -28231,6 +28565,7 @@ class QuerySchemaRoot(
| WebNotableChangesQuery
| MarketingAnalyticsTableQuery
| MarketingAnalyticsAggregatedQuery
+ | MarketingAnalyticsAttributionQuery
| NonIntegratedConversionsTableQuery
| DataVisualizationNode
| DataTableNode
@@ -28325,6 +28660,7 @@ class QuerySchemaRoot(
| WebNotableChangesQuery
| MarketingAnalyticsTableQuery
| MarketingAnalyticsAggregatedQuery
+ | MarketingAnalyticsAttributionQuery
| NonIntegratedConversionsTableQuery
| DataVisualizationNode
| DataTableNode
@@ -28424,6 +28760,7 @@ class QueryUpgradeRequest(BaseModel):
| WebNotableChangesQuery
| MarketingAnalyticsTableQuery
| MarketingAnalyticsAggregatedQuery
+ | MarketingAnalyticsAttributionQuery
| NonIntegratedConversionsTableQuery
| DataVisualizationNode
| DataTableNode
@@ -28523,6 +28860,7 @@ class QueryUpgradeResponse(BaseModel):
| WebNotableChangesQuery
| MarketingAnalyticsTableQuery
| MarketingAnalyticsAggregatedQuery
+ | MarketingAnalyticsAttributionQuery
| NonIntegratedConversionsTableQuery
| DataVisualizationNode
| DataTableNode
@@ -28804,6 +29142,7 @@ class VisualizationArtifactContent(BaseModel):
| WebNotableChangesQuery
| MarketingAnalyticsTableQuery
| MarketingAnalyticsAggregatedQuery
+ | MarketingAnalyticsAttributionQuery
| NonIntegratedConversionsTableQuery
| DataVisualizationNode
| DataTableNode
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index 03ecfc058736..d2ad7bf4b6b3 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -2941,6 +2941,17 @@ class NeighborDirection(StrEnum):
AFTER = "after"
+class MarketingAnalyticsAttributionBreakdown(StrEnum):
+ CHANNEL = "channel"
+ SOURCE = "source"
+ CAMPAIGN = "campaign"
+ MEDIUM = "medium"
+ CONTENT = "content"
+ TERM = "term"
+ REFERRING_DOMAIN = "referring_domain"
+ LANDING_PAGE = "landing_page"
+
+
class MarketingAnalyticsBaseColumns(StrEnum):
ID = "ID"
CAMPAIGN = "Campaign"
@@ -3213,6 +3224,7 @@ class NodeKind(StrEnum):
WEB_NOTABLE_CHANGES_QUERY = "WebNotableChangesQuery"
MARKETING_ANALYTICS_TABLE_QUERY = "MarketingAnalyticsTableQuery"
MARKETING_ANALYTICS_AGGREGATED_QUERY = "MarketingAnalyticsAggregatedQuery"
+ MARKETING_ANALYTICS_ATTRIBUTION_QUERY = "MarketingAnalyticsAttributionQuery"
NON_INTEGRATED_CONVERSIONS_TABLE_QUERY = "NonIntegratedConversionsTableQuery"
EXPERIMENT_METRIC = "ExperimentMetric"
EXPERIMENT_QUERY = "ExperimentQuery"
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
new file mode 100644
index 000000000000..1155bf30c90b
--- /dev/null
+++ b/products/marketing_analytics/backend/hogql_queries/attribution_table_query_runner.py
@@ -0,0 +1,960 @@
+"""Attribution table: every attribution model's credit for one conversion goal, side by side.
+
+The Dashboard applies the team's single configured `attribution_mode`. This runner instead computes all
+five models in one pass, so a marketer can see how differently each channel gets paid depending on how
+credit is split — a channel that looks great under last touch and poor under first touch is a channel
+whose spend is being misjudged.
+
+Two things differ deliberately from the Dashboard's attribution pipeline in `conversion_goal_processor`:
+
+1. A touchpoint here is a **session**, identified through the `events.session` lazy join, not a
+ UTM-tagged pageview. That means Direct / Organic search / Referral appear as rows (the whole point of
+ comparing models is seeing what unpaid touches contribute), and a visitor who lands with a UTM and
+ browses ten pages counts once rather than ten times.
+2. Only one dimension is tracked instead of nine, because the table breaks down by one at a time.
+
+Consequence worth knowing: the Last touch column will not equal the Dashboard's conversion count for the
+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
+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_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
+
+# 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.
+MODEL_ORDER: list[AttributionMode] = [
+ AttributionMode.FIRST_TOUCH,
+ AttributionMode.LAST_TOUCH,
+ AttributionMode.LINEAR,
+ AttributionMode.TIME_DECAY,
+ AttributionMode.POSITION_BASED,
+]
+
+# Per-model weight column aliases, parallel to MODEL_ORDER.
+_WEIGHT_ALIASES: dict[AttributionMode, str] = {
+ AttributionMode.FIRST_TOUCH: "w_first",
+ AttributionMode.LAST_TOUCH: "w_last",
+ AttributionMode.LINEAR: "w_linear",
+ AttributionMode.TIME_DECAY: "w_decay",
+ 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"
+_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"
+_INFLUENCED_VALUE = "influenced_value"
+_TOTAL_CONVERSIONS = "total_conversions"
+_ATTRIBUTED_CONVERSIONS = "attributed_conversions"
+_JOIN_KEY = "footer_key"
+# ARRAY JOIN index identifying a conversion within its person.
+_CONVERSION_INDEX = "i"
+
+
+def _ordered_weight_aliases() -> list[str]:
+ """Producers and consumers of the per-model columns iterate this rather than `_WEIGHT_ALIASES.values()`,
+ so reordering that dict literal can't pair one model's numbers with another's column."""
+ return [_WEIGHT_ALIASES[model] for model in MODEL_ORDER]
+
+
+class MarketingAnalyticsAttributionQueryRunner(
+ MarketingAnalyticsBaseQueryRunner[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:
+ """(A) Unique visitors per dimension, converters or not.
+
+ Shares the touchpoint definition and the lookback-extended window with the credit side. Bounding
+ visitors to the display window instead let a conversion be credited to a touch from before the
+ range while its person was missing from the denominator, reporting rates above 100%.
+ """
+ breakdown = self._breakdown_expr()
+ return ast.SelectQuery(
+ select=[
+ ast.Alias(alias=_BREAKDOWN_VALUE, expr=breakdown),
+ ast.Alias(
+ alias=_VISITORS,
+ expr=ast.Call(name="uniq", args=[ast.Field(chain=["events", "person_id"])]),
+ ),
+ ],
+ select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),
+ where=ast.And(
+ exprs=[
+ self._touchpoint_condition(),
+ *self._lookback_date_conditions(date_range),
+ ]
+ ),
+ 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.
+
+ Every builder maps over the same `ts`, so all five arrays have identical length — that is what
+ lets (E) explode them with a single shared ARRAY JOIN instead of five.
+ """
+ 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"]),
+ ],
+ )
+
+ conversion = ast.ArrayAccess(
+ array=ast.Field(chain=["conversions"]), property=ast.Field(chain=[_CONVERSION_INDEX])
+ )
+
+ select: list[ast.Expr] = [
+ ast.Field(chain=["person_id"]),
+ # The ARRAY JOIN index identifies this conversion within the person. Carried downstream
+ # because timestamps don't: they're truncated to whole seconds, so two conversions in the
+ # same second would otherwise group together as one.
+ ast.Field(chain=[_CONVERSION_INDEX]),
+ ast.Alias(alias="conversion_time", expr=ast.TupleAccess(tuple=conversion, index=1)),
+ ast.Alias(alias="conversion_value", expr=ast.TupleAccess(tuple=conversion, index=2)),
+ ast.Alias(alias="tps", expr=in_window),
+ ast.Alias(
+ # Deliberately not named `ts`: attribution_weights substitutes this reference inside
+ # arrayMap lambdas whose parameter is `ts`, and the shadowed name would resolve to the
+ # scalar argument instead of the array.
+ alias="touch_ts",
+ expr=ast.Call(
+ name="arrayMap",
+ args=[
+ ast.Lambda(args=["t"], expr=ast.TupleAccess(tuple=ast.Field(chain=["t"]), index=1)),
+ ast.Field(chain=["tps"]),
+ ],
+ ),
+ ),
+ ast.Alias(
+ alias="dims",
+ 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=_WEIGHT_ALIASES[AttributionMode.FIRST_TOUCH], expr=build_first_touch_weights(ts)),
+ ast.Alias(alias=_WEIGHT_ALIASES[AttributionMode.LAST_TOUCH], expr=build_last_touch_weights(ts)),
+ ast.Alias(alias=_WEIGHT_ALIASES[AttributionMode.LINEAR], expr=build_linear_weights(ts)),
+ ast.Alias(
+ alias=_WEIGHT_ALIASES[AttributionMode.TIME_DECAY],
+ expr=build_time_decay_weights(ts, conversion_time, self.attribution_window_seconds),
+ ),
+ ast.Alias(alias=_WEIGHT_ALIASES[AttributionMode.POSITION_BASED], expr=build_position_based_weights(ts)),
+ ]
+
+ return ast.SelectQuery(
+ select=select,
+ 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_per_touchpoint_select(self) -> ast.SelectQuery:
+ """(E) One row per touchpoint, indexing all five weight arrays off one ARRAY JOIN."""
+ k = ast.Field(chain=["k"])
+ select: list[ast.Expr] = [
+ ast.Field(chain=["person_id"]),
+ ast.Field(chain=[_CONVERSION_INDEX]),
+ ast.Field(chain=["conversion_value"]),
+ ast.Alias(
+ alias=_BREAKDOWN_VALUE,
+ expr=ast.ArrayAccess(array=ast.Field(chain=["dims"]), property=k),
+ ),
+ ]
+ for alias in _ordered_weight_aliases():
+ select.append(ast.Alias(alias=alias, expr=ast.ArrayAccess(array=ast.Field(chain=[alias]), property=k)))
+
+ return ast.SelectQuery(
+ select=select,
+ select_from=ast.JoinExpr(table=ast.Field(chain=[_PER_CONVERSION_CTE])),
+ array_join_op="ARRAY JOIN",
+ array_join_list=[
+ ast.Alias(alias="k", expr=ast.Call(name="arrayEnumerate", args=[ast.Field(chain=["touch_ts"])]))
+ ],
+ )
+
+ def _build_per_conversion_dim_select(self) -> ast.SelectQuery:
+ """(F) Collapse repeat touches on the same dimension within one conversion.
+
+ Gives "influenced" its once-per-conversion semantics, and rolls the weights up: a channel touched
+ on 3 of 5 sessions earns 0.6 of the linear credit as one row, not three rows of 0.2.
+
+ Keyed on the conversion's index within its person, not its timestamp: timestamps are truncated to
+ whole seconds, so two conversions in the same second would merge into one.
+ """
+ select: list[ast.Expr] = [
+ ast.Field(chain=[_BREAKDOWN_VALUE]),
+ ast.Field(chain=["person_id"]),
+ ast.Field(chain=[_CONVERSION_INDEX]),
+ ast.Alias(alias="conv_value", expr=ast.Call(name="any", args=[ast.Field(chain=["conversion_value"])])),
+ ]
+ for alias in _ordered_weight_aliases():
+ select.append(ast.Alias(alias=alias, expr=ast.Call(name="sum", args=[ast.Field(chain=[alias])])))
+
+ return ast.SelectQuery(
+ select=select,
+ select_from=ast.JoinExpr(table=ast.Field(chain=[_PER_TOUCHPOINT_CTE])),
+ group_by=[
+ ast.Field(chain=[_BREAKDOWN_VALUE]),
+ ast.Field(chain=["person_id"]),
+ ast.Field(chain=[_CONVERSION_INDEX]),
+ ],
+ )
+
+ def _build_totals_select(self) -> ast.SelectQuery:
+ """(G) One row per dimension: influenced counts plus each model's weighted credit."""
+ select: list[ast.Expr] = [
+ ast.Field(chain=[_BREAKDOWN_VALUE]),
+ ast.Alias(alias=_INFLUENCED_CONVERSIONS, expr=ast.Call(name="count", args=[])),
+ ast.Alias(alias=_INFLUENCED_VALUE, expr=ast.Call(name="sum", args=[ast.Field(chain=["conv_value"])])),
+ ]
+ for alias in _ordered_weight_aliases():
+ select.append(
+ ast.Alias(alias=f"{alias}_conversions", expr=ast.Call(name="sum", args=[ast.Field(chain=[alias])]))
+ )
+ select.append(
+ ast.Alias(
+ alias=f"{alias}_value",
+ expr=ast.Call(
+ name="sum",
+ args=[
+ ast.ArithmeticOperation(
+ left=ast.Field(chain=["conv_value"]),
+ op=ast.ArithmeticOperationOp.Mult,
+ right=ast.Field(chain=[alias]),
+ )
+ ],
+ ),
+ )
+ )
+
+ return ast.SelectQuery(
+ select=select,
+ select_from=ast.JoinExpr(table=ast.Field(chain=[_PER_CONVERSION_DIM_CTE])),
+ group_by=[ast.Field(chain=[_BREAKDOWN_VALUE])],
+ )
+
+ # ------------------------------------------------------------------ main query
+
+ def to_query(self) -> ast.SelectQuery:
+ date_range = self.query_date_range
+
+ ctes: dict[str, ast.CTE] = {}
+ 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,
+ 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_CTE] = ast.CTE(
+ name=_PER_CONVERSION_CTE,
+ expr=self._build_per_conversion_select(),
+ cte_type="subquery",
+ materialized=True,
+ )
+ ctes[_PER_TOUCHPOINT_CTE] = ast.CTE(
+ name=_PER_TOUCHPOINT_CTE, expr=self._build_per_touchpoint_select(), cte_type="subquery"
+ )
+ ctes[_PER_CONVERSION_DIM_CTE] = ast.CTE(
+ name=_PER_CONVERSION_DIM_CTE, expr=self._build_per_conversion_dim_select(), cte_type="subquery"
+ )
+ ctes[_TOTALS_CTE] = ast.CTE(name=_TOTALS_CTE, expr=self._build_totals_select(), cte_type="subquery")
+ ctes[_ROWS_CTE] = ast.CTE(name=_ROWS_CTE, expr=self._build_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
+
+ def _build_footer_select(self) -> ast.SelectQuery:
+ """(I) One row reconciling what the models could and couldn't credit.
+
+ Its own CTE rather than two scalar subqueries hanging off the outer SELECT, for two reasons.
+ `per_conversion` is read once here instead of twice. And a SELECT-list scalar is evaluated per
+ output row, so a query that returns no dimension rows would report zero conversions rather than
+ "you have conversions and none of them could be credited", which is the more useful of the two.
+ """
+ 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.Call(name="length", args=[ast.Field(chain=["tps"])]),
+ 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_CTE])),
+ )
+
+ def _build_outer_select(self) -> ast.SelectQuery:
+ """(J) Attach the footer counts to every row.
+
+ LEFT from the footer, which always has exactly one row, so the reconciliation survives a goal
+ whose conversions produced no dimension rows at all. That leaves one placeholder row when there
+ is nothing to show; `_JOIN_KEY` is 0 on it, and `_calculate` drops it.
+ """
+ select: list[ast.Expr] = [
+ ast.Alias(alias=name, expr=ast.Field(chain=[_ROWS_CTE, name])) for name in self._row_column_names()
+ ]
+ 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=[_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=[_ROWS_CTE]),
+ constraint=ast.JoinConstraint(
+ expr=ast.CompareOperation(
+ left=ast.Field(chain=[_FOOTER_CTE, _JOIN_KEY]),
+ op=ast.CompareOperationOp.Eq,
+ right=ast.Field(chain=[_ROWS_CTE, _JOIN_KEY]),
+ ),
+ constraint_type="ON",
+ ),
+ ),
+ ),
+ # Server ordering only decides which rows make the page; the table re-sorts client side.
+ order_by=[
+ ast.OrderExpr(expr=ast.Field(chain=[_INFLUENCED_CONVERSIONS]), order="DESC"),
+ ast.OrderExpr(expr=ast.Field(chain=[_VISITORS]), order="DESC"),
+ ],
+ limit=ast.Constant(value=(self.query.limit or DEFAULT_LIMIT) + PAGINATION_EXTRA),
+ offset=ast.Constant(value=self.query.offset or 0),
+ )
+
+ def _row_column_names(self) -> list[str]:
+ """The dimension columns, in the order `_build_rows_select` produces them."""
+ names = [_BREAKDOWN_VALUE, _VISITORS, _INFLUENCED_CONVERSIONS, _INFLUENCED_VALUE]
+ for alias in _ordered_weight_aliases():
+ names.extend([f"{alias}_conversions", f"{alias}_value"])
+ return names
+
+ def _build_rows_select(self) -> ast.SelectQuery:
+ """(H) Join credit onto reach.
+
+ FULL OUTER so a dimension keeps its row whether or not it has both sides: traffic that never
+ converted still shows visitors, and a credited row can't silently vanish if reach drops it.
+ """
+ totals = ast.Field(chain=[_TOTALS_CTE, _BREAKDOWN_VALUE])
+ reach = ast.Field(chain=[_REACH_CTE, _BREAKDOWN_VALUE])
+
+ select: list[ast.Expr] = [
+ ast.Alias(
+ alias=_BREAKDOWN_VALUE,
+ expr=ast.Call(
+ name="coalesce",
+ args=[ast.Call(name="nullIf", args=[totals, ast.Constant(value="")]), reach],
+ ),
+ ),
+ ast.Alias(
+ alias=_VISITORS,
+ expr=ast.Call(
+ name="ifNull",
+ args=[ast.Field(chain=[_REACH_CTE, _VISITORS]), ast.Constant(value=0)],
+ ),
+ ),
+ ast.Alias(
+ alias=_INFLUENCED_CONVERSIONS,
+ expr=ast.Call(
+ name="ifNull",
+ args=[ast.Field(chain=[_TOTALS_CTE, _INFLUENCED_CONVERSIONS]), ast.Constant(value=0)],
+ ),
+ ),
+ ast.Alias(
+ alias=_INFLUENCED_VALUE,
+ expr=ast.Call(
+ name="ifNull",
+ args=[ast.Field(chain=[_TOTALS_CTE, _INFLUENCED_VALUE]), ast.Constant(value=0.0)],
+ ),
+ ),
+ ]
+ for alias in _ordered_weight_aliases():
+ for suffix in ("conversions", "value"):
+ col = f"{alias}_{suffix}"
+ select.append(
+ ast.Alias(
+ alias=col,
+ expr=ast.Call(
+ name="ifNull",
+ args=[ast.Field(chain=[_TOTALS_CTE, col]), ast.Constant(value=0.0)],
+ ),
+ )
+ )
+
+ # Constant key the footer joins on, and the marker that tells a real row from the placeholder
+ # the outer LEFT JOIN emits when there are no rows at all.
+ select.append(ast.Alias(alias=_JOIN_KEY, expr=ast.Constant(value=1)))
+
+ join = ast.JoinExpr(
+ table=ast.Field(chain=[_TOTALS_CTE]),
+ next_join=ast.JoinExpr(
+ join_type="FULL OUTER JOIN",
+ table=ast.Field(chain=[_REACH_CTE]),
+ constraint=ast.JoinConstraint(
+ expr=ast.CompareOperation(left=totals, op=ast.CompareOperationOp.Eq, right=reach),
+ constraint_type="ON",
+ ),
+ ),
+ )
+
+ return ast.SelectQuery(select=select, select_from=join)
+
+ # ------------------------------------------------------------------ execution
+
+ def _calculate(self) -> MarketingAnalyticsAttributionQueryResponse:
+ query = self.to_query()
+
+ response = execute_hogql_query(
+ query_type="marketing_analytics_attribution_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 dimension 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 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 MarketingAnalyticsAttributionQueryResponse(
+ results=rows,
+ models=MODEL_ORDER,
+ hasValue=has_value,
+ attributionWindowDays=self.lookback_window_days,
+ allowsMultipleConversionsPerVisitor=self.allows_multiple_conversions_per_visitor,
+ unattributedConversions=max(total_conversions - attributed_conversions, 0),
+ totalConversions=total_conversions,
+ hogql=response.hogql,
+ timings=response.timings,
+ modifiers=self.modifiers,
+ hasMore=has_more,
+ limit=requested_limit,
+ offset=self.query.offset or 0,
+ )
+
+ def _build_row(self, row: dict[str, Any], *, has_value: bool) -> MarketingAnalyticsAttributionRow:
+ """The rate is derived here rather than in SQL so the frontend keeps the raw numerator and
+ denominator for its tooltips."""
+ visitors = int(row.get(_VISITORS) or 0)
+
+ models: list[MarketingAnalyticsAttributionModelCell] = []
+ for model in MODEL_ORDER:
+ alias = _WEIGHT_ALIASES[model]
+ conversions = float(row.get(f"{alias}_conversions") or 0.0)
+ value = float(row.get(f"{alias}_value") or 0.0)
+ models.append(
+ MarketingAnalyticsAttributionModelCell(
+ model=model,
+ conversions=conversions,
+ conversionRate=(conversions / visitors) if visitors else None,
+ conversionValue=value if has_value else None,
+ )
+ )
+
+ return MarketingAnalyticsAttributionRow(
+ breakdownValue=str(row.get(_BREAKDOWN_VALUE) or ""),
+ visitors=visitors,
+ influencedConversions=int(row.get(_INFLUENCED_CONVERSIONS) or 0),
+ 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/attribution_weights.py b/products/marketing_analytics/backend/hogql_queries/attribution_weights.py
new file mode 100644
index 000000000000..33b921cb7b3c
--- /dev/null
+++ b/products/marketing_analytics/backend/hogql_queries/attribution_weights.py
@@ -0,0 +1,285 @@
+"""Per-touchpoint credit weights for each attribution model.
+
+Every builder returns an array expression parallel to `filtered_ts` (the touchpoint timestamps inside the
+attribution window, ascending or not — order is never assumed). Weights sum to 1.0 per conversion, so
+summing a model's weights across every row reproduces the total conversion count.
+
+Because all five builders map over the same `filtered_ts`, their outputs are guaranteed to be the same
+length. That's what lets a caller emit all five arrays and explode them with a single shared
+`ARRAY JOIN arrayEnumerate(...)`, computing every model in one pass over the events table.
+
+Caller beware: `filtered_ts` is substituted inside `arrayMap` lambdas, so if it's a bare field reference
+its name must not collide with a lambda parameter used below — `ts`, `w`, `_x`, `_pw`, `_j`. A collision
+resolves the reference to the scalar lambda argument instead of the array, which ClickHouse rejects with
+"argument for function arrayMin must be array".
+"""
+
+import math
+
+from posthog.hogql import ast
+
+DAY_IN_SECONDS = 86400
+LN2 = math.log(2) # ≈ 0.693, used in half-life formula: weight = exp(-ln(2) * t / half_life)
+# Half-life = attribution_window / 4, so a 90-day window gives ~22.5-day half-life.
+# At t = half_life, weight = exp(-ln(2)) = 0.5 (exactly half).
+# This follows the industry standard (Google Analytics, Adobe, Mixpanel all use 7-day half-life).
+TIME_DECAY_HALF_LIFE_DIVISOR = 4
+
+
+def build_linear_weights(filtered_ts: ast.Expr) -> ast.Expr:
+ """Equal weight for all touchpoints: 1.0 / n."""
+ n = ast.Call(name="toFloat", args=[ast.Call(name="length", args=[filtered_ts])])
+ return ast.Call(
+ name="arrayMap",
+ args=[
+ ast.Lambda(
+ args=["_x"],
+ expr=ast.ArithmeticOperation(
+ left=ast.Constant(value=1.0),
+ op=ast.ArithmeticOperationOp.Div,
+ right=ast.Call(name="greatest", args=[n, ast.Constant(value=1.0)]),
+ ),
+ ),
+ filtered_ts,
+ ],
+ )
+
+
+def build_time_decay_weights(
+ filtered_ts: ast.Expr, conversion_time: ast.Expr, attribution_window_seconds: int
+) -> ast.Expr:
+ """Exponential half-life decay: weight = exp(-ln(2) * delta / half_life).
+
+ At t = half_life, weight = 0.5 (exactly half). This matches the industry
+ standard used by Google Analytics, Adobe Analytics, and Mixpanel.
+ The half-life scales with the attribution window (window / 4).
+ Weights are normalized so they sum to 1.
+ """
+ half_life_seconds = max(attribution_window_seconds // TIME_DECAY_HALF_LIFE_DIVISOR, DAY_IN_SECONDS)
+ # weight = exp(-ln(2) * (conversion_time - ts) / half_life)
+ raw_weights = ast.Call(
+ name="arrayMap",
+ args=[
+ ast.Lambda(
+ args=["ts"],
+ expr=ast.Call(
+ name="exp",
+ args=[
+ ast.ArithmeticOperation(
+ left=ast.Constant(value=-LN2),
+ op=ast.ArithmeticOperationOp.Mult,
+ right=ast.ArithmeticOperation(
+ left=ast.ArithmeticOperation(
+ left=conversion_time,
+ op=ast.ArithmeticOperationOp.Sub,
+ right=ast.Field(chain=["ts"]),
+ ),
+ op=ast.ArithmeticOperationOp.Div,
+ right=ast.Constant(value=half_life_seconds),
+ ),
+ ),
+ ],
+ ),
+ ),
+ filtered_ts,
+ ],
+ )
+ # Normalize: divide each weight by sum of all weights.
+ # Note: raw_weights AST node is referenced twice (in arraySum and as the
+ # arrayMap input), so ClickHouse evaluates the exp() computation twice per row.
+ # This is acceptable because touchpoint arrays are small (typically 3-10 elements).
+ weight_sum = ast.Call(name="arraySum", args=[raw_weights])
+ return ast.Call(
+ name="arrayMap",
+ args=[
+ ast.Lambda(
+ args=["w"],
+ expr=ast.ArithmeticOperation(
+ left=ast.Field(chain=["w"]),
+ op=ast.ArithmeticOperationOp.Div,
+ right=ast.Call(name="greatest", args=[weight_sum, ast.Constant(value=0.000001)]),
+ ),
+ ),
+ raw_weights,
+ ],
+ )
+
+
+def build_position_based_weights(filtered_ts: ast.Expr) -> ast.Expr:
+ """40% first touch, 40% last touch, 20% distributed among middle touchpoints.
+
+ Uses arrayMin/arrayMax to identify first/last by timestamp value,
+ avoiding dependency on array ordering (groupArray doesn't guarantee order).
+
+ Edge cases:
+ - 0 touchpoints: empty array (ARRAY JOIN produces no rows)
+ - 1 touchpoint: [1.0]
+ - 2 touchpoints: [0.5, 0.5]
+ - Duplicate timestamps: if multiple touchpoints share min/max timestamp,
+ all get 0.4 weight before normalization. Normalization rescues the total
+ to 1.0, but credit distribution may deviate from the intended 40/20/40.
+ """
+ n = ast.Call(name="toFloat", args=[ast.Call(name="length", args=[filtered_ts])])
+ middle_weight = ast.ArithmeticOperation(
+ left=ast.Constant(value=0.2),
+ op=ast.ArithmeticOperationOp.Div,
+ right=ast.Call(
+ name="greatest",
+ args=[
+ ast.ArithmeticOperation(
+ left=n,
+ op=ast.ArithmeticOperationOp.Sub,
+ right=ast.Constant(value=2.0),
+ ),
+ ast.Constant(value=1.0),
+ ],
+ ),
+ )
+
+ min_ts = ast.Call(name="arrayMin", args=[filtered_ts])
+ max_ts = ast.Call(name="arrayMax", args=[filtered_ts])
+
+ position_weights = ast.Call(
+ name="arrayMap",
+ args=[
+ ast.Lambda(
+ args=["ts"],
+ expr=ast.Call(
+ name="if",
+ args=[
+ ast.CompareOperation(
+ left=ast.Field(chain=["ts"]),
+ op=ast.CompareOperationOp.Eq,
+ right=min_ts,
+ ),
+ ast.Constant(value=0.4),
+ ast.Call(
+ name="if",
+ args=[
+ ast.CompareOperation(
+ left=ast.Field(chain=["ts"]),
+ op=ast.CompareOperationOp.Eq,
+ right=max_ts,
+ ),
+ ast.Constant(value=0.4),
+ middle_weight,
+ ],
+ ),
+ ],
+ ),
+ ),
+ filtered_ts,
+ ],
+ )
+
+ # Normalize so weights always sum to 1.0.
+ # Handles edge cases like duplicate timestamps where multiple elements
+ # match arrayMin/arrayMax.
+ # Wrap in ifNull to handle Nullable(Float64) from HogQL casts.
+ non_nullable_weights = ast.Call(
+ name="arrayMap",
+ args=[
+ ast.Lambda(
+ args=["_pw"],
+ expr=ast.Call(name="ifNull", args=[ast.Field(chain=["_pw"]), ast.Constant(value=0.0)]),
+ ),
+ position_weights,
+ ],
+ )
+ weight_sum = ast.Call(name="arraySum", args=[non_nullable_weights])
+ normalized_weights = ast.Call(
+ name="arrayMap",
+ args=[
+ ast.Lambda(
+ args=["w"],
+ expr=ast.ArithmeticOperation(
+ left=ast.Field(chain=["w"]),
+ op=ast.ArithmeticOperationOp.Div,
+ right=ast.Call(name="greatest", args=[weight_sum, ast.Constant(value=0.000001)]),
+ ),
+ ),
+ non_nullable_weights,
+ ],
+ )
+
+ return ast.Call(
+ name="if",
+ args=[
+ # n == 0: no touchpoints in window, empty weights (ARRAY JOIN produces no rows)
+ ast.CompareOperation(
+ left=ast.Call(name="length", args=[filtered_ts]),
+ op=ast.CompareOperationOp.Eq,
+ right=ast.Constant(value=0),
+ ),
+ ast.Array(exprs=[]),
+ ast.Call(
+ name="if",
+ args=[
+ # n == 1: single touchpoint gets all credit
+ ast.CompareOperation(
+ left=ast.Call(name="length", args=[filtered_ts]),
+ op=ast.CompareOperationOp.Eq,
+ right=ast.Constant(value=1),
+ ),
+ ast.Array(exprs=[ast.Constant(value=1.0)]),
+ ast.Call(
+ name="if",
+ args=[
+ # n == 2: [0.5, 0.5]
+ ast.CompareOperation(
+ left=ast.Call(name="length", args=[filtered_ts]),
+ op=ast.CompareOperationOp.Eq,
+ right=ast.Constant(value=2),
+ ),
+ ast.Array(exprs=[ast.Constant(value=0.5), ast.Constant(value=0.5)]),
+ # n >= 3: assign by min/max timestamp, normalized
+ normalized_weights,
+ ],
+ ),
+ ],
+ ),
+ ],
+ )
+
+
+def _build_single_touch_weights(filtered_ts: ast.Expr, extreme: str) -> ast.Expr:
+ """All credit to the touchpoint at the min (first) or max (last) timestamp.
+
+ `indexOf` returns the position of the *first* match, so exactly one element gets 1.0 even when
+ several touchpoints share the extreme timestamp. That matches how the single-touch attribution path
+ resolves ties, and keeps the weights summing to exactly 1.0 without a normalization step.
+ """
+ return ast.Call(
+ name="arrayMap",
+ args=[
+ ast.Lambda(
+ args=["_j"],
+ expr=ast.Call(
+ name="if",
+ args=[
+ ast.CompareOperation(
+ left=ast.Field(chain=["_j"]),
+ op=ast.CompareOperationOp.Eq,
+ right=ast.Call(
+ name="indexOf",
+ args=[filtered_ts, ast.Call(name=extreme, args=[filtered_ts])],
+ ),
+ ),
+ ast.Constant(value=1.0),
+ ast.Constant(value=0.0),
+ ],
+ ),
+ ),
+ ast.Call(name="arrayEnumerate", args=[filtered_ts]),
+ ],
+ )
+
+
+def build_first_touch_weights(filtered_ts: ast.Expr) -> ast.Expr:
+ """All credit to the earliest touchpoint in the window."""
+ return _build_single_touch_weights(filtered_ts, "arrayMin")
+
+
+def build_last_touch_weights(filtered_ts: ast.Expr) -> ast.Expr:
+ """All credit to the latest touchpoint in the window."""
+ return _build_single_touch_weights(filtered_ts, "arrayMax")
diff --git a/products/marketing_analytics/backend/hogql_queries/conversion_goal_conditions.py b/products/marketing_analytics/backend/hogql_queries/conversion_goal_conditions.py
new file mode 100644
index 000000000000..1306c4ead77c
--- /dev/null
+++ b/products/marketing_analytics/backend/hogql_queries/conversion_goal_conditions.py
@@ -0,0 +1,83 @@
+"""What counts as a conversion for a marketing analytics goal.
+
+Both the Dashboard's `ConversionGoalProcessor` and the attribution table ask the same question of an
+event row, so the answer lives here once. A goal is its event or action **and** its configured property
+filters; splitting those apart is how one pipeline ends up counting every `purchase` while the other
+counts only the ones over $100.
+"""
+
+from typing import Optional
+
+from posthog.schema import ConversionGoalFilter1, ConversionGoalFilter2, ConversionGoalFilter3
+
+from posthog.hogql import ast
+from posthog.hogql.property import action_to_expr, property_to_expr
+
+from posthog.models import Team
+
+from products.actions.backend.models.action import Action
+
+ConversionGoal = ConversionGoalFilter1 | ConversionGoalFilter2 | ConversionGoalFilter3
+
+
+def conversion_goal_property_expr(conversion_goal: ConversionGoal, team: Team) -> Optional[ast.Expr]:
+ """The goal's own property filters, or None when it has none."""
+ if not conversion_goal.properties:
+ return None
+ return property_to_expr(conversion_goal.properties, team=team, scope="event")
+
+
+def add_conversion_goal_property_filters(
+ conditions: list[ast.Expr],
+ conversion_goal: ConversionGoal,
+ team: Team,
+) -> list[ast.Expr]:
+ """Add property filters for conversion goals"""
+ property_expr = conversion_goal_property_expr(conversion_goal, team)
+ if property_expr:
+ conditions.append(property_expr)
+
+ return conditions
+
+
+def action_match_expr(conversion_goal: ConversionGoal, team: Team) -> Optional[ast.Expr]:
+ """The goal's action as a condition, or None when its action no longer resolves for this project.
+
+ Returning None rather than deciding here, because the right answer depends on the surface: the
+ Dashboard renders many goals at once and degrades a broken one to zero, while the attribution table
+ renders one goal and can tell the user their goal is misconfigured.
+ """
+ if not isinstance(conversion_goal, ConversionGoalFilter2) or not conversion_goal.id:
+ return None
+ try:
+ action = Action.objects.get(pk=int(conversion_goal.id), team__project_id=team.project_id)
+ except (Action.DoesNotExist, TypeError, ValueError):
+ return None
+ return action_to_expr(action)
+
+
+def conversion_goal_match_expr(conversion_goal: ConversionGoal, team: Team) -> Optional[ast.Expr]:
+ """The event or action half of the goal, without its property filters.
+
+ None when the goal names nothing to match on: a bare "All Events" goal, a data warehouse goal (whose
+ conversions aren't event rows at all), or an action that no longer resolves.
+ """
+ if isinstance(conversion_goal, ConversionGoalFilter1):
+ if not conversion_goal.event:
+ return None
+ return ast.CompareOperation(
+ left=ast.Field(chain=["events", "event"]),
+ op=ast.CompareOperationOp.Eq,
+ right=ast.Constant(value=conversion_goal.event),
+ )
+ return action_match_expr(conversion_goal, team)
+
+
+def conversion_goal_condition(conversion_goal: ConversionGoal, team: Team) -> Optional[ast.Expr]:
+ """True for an event row that counts as a conversion: the event or action, narrowed by the goal's
+ property filters. None when the goal has no resolvable event condition at all."""
+ match = conversion_goal_match_expr(conversion_goal, team)
+ if match is None:
+ return None
+ properties = conversion_goal_property_expr(conversion_goal, team)
+ return ast.And(exprs=[match, properties]) if properties else match
diff --git a/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py b/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py
index d0449408904c..18ebcf9d5faa 100644
--- a/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py
+++ b/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py
@@ -1,4 +1,3 @@
-import math
import uuid
import threading
from collections.abc import Sequence
@@ -25,31 +24,33 @@ from posthog.hogql import ast
from posthog.hogql.database.schema.channel_type import ChannelTypeExprs, create_channel_type_expr
from posthog.hogql.database.schema.exchange_rate import convert_currency_call
from posthog.hogql.modifiers import create_default_modifiers_for_team
-from posthog.hogql.property import action_to_expr, property_to_expr
from posthog.hogql.timings import HogQLTimings
from posthog.models import PropertyDefinition, Team, User
from products.access_control.backend.property_access_control import get_restricted_property_names
-from products.actions.backend.models.action import Action
from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (
LazyComputationResult,
LazyComputationTable,
)
from .adapters.factory import MarketingSourceFactory
+from .attribution_weights import (
+ DAY_IN_SECONDS,
+ build_linear_weights,
+ build_position_based_weights,
+ build_time_decay_weights,
+)
+from .conversion_goal_conditions import (
+ action_match_expr,
+ add_conversion_goal_property_filters,
+ conversion_goal_match_expr,
+)
from .marketing_analytics_config import MarketingAnalyticsConfig
from .marketing_lazy_precompute import marketing_ensure_precomputed
from .metrics import CONVERSION_GOAL_PRECOMPUTE_FALLBACK_COUNTER
from .utils import build_source_normalization_expr
-DAY_IN_SECONDS = 86400
-LN2 = math.log(2) # ≈ 0.693, used in half-life formula: weight = exp(-ln(2) * t / half_life)
-# Half-life = attribution_window / 4, so a 90-day window gives ~22.5-day half-life.
-# At t = half_life, weight = exp(-ln(2)) = 0.5 (exactly half).
-# This follows the industry standard (Google Analytics, Adobe, Mixpanel all use 7-day half-life).
-TIME_DECAY_HALF_LIFE_DIVISOR = 4
-
# Freshness windows for the precompute read path. The Dagster warmer
# (products/marketing_analytics/dags/marketing_precompute.py) MUST drive ensure_precomputed with this
# exact schedule — otherwise the read path's freshness check would treat warmed rows as stale and
@@ -355,25 +356,12 @@ class ConversionGoalProcessor:
def get_base_where_conditions(self) -> list[ast.Expr]:
"""Build base WHERE conditions for conversion goal filtering"""
- conditions: list[ast.Expr] = []
-
- if self.goal.kind == "EventsNode":
- event_name = self.goal.event
- if event_name:
- conditions.append(
- ast.CompareOperation(
- left=ast.Field(chain=["events", "event"]),
- op=ast.CompareOperationOp.Eq,
- right=ast.Constant(value=event_name),
- )
- )
- elif self.goal.kind == "ActionsNode":
- action_id = self.goal.id
- if action_id:
- action = Action.objects.get(pk=int(action_id), team__project_id=self.team.project_id)
- conditions.append(action_to_expr(action))
+ if self.goal.kind == "ActionsNode":
+ # A goal whose action is gone matches nothing, so the Dashboard's other goals still render.
+ return [action_match_expr(self.goal, self.team) or ast.Constant(value=False)]
- return conditions
+ match = conversion_goal_match_expr(self.goal, self.team)
+ return [match] if match is not None else []
def get_date_field(self) -> str:
"""Get appropriate timestamp field based on goal type"""
@@ -1253,13 +1241,8 @@ class ConversionGoalProcessor:
# For ActionsNode (when conversion_event is None), we need to use the action condition
# instead of matching all events
if self.goal.kind == "ActionsNode":
- action_id = self.goal.id
- if action_id:
- try:
- action = Action.objects.get(pk=int(action_id), team__project_id=self.team.project_id)
- return action_to_expr(action)
- except Action.DoesNotExist:
- return ast.Constant(value=False)
+ # A goal whose action is gone matches nothing, so the Dashboard's other goals still render.
+ return action_match_expr(self.goal, self.team) or ast.Constant(value=False)
# Fallback for other cases
return ast.Constant(value=True)
@@ -1538,229 +1521,18 @@ class ConversionGoalProcessor:
filtered_ts = ast.Field(chain=[filtered_timestamps_alias])
if self.config.attribution_mode == AttributionMode.LINEAR:
- return self._build_linear_weights(filtered_ts)
+ return build_linear_weights(filtered_ts)
elif self.config.attribution_mode == AttributionMode.TIME_DECAY:
- return self._build_time_decay_weights(filtered_ts, attribution_window_seconds)
+ conversion_time = ast.ArrayAccess(
+ array=ast.Field(chain=["conversion_timestamps"]),
+ property=ast.Field(chain=["i"]),
+ )
+ return build_time_decay_weights(filtered_ts, conversion_time, attribution_window_seconds)
elif self.config.attribution_mode == AttributionMode.POSITION_BASED:
- return self._build_position_based_weights(filtered_ts)
+ return build_position_based_weights(filtered_ts)
raise ValueError(f"Unknown multi-touch attribution mode: {self.config.attribution_mode}")
- def _build_linear_weights(self, filtered_ts: ast.Expr) -> ast.Expr:
- """Equal weight for all touchpoints: 1.0 / n."""
- n = ast.Call(name="toFloat", args=[ast.Call(name="length", args=[filtered_ts])])
- return ast.Call(
- name="arrayMap",
- args=[
- ast.Lambda(
- args=["_x"],
- expr=ast.ArithmeticOperation(
- left=ast.Constant(value=1.0),
- op=ast.ArithmeticOperationOp.Div,
- right=ast.Call(name="greatest", args=[n, ast.Constant(value=1.0)]),
- ),
- ),
- filtered_ts,
- ],
- )
-
- def _build_time_decay_weights(self, filtered_ts: ast.Expr, attribution_window_seconds: int) -> ast.Expr:
- """Exponential half-life decay: weight = exp(-ln(2) * delta / half_life).
-
- At t = half_life, weight = 0.5 (exactly half). This matches the industry
- standard used by Google Analytics, Adobe Analytics, and Mixpanel.
- The half-life scales with the attribution window (window / 4).
- Weights are normalized so they sum to 1.
- """
- half_life_seconds = max(attribution_window_seconds // TIME_DECAY_HALF_LIFE_DIVISOR, DAY_IN_SECONDS)
- conversion_time = ast.ArrayAccess(
- array=ast.Field(chain=["conversion_timestamps"]),
- property=ast.Field(chain=["i"]),
- )
- # weight = exp(-ln(2) * (conversion_time - ts) / half_life)
- raw_weights = ast.Call(
- name="arrayMap",
- args=[
- ast.Lambda(
- args=["ts"],
- expr=ast.Call(
- name="exp",
- args=[
- ast.ArithmeticOperation(
- left=ast.Constant(value=-LN2),
- op=ast.ArithmeticOperationOp.Mult,
- right=ast.ArithmeticOperation(
- left=ast.ArithmeticOperation(
- left=conversion_time,
- op=ast.ArithmeticOperationOp.Sub,
- right=ast.Field(chain=["ts"]),
- ),
- op=ast.ArithmeticOperationOp.Div,
- right=ast.Constant(value=half_life_seconds),
- ),
- ),
- ],
- ),
- ),
- filtered_ts,
- ],
- )
- # Normalize: divide each weight by sum of all weights.
- # Note: raw_weights AST node is referenced twice (in arraySum and as the
- # arrayMap input), so ClickHouse evaluates the exp() computation twice per row.
- # This is acceptable because touchpoint arrays are small (typically 3-10 elements).
- weight_sum = ast.Call(name="arraySum", args=[raw_weights])
- return ast.Call(
- name="arrayMap",
- args=[
- ast.Lambda(
- args=["w"],
- expr=ast.ArithmeticOperation(
- left=ast.Field(chain=["w"]),
- op=ast.ArithmeticOperationOp.Div,
- right=ast.Call(name="greatest", args=[weight_sum, ast.Constant(value=0.000001)]),
- ),
- ),
- raw_weights,
- ],
- )
-
- def _build_position_based_weights(self, filtered_ts: ast.Expr) -> ast.Expr:
- """40% first touch, 40% last touch, 20% distributed among middle touchpoints.
-
- Uses arrayMin/arrayMax to identify first/last by timestamp value,
- avoiding dependency on array ordering (groupArray doesn't guarantee order).
-
- Edge cases:
- - 0 touchpoints: empty array (ARRAY JOIN produces no rows)
- - 1 touchpoint: [1.0]
- - 2 touchpoints: [0.5, 0.5]
- - Duplicate timestamps: if multiple touchpoints share min/max timestamp,
- all get 0.4 weight before normalization. Normalization rescues the total
- to 1.0, but credit distribution may deviate from the intended 40/20/40.
- """
- n = ast.Call(name="toFloat", args=[ast.Call(name="length", args=[filtered_ts])])
- middle_weight = ast.ArithmeticOperation(
- left=ast.Constant(value=0.2),
- op=ast.ArithmeticOperationOp.Div,
- right=ast.Call(
- name="greatest",
- args=[
- ast.ArithmeticOperation(
- left=n,
- op=ast.ArithmeticOperationOp.Sub,
- right=ast.Constant(value=2.0),
- ),
- ast.Constant(value=1.0),
- ],
- ),
- )
-
- min_ts = ast.Call(name="arrayMin", args=[filtered_ts])
- max_ts = ast.Call(name="arrayMax", args=[filtered_ts])
-
- position_weights = ast.Call(
- name="arrayMap",
- args=[
- ast.Lambda(
- args=["ts"],
- expr=ast.Call(
- name="if",
- args=[
- ast.CompareOperation(
- left=ast.Field(chain=["ts"]),
- op=ast.CompareOperationOp.Eq,
- right=min_ts,
- ),
- ast.Constant(value=0.4),
- ast.Call(
- name="if",
- args=[
- ast.CompareOperation(
- left=ast.Field(chain=["ts"]),
- op=ast.CompareOperationOp.Eq,
- right=max_ts,
- ),
- ast.Constant(value=0.4),
- middle_weight,
- ],
- ),
- ],
- ),
- ),
- filtered_ts,
- ],
- )
-
- # Normalize so weights always sum to 1.0.
- # Handles edge cases like duplicate timestamps where multiple elements
- # match arrayMin/arrayMax.
- # Wrap in ifNull to handle Nullable(Float64) from HogQL casts.
- non_nullable_weights = ast.Call(
- name="arrayMap",
- args=[
- ast.Lambda(
- args=["_pw"],
- expr=ast.Call(name="ifNull", args=[ast.Field(chain=["_pw"]), ast.Constant(value=0.0)]),
- ),
- position_weights,
- ],
- )
- weight_sum = ast.Call(name="arraySum", args=[non_nullable_weights])
- normalized_weights = ast.Call(
- name="arrayMap",
- args=[
- ast.Lambda(
- args=["w"],
- expr=ast.ArithmeticOperation(
- left=ast.Field(chain=["w"]),
- op=ast.ArithmeticOperationOp.Div,
- right=ast.Call(name="greatest", args=[weight_sum, ast.Constant(value=0.000001)]),
- ),
- ),
- non_nullable_weights,
- ],
- )
-
- return ast.Call(
- name="if",
- args=[
- # n == 0: no touchpoints in window, empty weights (ARRAY JOIN produces no rows)
- ast.CompareOperation(
- left=ast.Call(name="length", args=[filtered_ts]),
- op=ast.CompareOperationOp.Eq,
- right=ast.Constant(value=0),
- ),
- ast.Array(exprs=[]),
- ast.Call(
- name="if",
- args=[
- # n == 1: single touchpoint gets all credit
- ast.CompareOperation(
- left=ast.Call(name="length", args=[filtered_ts]),
- op=ast.CompareOperationOp.Eq,
- right=ast.Constant(value=1),
- ),
- ast.Array(exprs=[ast.Constant(value=1.0)]),
- ast.Call(
- name="if",
- args=[
- # n == 2: [0.5, 0.5]
- ast.CompareOperation(
- left=ast.Call(name="length", args=[filtered_ts]),
- op=ast.CompareOperationOp.Eq,
- right=ast.Constant(value=2),
- ),
- ast.Array(exprs=[ast.Constant(value=0.5), ast.Constant(value=0.5)]),
- # n >= 3: assign by min/max timestamp, normalized
- normalized_weights,
- ],
- ),
- ],
- ),
- ],
- )
-
def _build_multi_touch_array_join_subquery(
self, inner_query: ast.SelectQuery, attribution_window_seconds: int
) -> ast.SelectQuery:
@@ -2453,18 +2225,3 @@ class ConversionGoalProcessor:
return event_value == conversion_event or event_value == "$pageview"
return False
-
-
-def add_conversion_goal_property_filters(
- conditions: list[ast.Expr],
- conversion_goal: ConversionGoalFilter1 | ConversionGoalFilter2 | ConversionGoalFilter3,
- team: Team,
-) -> list[ast.Expr]:
- """Add property filters for conversion goals"""
- conversion_goal_properties = conversion_goal.properties
- if conversion_goal_properties:
- property_expr = property_to_expr(conversion_goal_properties, team=team, scope="event")
- if property_expr:
- conditions.append(property_expr)
-
- return conditions
diff --git a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_aggregated_query_runner.py b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_aggregated_query_runner.py
index ac7d2f126a19..418cf9189758 100644
--- a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_aggregated_query_runner.py
+++ b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_aggregated_query_runner.py
@@ -179,7 +179,7 @@ class MarketingAnalyticsAggregatedQueryRunner(
hogql=response.hogql,
timings=response.timings,
modifiers=self.modifiers,
- error="; ".join(self._conversion_goal_warnings) if self._conversion_goal_warnings else None,
+ error=self._conversion_goal_error,
)
def calculate_without_compare(self) -> ast.SelectQuery:
diff --git a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py
index 479c34f8b0ae..28e0da18a010 100644
--- a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py
+++ b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py
@@ -1,5 +1,6 @@
import time
from abc import ABC, abstractmethod
+from dataclasses import dataclass
from datetime import datetime
from functools import cached_property
from typing import Generic, Optional, TypeVar
@@ -55,6 +56,19 @@ from .conversion_goals_aggregator import ConversionGoalsAggregator
from .marketing_analytics_config import MarketingAnalyticsConfig
from .utils import build_source_normalization_expr, convert_team_conversion_goals_to_objects
+
+@dataclass(frozen=True)
+class SkippedConversionGoal:
+ """A goal that can't be queried, and why.
+
+ Carries the id because goal names are not unique - the duplicate-name skip below exists precisely
+ because they collide - so a caller looking up why *its* goal was dropped can't match on the name.
+ """
+
+ conversion_goal_id: str
+ message: str
+
+
logger = structlog.get_logger(__name__)
ResponseType = TypeVar("ResponseType", bound=AnalyticsQueryResponseProtocol)
@@ -107,7 +121,7 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,
# settings and the precompute feature flags. Subclasses previously each set this; the aggregated
# runner didn't, so it silently used defaults (cost precompute always off).
self.config = MarketingAnalyticsConfig.from_team(self.team)
- self._conversion_goal_warnings: list[str] = []
+ self._skipped_conversion_goals: list[SkippedConversionGoal] = []
self._valid_conversion_goals_count: Optional[int] = None
# Cost-precompute observability — surfaced in the query telemetry event so we can confirm,
# per query, whether the native cost table was used or we fell back to the live S3 union.
@@ -217,8 +231,18 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,
@cached_property
def _shared_hogql_context(self) -> HogQLContext:
"""HogQLContext carrying the prebuilt database, passed to execute_hogql_query so its
- `_generate_hogql` reuses the database instead of building a second one."""
- return HogQLContext(team_id=self.team.pk, database=self._shared_hogql_database)
+ `_generate_hogql` reuses the database instead of building a second one.
+
+ Carries the runner's team and user because supplying a context stops `execute_hogql_query` from
+ building a user-aware one, and the printer loads property-level access control off the context:
+ without the user it would see only the team's default restrictions, so a property denied to this
+ user specifically would print unmasked. That masking is what `ConversionGoalProcessor` skips the
+ precompute path to fall back onto, so it has to actually be in force here."""
+ return HogQLContext(
+ team=self.team,
+ database=self._shared_hogql_database,
+ user=self.user,
+ )
def _factory(self, date_range: QueryDateRange):
"""Create factory instance for the given date range"""
@@ -674,18 +698,30 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,
return conversion_goals
+ @property
+ def _conversion_goal_error(self) -> Optional[str]:
+ """The skipped goals as one message for the response's `error` field."""
+ if not self._skipped_conversion_goals:
+ return None
+ return "; ".join(skipped.message for skipped in self._skipped_conversion_goals)
+
def _filter_invalid_conversion_goals(
self, conversion_goals: list[ConversionGoalFilter1 | ConversionGoalFilter2 | ConversionGoalFilter3]
- ) -> tuple[list[ConversionGoalFilter1 | ConversionGoalFilter2 | ConversionGoalFilter3], list[str]]:
+ ) -> tuple[
+ list[ConversionGoalFilter1 | ConversionGoalFilter2 | ConversionGoalFilter3], list[SkippedConversionGoal]
+ ]:
"""
Filter out invalid conversion goals (e.g., those using "All Events" or
referencing missing Data Warehouse columns).
- Returns (valid_goals, warnings).
+ Returns (valid_goals, skipped).
"""
valid_goals: list[ConversionGoalFilter1 | ConversionGoalFilter2 | ConversionGoalFilter3] = []
- warnings: list[str] = []
+ skipped: list[SkippedConversionGoal] = []
seen_names: set[str] = set()
+ def skip(message: str) -> None:
+ skipped.append(SkippedConversionGoal(conversion_goal_id=goal.conversion_goal_id, message=message))
+
for goal in conversion_goals:
goal_name = getattr(goal, "conversion_goal_name", "Unknown")
@@ -697,7 +733,7 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,
"filtering_out_all_events_conversion_goal",
goal_name=goal_name,
)
- warnings.append(f"Conversion goal '{goal_name}' skipped: 'All Events' cannot be used")
+ skip(f"Conversion goal '{goal_name}' skipped: 'All Events' cannot be used")
continue
# Validate DataWarehouseNode column existence
@@ -709,7 +745,7 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,
goal_name=goal_name,
table_name=goal.table_name,
)
- warnings.append(f"Conversion goal '{goal_name}' skipped: table '{goal.table_name}' not found")
+ skip(f"Conversion goal '{goal_name}' skipped: table '{goal.table_name}' not found")
continue
schema_map = goal.schema_map or {}
@@ -730,7 +766,7 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,
table_name=goal.table_name,
missing_columns=missing_cols,
)
- warnings.append(
+ skip(
f"Conversion goal '{goal_name}' skipped: columns {missing_cols} not found on table '{goal.table_name}'"
)
continue
@@ -742,13 +778,13 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,
"filtering_out_duplicate_named_conversion_goal",
goal_name=goal_name,
)
- warnings.append(f"Conversion goal '{goal_name}' skipped: duplicate name")
+ skip(f"Conversion goal '{goal_name}' skipped: duplicate name")
continue
seen_names.add(goal_name)
valid_goals.append(goal)
- return valid_goals, warnings
+ return valid_goals, skipped
def _get_filtered_select_columns(self, query: ast.SelectQuery) -> list[ast.Expr]:
"""Filter a query's SELECT to the columns requested in self.query.select, in order."""
@@ -1088,7 +1124,7 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,
with self.timings.measure("ma_get_conversion_goals"):
conversion_goals = self._get_team_conversion_goals()
with self.timings.measure("ma_filter_conversion_goals"):
- valid_conversion_goals, self._conversion_goal_warnings = self._filter_invalid_conversion_goals(
+ valid_conversion_goals, self._skipped_conversion_goals = self._filter_invalid_conversion_goals(
conversion_goals
)
self._valid_conversion_goals_count = len(valid_conversion_goals)
diff --git a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_table_query_runner.py b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_table_query_runner.py
index 39588185461b..8f8cd07a0f98 100644
--- a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_table_query_runner.py
+++ b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_table_query_runner.py
@@ -119,7 +119,7 @@ class MarketingAnalyticsTableQueryRunner(MarketingAnalyticsBaseQueryRunner[Marke
hasMore=has_more,
limit=requested_limit,
offset=self.query.offset or 0,
- error="; ".join(self._conversion_goal_warnings) if self._conversion_goal_warnings else None,
+ error=self._conversion_goal_error,
)
def _get_column_names_for_order_by(self, select_columns: list[ast.Expr]) -> list[str]:
diff --git a/products/marketing_analytics/backend/hogql_queries/non_integrated_conversions_table_query_runner.py b/products/marketing_analytics/backend/hogql_queries/non_integrated_conversions_table_query_runner.py
index 7335a4ab8640..b0e3f7c9bd4f 100644
--- a/products/marketing_analytics/backend/hogql_queries/non_integrated_conversions_table_query_runner.py
+++ b/products/marketing_analytics/backend/hogql_queries/non_integrated_conversions_table_query_runner.py
@@ -116,7 +116,7 @@ class NonIntegratedConversionsTableQueryRunner(
hasMore=has_more,
limit=requested_limit,
offset=self.query.offset or 0,
- error="; ".join(self._conversion_goal_warnings) if self._conversion_goal_warnings else None,
+ error=self._conversion_goal_error,
)
def _get_filtered_select_columns(self, query: ast.SelectQuery) -> list[ast.Expr]:
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
new file mode 100644
index 000000000000..3f99b7be92f1
--- /dev/null
+++ b/products/marketing_analytics/backend/hogql_queries/test_attribution_table_query_runner.py
@@ -0,0 +1,750 @@
+from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
+from unittest.mock import patch
+
+from parameterized import parameterized
+
+from posthog.schema import (
+ AttributionMode,
+ BaseMathType,
+ ConversionGoalFilter1,
+ ConversionGoalFilter2,
+ DateRange,
+ EventPropertyFilter,
+ MarketingAnalyticsAttributionBreakdown,
+ MarketingAnalyticsAttributionQuery,
+ PropertyMathType,
+ PropertyOperator,
+)
+
+from posthog.hogql import ast
+from posthog.hogql.printer import prepare_and_print_ast
+from posthog.hogql.visitor import TraversingVisitor
+
+from posthog.models import PropertyDefinition
+from posthog.models.team.team_marketing_analytics_config import MAX_ATTRIBUTION_WINDOW_DAYS
+from posthog.models.utils import uuid7
+from posthog.test.persons import create_person
+
+from products.actions.backend.models.action import Action
+from products.marketing_analytics.backend.hogql_queries.attribution_table_query_runner import (
+ MarketingAnalyticsAttributionQueryRunner,
+)
+
+GOAL_ID = "goal-1"
+CONVERSION_EVENT = "purchase"
+
+# A 4-day window makes the half-life exactly 1 day (window // 4), so touchpoints one, two and three
+# days before the conversion decay to 0.5, 0.25 and 0.125 — a geometric series whose normalized
+# weights are the clean 4/7, 2/7, 1/7 asserted below.
+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 TestMarketingAnalyticsAttributionQueryRunner(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",
+ pageviews: int = 1,
+ ) -> None:
+ """One session's worth of pageviews. uuid7 seeds the session id so `$start_timestamp` lands on
+ `started_at`, which is what the attribution window filters against. `$referring_domain` defaults
+ to the `$direct` sentinel the SDKs send when there's no referrer — without it `$channel_type`
+ classifies as Unknown rather than Direct."""
+ session_id = str(uuid7(started_at))
+ for _ in range(pageviews):
+ _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,
+ *,
+ exclude_direct: 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,
+ ):
+ flush_persons_and_events()
+ query = MarketingAnalyticsAttributionQuery(
+ dateRange=DateRange(date_from=date_from, date_to=date_to),
+ breakdownBy=breakdown,
+ conversionGoalId=GOAL_ID,
+ excludeDirectTraffic=exclude_direct,
+ lookbackWindowDays=lookback_days,
+ allowMultipleConversionsPerVisitor=allow_multiple_conversions,
+ properties=[],
+ )
+ return MarketingAnalyticsAttributionQueryRunner(query=query, team=self.team).calculate()
+
+ @staticmethod
+ def _by_breakdown(response) -> dict[str, dict[AttributionMode, float]]:
+ """{breakdown value: {model: conversions}} — the shape every weight assertion needs."""
+ return {row.breakdownValue: {cell.model: cell.conversions for cell in row.models} for row in response.results}
+
+ def test_visitors_include_lookback_arrivals_that_can_earn_credit(self):
+ # Credit looks back attribution_window_days before the date range, so reach must too: a visitor
+ # whose only touch predates the range used to be missing from the denominator, which reported
+ # conversion rates above 100%.
+ create_person(team=self.team, distinct_ids=["p1"])
+ self._session("p1", "2022-12-30T12:00:00Z", utm_campaign="holiday")
+ self._conversion("p1", "2023-01-02T12:00:00Z")
+
+ response = self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN)
+
+ row = next(r for r in response.results if r.breakdownValue == "holiday")
+ self.assertEqual(row.visitors, 1)
+ self.assertEqual(row.influencedConversions, 1)
+ self.assertEqual(row.models[0].conversionRate, 1.0)
+
+ def test_unique_users_math_counts_each_person_once(self):
+ # A dau goal on a frequent event ($pageview being the common case) must not count every matching
+ # event as its own conversion: that reported more conversions than visitors. The person's three
+ # conversion events collapse to their first, so each model splits exactly 1 conversion.
+ self._configure_goal(counts_as_revenue=False, math=BaseMathType.DAU, math_property=None)
+ create_person(team=self.team, distinct_ids=["p1"])
+ self._session("p1", THREE_DAYS_BEFORE, utm_campaign="early")
+ self._session("p1", ONE_DAY_BEFORE, utm_campaign="late")
+ self._conversion("p1", CONVERSION_AT)
+ self._conversion("p1", "2023-01-10T13:00:00Z")
+ self._conversion("p1", "2023-01-11T12:00:00Z")
+
+ response = self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN)
+
+ self.assertEqual(response.totalConversions, 1)
+ for row in response.results:
+ self.assertEqual(row.influencedConversions, 1)
+ by_campaign = self._by_breakdown(response)
+ self.assertAlmostEqual(by_campaign["early"][AttributionMode.FIRST_TOUCH], 1.0, places=4)
+ self.assertAlmostEqual(by_campaign["late"][AttributionMode.LAST_TOUCH], 1.0, places=4)
+
+ @parameterized.expand(
+ [
+ # (goal math, toggle, expected conversions credited)
+ ("count_default_counts_every_conversion", PropertyMathType.SUM, None, 3.0),
+ ("count_toggled_off_counts_one", PropertyMathType.SUM, False, 1.0),
+ ("unique_users_default_counts_one", BaseMathType.DAU, None, 1.0),
+ ("unique_users_toggled_on_counts_every_conversion", BaseMathType.DAU, True, 3.0),
+ ]
+ )
+ def test_multiple_conversions_toggle_overrides_goal_math(
+ self, _name: str, math: PropertyMathType | BaseMathType, allow_multiple: bool | None, expected: float
+ ):
+ # Unset must follow the goal's math, and an explicit value must win over it in both directions.
+ # Getting this backwards is invisible on a count goal (which already counts everything) and would
+ # only show up on unique-users goals, where it would contradict the number the Dashboard reports.
+ is_revenue = math == PropertyMathType.SUM
+ self._configure_goal(counts_as_revenue=is_revenue, math=math, math_property="revenue" if is_revenue else None)
+ create_person(team=self.team, distinct_ids=["p1"])
+ self._session("p1", ONE_DAY_BEFORE, utm_campaign="c")
+ for at in (CONVERSION_AT, "2023-01-10T13:00:00Z", "2023-01-10T14:00:00Z"):
+ self._conversion("p1", at)
+
+ response = self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN, allow_multiple_conversions=allow_multiple)
+
+ self.assertEqual(response.allowsMultipleConversionsPerVisitor, expected > 1.0)
+ self.assertAlmostEqual(self._by_breakdown(response)["c"][AttributionMode.LAST_TOUCH], expected, places=4)
+ self.assertEqual(response.results[0].influencedConversions, int(expected))
+
+ def test_sessions_missing_from_the_sessions_table_are_not_touchpoints(self):
+ # A session id that resolves to no session row comes back as epoch zero, not null, because the join
+ # fills a non-nullable column with its default. Testing for null instead of for a real timestamp let
+ # 1970 touchpoints into the array, where they sorted to the front, consumed truncation slots, and
+ # earned nothing — so conversions whose own session was one of these silently went uncredited.
+ create_person(team=self.team, distinct_ids=["p1"])
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id="p1",
+ timestamp=ONE_DAY_BEFORE,
+ properties={
+ "$session_id": "00000000-0000-0000-0000-000000000000",
+ "$pathname": "/",
+ "$referring_domain": "$direct",
+ "utm_campaign": "unresolvable",
+ },
+ )
+ self._session("p1", ONE_DAY_BEFORE, utm_campaign="real")
+ self._conversion("p1", CONVERSION_AT)
+
+ by_campaign = self._by_breakdown(self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN))
+
+ self.assertNotIn("unresolvable", by_campaign)
+ self.assertAlmostEqual(by_campaign["real"][AttributionMode.LINEAR], 1.0, places=4)
+
+ def test_conversions_before_the_date_range_are_not_credited(self):
+ # Touchpoint collection reaches a lookback window further back than the date range, and the
+ # conversion side used to ride on that same widened scan: conversions from the older stretch were
+ # credited and counted, so the table silently reported a much longer period than the one asked for.
+ create_person(team=self.team, distinct_ids=["p1"])
+ self._session("p1", "2022-12-20T12:00:00Z", utm_campaign="c")
+ self._conversion("p1", "2022-12-21T12:00:00Z", revenue=500.0) # before date_from
+ self._session("p1", ONE_DAY_BEFORE, utm_campaign="c")
+ self._conversion("p1", CONVERSION_AT, revenue=100.0) # inside the range
+
+ response = self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN, date_from="2023-01-01")
+
+ self.assertEqual(response.totalConversions, 1)
+ row = response.results[0]
+ self.assertEqual(row.influencedConversions, 1)
+ self.assertAlmostEqual(row.influencedValue or 0.0, 100.0, places=2)
+
+ def test_conversions_in_the_same_second_stay_separate(self):
+ # Conversions were keyed by (dimension, person, timestamp) with the timestamp truncated to whole
+ # seconds, so a retry or a batched server-side send merged two conversions into one: the influenced
+ # count under-reported and one conversion's revenue silently vanished, while the model columns
+ # still counted both. The row contradicted itself.
+ create_person(team=self.team, distinct_ids=["p1"])
+ self._session("p1", ONE_DAY_BEFORE, utm_campaign="c")
+ self._conversion("p1", CONVERSION_AT, revenue=100.0)
+ self._conversion("p1", CONVERSION_AT, revenue=100.0)
+
+ row = self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN).results[0]
+
+ self.assertEqual(row.influencedConversions, 2)
+ self.assertAlmostEqual(row.influencedValue or 0.0, 200.0, places=2)
+ last_touch = next(c for c in row.models if c.model == AttributionMode.LAST_TOUCH)
+ self.assertAlmostEqual(last_touch.conversions, 2.0, places=4)
+ self.assertAlmostEqual(last_touch.conversionValue or 0.0, 200.0, places=2)
+
+ def test_every_model_splits_one_conversion_its_own_way(self):
+ # The one test that catches this design's central risk: five weight arrays are built per
+ # conversion and exploded through a single shared ARRAY JOIN, so indexing the wrong array into a
+ # model's column, or an off-by-one in `arrayEnumerate(ts)`, silently reports another model's
+ # numbers. Also pins time decay's normalization and position-based's 40/20/40.
+ create_person(team=self.team, distinct_ids=["p1"])
+ self._session("p1", THREE_DAYS_BEFORE, utm_campaign="early")
+ self._session("p1", TWO_DAYS_BEFORE, utm_campaign="middle")
+ self._session("p1", ONE_DAY_BEFORE, utm_campaign="late")
+ self._conversion("p1", CONVERSION_AT, revenue=100.0)
+
+ response = self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN)
+ by_campaign = self._by_breakdown(response)
+
+ self.assertEqual(set(by_campaign), {"early", "middle", "late"})
+
+ self.assertAlmostEqual(by_campaign["early"][AttributionMode.FIRST_TOUCH], 1.0, places=4)
+ self.assertAlmostEqual(by_campaign["middle"][AttributionMode.FIRST_TOUCH], 0.0, places=4)
+ self.assertAlmostEqual(by_campaign["late"][AttributionMode.FIRST_TOUCH], 0.0, places=4)
+
+ self.assertAlmostEqual(by_campaign["early"][AttributionMode.LAST_TOUCH], 0.0, places=4)
+ self.assertAlmostEqual(by_campaign["late"][AttributionMode.LAST_TOUCH], 1.0, places=4)
+
+ for campaign in ("early", "middle", "late"):
+ self.assertAlmostEqual(by_campaign[campaign][AttributionMode.LINEAR], 1 / 3, places=4)
+
+ # exp(-ln2 * days) normalized over 0.5 + 0.25 + 0.125
+ self.assertAlmostEqual(by_campaign["late"][AttributionMode.TIME_DECAY], 4 / 7, places=4)
+ self.assertAlmostEqual(by_campaign["middle"][AttributionMode.TIME_DECAY], 2 / 7, places=4)
+ self.assertAlmostEqual(by_campaign["early"][AttributionMode.TIME_DECAY], 1 / 7, places=4)
+
+ self.assertAlmostEqual(by_campaign["early"][AttributionMode.POSITION_BASED], 0.4, places=4)
+ self.assertAlmostEqual(by_campaign["middle"][AttributionMode.POSITION_BASED], 0.2, places=4)
+ self.assertAlmostEqual(by_campaign["late"][AttributionMode.POSITION_BASED], 0.4, places=4)
+
+ def test_every_model_conserves_total_credit(self):
+ # Weights must sum to 1 per conversion, so each model's column sums to the conversion count no
+ # matter how many touchpoints there were. A normalization bug (or a dropped touchpoint) shows up
+ # here as a column that quietly totals less than the truth.
+ create_person(team=self.team, distinct_ids=["p1"])
+ self._session("p1", THREE_DAYS_BEFORE, utm_campaign="a")
+ self._session("p1", TWO_DAYS_BEFORE, utm_campaign="b")
+ self._session("p1", ONE_DAY_BEFORE, utm_campaign="c")
+ self._conversion("p1", CONVERSION_AT)
+
+ response = self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN)
+
+ for model in response.models:
+ total = sum(cell.conversions for row in response.results for cell in row.models if cell.model == model)
+ self.assertAlmostEqual(total, 1.0, places=4, msg=f"{model} did not conserve credit")
+
+ def test_influenced_counts_each_conversion_once_and_overlaps_across_rows(self):
+ # Guards the per-(dimension, person, conversion) collapse. Without it "influenced" would count
+ # touchpoint rows instead of conversions. The deliberate over-count across rows is asserted too,
+ # so a later "fix" that dedupes it away fails here rather than silently changing the meaning.
+ create_person(team=self.team, distinct_ids=["p1"])
+ for conversion_at, first_touch, second_touch in [
+ (CONVERSION_AT, THREE_DAYS_BEFORE, TWO_DAYS_BEFORE),
+ ("2023-01-11T12:00:00Z", "2023-01-08T18:00:00Z", "2023-01-09T18:00:00Z"),
+ ]:
+ self._session("p1", first_touch, utm_campaign="a")
+ self._session("p1", second_touch, utm_campaign="b")
+ self._conversion("p1", conversion_at)
+
+ response = self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN)
+ influenced = {row.breakdownValue: row.influencedConversions for row in response.results}
+
+ self.assertEqual(influenced["a"], 2)
+ self.assertEqual(influenced["b"], 2)
+ # Both campaigns influenced both conversions, so the column intentionally exceeds the real total.
+ self.assertEqual(sum(influenced.values()), 4)
+ self.assertEqual(response.totalConversions, 2)
+
+ def test_direct_traffic_earns_credit(self):
+ # The Dashboard's touchpoint filter requires utm_campaign AND utm_source, which drops Direct,
+ # Organic search and Referral entirely. This runner defines a touchpoint as a session instead,
+ # and this test fails the moment someone "reuses" that filter here.
+ create_person(team=self.team, distinct_ids=["p1"])
+ self._session("p1", ONE_DAY_BEFORE) # no utm, no referrer -> Direct
+ self._conversion("p1", CONVERSION_AT)
+
+ response = self._run(MarketingAnalyticsAttributionBreakdown.CHANNEL)
+ by_channel = self._by_breakdown(response)
+
+ self.assertIn("Direct", by_channel)
+ self.assertAlmostEqual(by_channel["Direct"][AttributionMode.LAST_TOUCH], 1.0, places=4)
+
+ def test_excluding_direct_redistributes_its_credit_instead_of_losing_it(self):
+ # The exclusion has to happen before the weights are computed. Applied afterwards, direct's share
+ # would simply vanish and the remaining columns would stop summing to the conversion count.
+ 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._by_breakdown(self._run(MarketingAnalyticsAttributionBreakdown.CHANNEL))
+ self.assertIn("Direct", with_direct)
+ paid_channel = next(channel for channel in with_direct if channel != "Direct")
+ self.assertAlmostEqual(with_direct[paid_channel][AttributionMode.LINEAR], 0.5, places=4)
+
+ without_direct = self._by_breakdown(
+ self._run(MarketingAnalyticsAttributionBreakdown.CHANNEL, exclude_direct=True)
+ )
+ self.assertNotIn("Direct", without_direct)
+ self.assertAlmostEqual(without_direct[paid_channel][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
+ # count — a change from sum() to any() there would pass every other test in this file.
+ create_person(team=self.team, distinct_ids=["p1"])
+ self._session("p1", THREE_DAYS_BEFORE, utm_campaign="repeat")
+ self._session("p1", TWO_DAYS_BEFORE, utm_campaign="repeat")
+ self._session("p1", ONE_DAY_BEFORE, utm_campaign="repeat")
+ self._session("p1", "2023-01-09T18:00:00Z", utm_campaign="once")
+ self._conversion("p1", CONVERSION_AT)
+
+ by_campaign = self._by_breakdown(self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN))
+
+ self.assertAlmostEqual(by_campaign["repeat"][AttributionMode.LINEAR], 0.75, places=4)
+ self.assertAlmostEqual(by_campaign["once"][AttributionMode.LINEAR], 0.25, places=4)
+
+ def test_repeated_pageviews_in_one_session_count_as_a_single_touchpoint(self):
+ # Touchpoint grain is the session, not the pageview. If it regressed to per-pageview, a visitor
+ # who browses several pages with the query string still attached would inflate that campaign's
+ # share — here 'browsed' would take 3/4 of the linear credit instead of half.
+ create_person(team=self.team, distinct_ids=["p1"])
+ self._session("p1", TWO_DAYS_BEFORE, utm_campaign="browsed", pageviews=3)
+ self._session("p1", ONE_DAY_BEFORE, utm_campaign="bounced", pageviews=1)
+ self._conversion("p1", CONVERSION_AT)
+
+ by_campaign = self._by_breakdown(self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN))
+
+ self.assertAlmostEqual(by_campaign["browsed"][AttributionMode.LINEAR], 0.5, places=4)
+ self.assertAlmostEqual(by_campaign["bounced"][AttributionMode.LINEAR], 0.5, places=4)
+
+ def test_touchpoints_outside_the_attribution_window_earn_nothing(self):
+ # The window is the whole point of an attribution model; a dropped bound would credit a touch
+ # from any point in history.
+ create_person(team=self.team, distinct_ids=["p1"])
+ self._session("p1", "2022-12-01T12:00:00Z", utm_campaign="ancient")
+ self._session("p1", ONE_DAY_BEFORE, utm_campaign="recent")
+ self._conversion("p1", CONVERSION_AT)
+
+ by_campaign = self._by_breakdown(self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN))
+
+ self.assertAlmostEqual(by_campaign["recent"][AttributionMode.LINEAR], 1.0, places=4)
+ self.assertNotIn("ancient", by_campaign)
+
+ def test_lookback_override_shrinks_the_window(self):
+ # The query-level override must actually reach the window math; a dropped wire silently falls
+ # back to the team's configured window and the UI control does nothing.
+ create_person(team=self.team, distinct_ids=["p1"])
+ self._session("p1", THREE_DAYS_BEFORE, utm_campaign="early")
+ self._session("p1", ONE_DAY_BEFORE, utm_campaign="late")
+ self._conversion("p1", CONVERSION_AT)
+
+ response = self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN, lookback_days=2)
+
+ self.assertEqual(response.attributionWindowDays, 2)
+ by_campaign = self._by_breakdown(response)
+ self.assertAlmostEqual(by_campaign["late"][AttributionMode.LINEAR], 1.0, places=4)
+ # The early touch stays visible as reach, but a 2-day window must not credit a 3-day-old touch.
+ self.assertAlmostEqual(by_campaign["early"][AttributionMode.LINEAR], 0.0, places=4)
+
+ def test_conversions_with_no_touchpoints_are_reported_not_dropped(self):
+ # An ARRAY JOIN over an empty touchpoint array yields no rows, so these conversions leave the
+ # table entirely. Reporting them is the only way a user can reconcile the model columns against
+ # their real conversion count.
+ create_person(team=self.team, distinct_ids=["p1"])
+ create_person(team=self.team, distinct_ids=["p2"])
+ self._session("p1", ONE_DAY_BEFORE, utm_campaign="a")
+ self._conversion("p1", CONVERSION_AT)
+ self._conversion("p2", CONVERSION_AT) # never browsed
+
+ response = self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN)
+
+ self.assertEqual(response.totalConversions, 2)
+ self.assertEqual(response.unattributedConversions, 1)
+
+ def test_value_columns_are_populated_only_for_revenue_goals(self):
+ # `hasValue` gates the value columns in the table. If the flag and the numbers disagree the UI
+ # either hides real revenue or shows a column of nulls.
+ create_person(team=self.team, distinct_ids=["p1"])
+ self._session("p1", ONE_DAY_BEFORE, utm_campaign="a")
+ self._conversion("p1", CONVERSION_AT, revenue=250.0)
+
+ revenue_response = self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN)
+ self.assertTrue(revenue_response.hasValue)
+ self.assertAlmostEqual(revenue_response.results[0].influencedValue or 0.0, 250.0, places=2)
+ last_touch = next(c for c in revenue_response.results[0].models if c.model == AttributionMode.LAST_TOUCH)
+ self.assertAlmostEqual(last_touch.conversionValue or 0.0, 250.0, places=2)
+
+ self._configure_goal(counts_as_revenue=False)
+ countable_response = self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN)
+ self.assertFalse(countable_response.hasValue)
+ self.assertIsNone(countable_response.results[0].influencedValue)
+ self.assertIsNone(countable_response.results[0].models[0].conversionValue)
+
+ def test_touchpoint_scan_is_restricted_to_people_who_converted(self):
+ # Widening touchpoints from UTM-tagged pageviews to every session multiplies the pageview side by
+ # roughly 10x; the converter semi-join is what pays that back. Dropping it changes no result and
+ # costs one to two orders of magnitude more, so no behavioural test can see it.
+ query = MarketingAnalyticsAttributionQuery(
+ dateRange=DateRange(date_from="2023-01-01", date_to="2023-01-31"),
+ breakdownBy=MarketingAnalyticsAttributionBreakdown.CHANNEL,
+ conversionGoalId=GOAL_ID,
+ properties=[],
+ )
+ runner = MarketingAnalyticsAttributionQueryRunner(query=query, team=self.team)
+ ctes = runner.to_query().ctes or {}
+ person_arrays = ctes["person_arrays"].expr
+ assert isinstance(person_arrays, ast.SelectQuery)
+
+ class FindSubqueryIn(TraversingVisitor):
+ def __init__(self) -> None:
+ self.found = False
+
+ def visit_compare_operation(self, node: ast.CompareOperation) -> None:
+ if node.op == ast.CompareOperationOp.In and isinstance(node.right, ast.SelectQuery):
+ self.found = True
+ super().visit_compare_operation(node)
+
+ finder = FindSubqueryIn()
+ finder.visit(person_arrays.where)
+ self.assertTrue(finder.found, "person_arrays must restrict the events scan to converting persons")
+
+ def test_action_goals_credit_the_events_the_action_matches(self):
+ # The action branch resolves the goal through Postgres and `action_to_expr` rather than a plain
+ # event name. A goal that silently matched nothing would render an empty table that reads as an
+ # honest absence of conversions.
+ action = Action.objects.create(team=self.team, name="Purchased", steps_json=[{"event": CONVERSION_EVENT}])
+ config = self.team.marketing_analytics_config
+ config.conversion_goals = [
+ ConversionGoalFilter2(
+ kind="ActionsNode",
+ id=str(action.pk),
+ name="Purchased",
+ conversion_goal_id=GOAL_ID,
+ conversion_goal_name="Purchased",
+ schema_map={},
+ math=BaseMathType.TOTAL,
+ ).model_dump()
+ ]
+ config.save()
+ create_person(team=self.team, distinct_ids=["p1"])
+ self._session("p1", ONE_DAY_BEFORE, utm_campaign="a")
+ self._conversion("p1", CONVERSION_AT)
+
+ response = self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN)
+
+ self.assertEqual(response.totalConversions, 1)
+ by_campaign = self._by_breakdown(response)
+ self.assertAlmostEqual(by_campaign["a"][AttributionMode.LAST_TOUCH], 1.0, places=4)
+
+ def test_referring_domain_breakdown_reads_the_sessions_entry_field(self):
+ # Channel and source get sentinel and normalization treatment; the remaining breakdowns pass the
+ # session's entry field straight through. A wrong field mapping would silently bucket every row
+ # under one value.
+ create_person(team=self.team, distinct_ids=["p1"])
+ create_person(team=self.team, distinct_ids=["p2"])
+ self._session("p1", ONE_DAY_BEFORE, referring_domain="google.com")
+ self._conversion("p1", CONVERSION_AT)
+ self._session("p2", ONE_DAY_BEFORE, referring_domain="news.ycombinator.com")
+ self._conversion("p2", CONVERSION_AT)
+
+ response = self._run(MarketingAnalyticsAttributionBreakdown.REFERRING_DOMAIN)
+
+ by_domain = self._by_breakdown(response)
+ self.assertAlmostEqual(by_domain["google.com"][AttributionMode.LAST_TOUCH], 1.0, places=4)
+ self.assertAlmostEqual(by_domain["news.ycombinator.com"][AttributionMode.LAST_TOUCH], 1.0, places=4)
+
+ def test_another_goals_problem_does_not_break_the_selected_goal(self):
+ # An unusable goal elsewhere in the team's settings used to replace the whole result with its
+ # warning, because those warnings were returned as the response's `error` and the table renders
+ # any error instead of rows. Asking for the broken goal itself still has to say why.
+ config = self.team.marketing_analytics_config
+ config.conversion_goals = [
+ *config.conversion_goals,
+ ConversionGoalFilter1(
+ kind="EventsNode",
+ event="",
+ name="All events",
+ conversion_goal_id="broken-goal",
+ conversion_goal_name="All events (misconfigured)",
+ schema_map={},
+ math=BaseMathType.TOTAL,
+ ).model_dump(),
+ ]
+ config.save()
+ create_person(team=self.team, distinct_ids=["p1"])
+ self._session("p1", ONE_DAY_BEFORE, utm_campaign="a")
+ self._conversion("p1", CONVERSION_AT)
+
+ response = self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN)
+ self.assertIsNone(response.error)
+ self.assertEqual([row.breakdownValue for row in response.results], ["a"])
+
+ broken = MarketingAnalyticsAttributionQuery(
+ dateRange=DateRange(date_from="2023-01-01", date_to="2023-01-31"),
+ conversionGoalId="broken-goal",
+ properties=[],
+ )
+ with self.assertRaises(ValueError) as raised:
+ MarketingAnalyticsAttributionQueryRunner(query=broken, team=self.team).to_query()
+ self.assertIn("All events (misconfigured)", str(raised.exception))
+
+ @parameterized.expand(
+ [
+ ("unknown_goal", "does-not-exist"),
+ ("empty_goal", ""),
+ ]
+ )
+ def test_unresolvable_goal_raises(self, _name: str, goal_id: str):
+ # A goal id that doesn't resolve must fail loudly. Falling through to "no conversions" would
+ # render an empty table that looks like a genuine absence of conversions.
+ query = MarketingAnalyticsAttributionQuery(
+ dateRange=DateRange(date_from="2023-01-01", date_to="2023-01-31"),
+ conversionGoalId=goal_id,
+ properties=[],
+ )
+ runner = MarketingAnalyticsAttributionQueryRunner(query=query, team=self.team)
+ with self.assertRaises(ValueError):
+ runner.to_query()
+
+ def test_goal_property_filters_narrow_the_conversions_counted(self):
+ # The goal's own property filters are part of what a conversion is. Matching on the event name
+ # alone counts purchases the Dashboard excludes, so the same goal reports two different numbers
+ # on two tabs with nothing saying which is right.
+ config = self.team.marketing_analytics_config
+ config.conversion_goals = [
+ ConversionGoalFilter1(
+ kind="EventsNode",
+ event=CONVERSION_EVENT,
+ name="Big purchases",
+ conversion_goal_id=GOAL_ID,
+ conversion_goal_name="Big purchases",
+ schema_map={},
+ math=BaseMathType.TOTAL,
+ properties=[
+ EventPropertyFilter(key="plan", operator=PropertyOperator.EXACT, value=["pro"], type="event")
+ ],
+ ).model_dump()
+ ]
+ config.save()
+ create_person(team=self.team, distinct_ids=["p1"])
+ self._session("p1", ONE_DAY_BEFORE, utm_campaign="a")
+ for at, plan in ((CONVERSION_AT, "pro"), ("2023-01-10T13:00:00Z", "free")):
+ _create_event(
+ team=self.team,
+ event=CONVERSION_EVENT,
+ distinct_id="p1",
+ timestamp=at,
+ properties={"revenue": 100.0, "plan": plan},
+ )
+
+ response = self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN)
+
+ self.assertEqual(response.totalConversions, 1)
+ by_campaign = self._by_breakdown(response)
+ self.assertAlmostEqual(by_campaign["a"][AttributionMode.LAST_TOUCH], 1.0, places=4)
+
+ def test_action_goal_whose_action_is_gone_reports_the_misconfiguration(self):
+ # An unresolvable action used to raise Action.DoesNotExist out of query building, so a goal
+ # pointing at a deleted action 500d instead of telling the user to fix the goal.
+ config = self.team.marketing_analytics_config
+ config.conversion_goals = [
+ ConversionGoalFilter2(
+ kind="ActionsNode",
+ id=99999999,
+ name="Purchased",
+ conversion_goal_id=GOAL_ID,
+ conversion_goal_name="Purchased",
+ schema_map={},
+ math=BaseMathType.TOTAL,
+ ).model_dump()
+ ]
+ config.save()
+
+ query = MarketingAnalyticsAttributionQuery(
+ dateRange=DateRange(date_from="2023-01-01", date_to="2023-01-31"),
+ conversionGoalId=GOAL_ID,
+ properties=[],
+ )
+ with self.assertRaises(ValueError) as raised:
+ MarketingAnalyticsAttributionQueryRunner(query=query, team=self.team).to_query()
+ self.assertIn("no longer exists", str(raised.exception))
+
+ def test_reconciliation_survives_a_result_with_no_dimension_rows(self):
+ # Conversions with no session at all produce neither credit nor reach, so the join emits nothing.
+ # The counts used to be scalar subqueries on that empty row set, reporting zero conversions
+ # instead of "all of them went uncredited", which is the one thing worth saying here.
+ create_person(team=self.team, distinct_ids=["p1"])
+ self._conversion("p1", CONVERSION_AT)
+
+ response = self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN)
+
+ self.assertEqual(response.results, [])
+ self.assertEqual(response.totalConversions, 1)
+ self.assertEqual(response.unattributedConversions, 1)
+
+ def test_per_conversion_is_materialized_for_its_two_readers(self):
+ # Two CTEs read per_conversion, and ClickHouse re-evaluates a plain CTE at each reference, which
+ # would run the events scan underneath it twice. Nothing about the results can show this.
+ query = MarketingAnalyticsAttributionQuery(
+ dateRange=DateRange(date_from="2023-01-01", date_to="2023-01-31"),
+ conversionGoalId=GOAL_ID,
+ properties=[],
+ )
+ ctes = MarketingAnalyticsAttributionQueryRunner(query=query, team=self.team).to_query().ctes or {}
+ self.assertTrue(ctes["per_conversion"].materialized)
+
+ @parameterized.expand(
+ [
+ ("restricted_for_this_user", True),
+ ("not_restricted", False),
+ ]
+ )
+ def test_property_denied_to_this_user_is_never_read(self, _name: str, restricted: bool):
+ # The runner hands execute_hogql_query a prebuilt context, which stops it building a user-aware
+ # one, and the printer loads property-level access control off that context. A context without the
+ # user resolves only the team's default restrictions, so a property denied to this user alone was
+ # read unmasked. ConversionGoalProcessor skips precompute specifically to fall back on this
+ # masking, so it has to hold on the direct path.
+ config = self.team.marketing_analytics_config
+ config.conversion_goals = [
+ ConversionGoalFilter1(
+ kind="EventsNode",
+ event=CONVERSION_EVENT,
+ name="Pro purchases",
+ conversion_goal_id=GOAL_ID,
+ conversion_goal_name="Pro purchases",
+ schema_map={},
+ math=BaseMathType.TOTAL,
+ properties=[
+ EventPropertyFilter(key="plan", operator=PropertyOperator.EXACT, value=["pro"], type="event")
+ ],
+ ).model_dump()
+ ]
+ config.save()
+
+ query = MarketingAnalyticsAttributionQuery(
+ dateRange=DateRange(date_from="2023-01-01", date_to="2023-01-31"),
+ conversionGoalId=GOAL_ID,
+ properties=[],
+ )
+ runner = MarketingAnalyticsAttributionQueryRunner(query=query, team=self.team, user=self.user)
+ context = runner._shared_hogql_context
+ # execute_hogql_query flips this on the context it is handed; do the same to print the real query.
+ context.enable_select_queries = True
+
+ # Mirrors the real lookup: userless callers get the team defaults only, which is why a context
+ # missing the user silently loses this user's own denial.
+ def restrictions_for(*, user, **_kwargs) -> set:
+ if user is None or not restricted:
+ return set()
+ return {("plan", PropertyDefinition.Type.EVENT)}
+
+ with patch(
+ "products.access_control.backend.property_access_control.get_restricted_properties_for_team",
+ side_effect=restrictions_for,
+ ):
+ prepare_and_print_ast(runner.to_query(), context=context, dialect="clickhouse")
+
+ # The property only reaches ClickHouse as a parameter when the query actually extracts it.
+ self.assertEqual("plan" in str(context.values), not restricted)
+
+ @parameterized.expand([("zero", 0), ("negative", -1), ("over_the_ceiling", MAX_ATTRIBUTION_WINDOW_DAYS + 1)])
+ def test_lookback_override_outside_the_allowed_range_is_rejected(self, _name: str, days: int):
+ # The override widens the events scan and the schema types it as a plain integer, so without this
+ # a hand-built query could scan the team's entire event history.
+ query = MarketingAnalyticsAttributionQuery(
+ dateRange=DateRange(date_from="2023-01-01", date_to="2023-01-31"),
+ conversionGoalId=GOAL_ID,
+ lookbackWindowDays=days,
+ properties=[],
+ )
+ with self.assertRaises(ValueError):
+ MarketingAnalyticsAttributionQueryRunner(query=query, team=self.team).to_query()
diff --git a/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_processor.py b/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_processor.py
index fb34e71fc103..1a933af9f15c 100644
--- a/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_processor.py
+++ b/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_processor.py
@@ -26,10 +26,10 @@ from posthog.hogql.test.utils import pretty_print_in_tests
from posthog.models.event.util import bulk_create_events
from products.actions.backend.models.action import Action
-from products.marketing_analytics.backend.hogql_queries.conversion_goal_processor import (
- ConversionGoalProcessor,
+from products.marketing_analytics.backend.hogql_queries.conversion_goal_conditions import (
add_conversion_goal_property_filters,
)
+from products.marketing_analytics.backend.hogql_queries.conversion_goal_processor import ConversionGoalProcessor
from products.marketing_analytics.backend.hogql_queries.marketing_analytics_config import MarketingAnalyticsConfig
from products.warehouse_sources.backend.facade.testing import create_data_warehouse_table_from_csv
@@ -1287,7 +1287,8 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
# ================================================================
def test_error_missing_action(self):
- """Test error handling when Action doesn't exist"""
+ # A goal whose action was deleted matches nothing, rather than raising and taking every other
+ # goal on the dashboard down with it. The conversion-array branch already behaved this way.
goal = ConversionGoalFilter2(
kind="ActionsNode",
id=999999,
@@ -1299,8 +1300,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
processor = ConversionGoalProcessor(goal=goal, index=0, team=self.team, config=self.config)
- with pytest.raises(Action.DoesNotExist):
- processor.get_base_where_conditions()
+ assert processor.get_base_where_conditions() == [ast.Constant(value=False)]
def test_error_invalid_math_property_combination(self):
"""Test graceful handling of invalid math+property combinations"""
diff --git a/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_table_query_runner.py b/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_table_query_runner.py
index 36998ad8d016..e3fafc49107c 100644
--- a/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_table_query_runner.py
+++ b/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_table_query_runner.py
@@ -232,10 +232,10 @@ class TestMarketingAnalyticsTableQueryRunner(ClickhouseTestMixin, BaseTest):
all_goals = runner._get_team_conversion_goals()
assert len(all_goals) == 3 # 1 valid + 2 invalid
- valid_goals, warnings = runner._filter_invalid_conversion_goals(all_goals)
+ valid_goals, skipped = runner._filter_invalid_conversion_goals(all_goals)
assert len(valid_goals) == 1 # Only the valid goal remains
assert valid_goals[0].conversion_goal_name == "Valid Purchase Goal"
- assert len(warnings) == 2
+ assert len(skipped) == 2
with patch.object(MarketingAnalyticsTableQueryRunner, "_get_marketing_source_adapters") as mock_get_adapters:
mock_get_adapters.return_value = []
@@ -285,12 +285,12 @@ class TestMarketingAnalyticsTableQueryRunner(ClickhouseTestMixin, BaseTest):
)
runner = self._create_query_runner()
- valid_goals, warnings = runner._filter_invalid_conversion_goals([dw_goal])
+ valid_goals, skipped = runner._filter_invalid_conversion_goals([dw_goal])
assert len(valid_goals) == 0
- assert len(warnings) == 1
- assert "nonexistent_table" in warnings[0]
- assert "not found" in warnings[0]
+ assert len(skipped) == 1
+ assert "nonexistent_table" in skipped[0].message
+ assert "not found" in skipped[0].message
def test_dw_goal_with_missing_columns_filtered_out(self):
"""DataWarehouseNode goals referencing missing columns are filtered out with a warning"""
@@ -319,12 +319,12 @@ class TestMarketingAnalyticsTableQueryRunner(ClickhouseTestMixin, BaseTest):
)
runner = self._create_query_runner()
- valid_goals, warnings = runner._filter_invalid_conversion_goals([dw_goal])
+ valid_goals, skipped = runner._filter_invalid_conversion_goals([dw_goal])
assert len(valid_goals) == 0
- assert len(warnings) == 1
- assert "utm_campaign" in warnings[0]
- assert "utm_source" in warnings[0]
+ assert len(skipped) == 1
+ assert "utm_campaign" in skipped[0].message
+ assert "utm_source" in skipped[0].message
def test_dw_goal_with_valid_columns_passes(self):
"""DataWarehouseNode goals with valid column mappings pass validation"""
@@ -355,10 +355,10 @@ class TestMarketingAnalyticsTableQueryRunner(ClickhouseTestMixin, BaseTest):
)
runner = self._create_query_runner()
- valid_goals, warnings = runner._filter_invalid_conversion_goals([dw_goal])
+ valid_goals, skipped = runner._filter_invalid_conversion_goals([dw_goal])
assert len(valid_goals) == 1
- assert len(warnings) == 0
+ assert len(skipped) == 0
assert valid_goals[0].conversion_goal_name == "Valid DW Goal"
def test_mixed_valid_and_invalid_goals(self):
@@ -386,12 +386,12 @@ class TestMarketingAnalyticsTableQueryRunner(ClickhouseTestMixin, BaseTest):
)
runner = self._create_query_runner()
- valid_goals, warnings = runner._filter_invalid_conversion_goals([event_goal, dw_goal])
+ valid_goals, skipped = runner._filter_invalid_conversion_goals([event_goal, dw_goal])
assert len(valid_goals) == 1
assert valid_goals[0].conversion_goal_name == "Test Goal"
- assert len(warnings) == 1
- assert "Bad DW Goal" in warnings[0]
+ assert len(skipped) == 1
+ assert "Bad DW Goal" in skipped[0].message
def test_duplicate_named_goals_deduped(self):
"""Goals sharing a name collapse to the first with a warning, to avoid alias collisions"""
@@ -413,13 +413,13 @@ class TestMarketingAnalyticsTableQueryRunner(ClickhouseTestMixin, BaseTest):
)
runner = self._create_query_runner()
- valid_goals, warnings = runner._filter_invalid_conversion_goals([first, second])
+ valid_goals, skipped = runner._filter_invalid_conversion_goals([first, second])
assert len(valid_goals) == 1
assert valid_goals[0].conversion_goal_id == "goal_a"
- assert len(warnings) == 1
- assert "duplicate name" in warnings[0]
- assert "Signups" in warnings[0]
+ assert len(skipped) == 1
+ assert "duplicate name" in skipped[0].message
+ assert "Signups" in skipped[0].message
def test_get_filtered_select_columns_dedupes_repeated_request(self):
"""A column requested twice is emitted once, avoiding 'Cannot redefine an alias'"""
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index d3e9ea48e141..3cf06f0f1e2a 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -9478,6 +9478,17 @@ export namespace Schemas {
sample_unmatched_utm_sources: UnmatchedUtmSample[];
}
+ export type AttributionMode = typeof AttributionMode[keyof typeof AttributionMode];
+
+
+ export const AttributionMode = {
+ FirstTouch: 'first_touch',
+ LastTouch: 'last_touch',
+ Linear: 'linear',
+ TimeDecay: 'time_decay',
+ PositionBased: 'position_based',
+ } as const;
+
/**
* * `first_touch` - First Touch
* * `last_touch` - Last Touch
@@ -35382,6 +35393,119 @@ export namespace Schemas {
version?: number | null;
}
+ export type MarketingAnalyticsAttributionBreakdown = typeof MarketingAnalyticsAttributionBreakdown[keyof typeof MarketingAnalyticsAttributionBreakdown];
+
+
+ export const MarketingAnalyticsAttributionBreakdown = {
+ Channel: 'channel',
+ Source: 'source',
+ Campaign: 'campaign',
+ Medium: 'medium',
+ Content: 'content',
+ Term: 'term',
+ ReferringDomain: 'referring_domain',
+ LandingPage: 'landing_page',
+ } as const;
+
+ export interface MarketingAnalyticsAttributionModelCell {
+ /** conversions / visitors. Null when the row has no visitors. */
+ conversionRate: number | null;
+ /** Null unless the goal is revenue-bearing. */
+ conversionValue: number | null;
+ /** Fractional for multi-touch models: each conversion's credit is split across its touchpoints. */
+ conversions: number;
+ model: AttributionMode;
+ }
+
+ export interface MarketingAnalyticsAttributionRow {
+ breakdownValue: string;
+ /** Conversions with at least one touchpoint on this dimension. Counted once per conversion, so a conversion influenced by several dimensions is counted in each of their rows. These deliberately sum to more than the total, unlike the per-model columns. */
+ influencedConversions: number;
+ influencedValue?: number | null;
+ /** One cell per model, always in the order given by the response's `models`. */
+ models: MarketingAnalyticsAttributionModelCell[];
+ /** Unique persons who arrived via this dimension in the date range, converters or not. */
+ visitors: number;
+ }
+
+ export interface MarketingAnalyticsAttributionQueryResponse {
+ /** Whether this result counted a repeat converter's every conversion, after resolving the query's null against the goal's math. The rate columns are a true share only when this is false, so the table reads it to label them. */
+ allowsMultipleConversionsPerVisitor: boolean;
+ /** The team's configured attribution window, 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 columns. */
+ hasValue: boolean;
+ /** Generated HogQL query. */
+ hogql?: string | null;
+ limit?: number | null;
+ /** Model order for the column groups. */
+ models: AttributionMode[];
+ /** 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: MarketingAnalyticsAttributionRow[];
+ /** Measured timings for different parts of the query generation process */
+ timings?: QueryTiming[] | null;
+ /** Total conversions in range, so the footer can say "N of M". */
+ totalConversions: number;
+ /** Conversions with no touchpoint in the window. Reported in the footer, not in any row. */
+ unattributedConversions: 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 MarketingAnalyticsAttributionQuery {
+ /** Groups aggregation - not used in Web Analytics but required for type compatibility */
+ aggregation_group_type_index?: number | null;
+ /** Whether one person converting repeatedly counts once or every time. Null follows the goal's own math: unique-users goals count each person once, count-based goals count every conversion. Set explicitly to override. Counting every conversion makes the rate columns exceed 100%, since a person can convert more times than they visited. */
+ allowMultipleConversionsPerVisitor?: boolean | null;
+ /** Row dimension. Defaults to channel. */
+ breakdownBy?: MarketingAnalyticsAttributionBreakdown | null;
+ conversionGoal?: ActionConversionGoal | CustomEventConversionGoal | null;
+ /** conversion_goal_id of the goal to attribute. The table is meaningless without one. */
+ 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 the touchpoint set before weights are computed, so the remaining touchpoints renormalize to full credit rather than losing direct's share. */
+ excludeDirectTraffic?: 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?: 'MarketingAnalyticsAttributionQuery';
+ /** Number of rows to return */
+ limit?: number | null;
+ /** How many days before each conversion a touchpoint can earn credit, overriding the team's configured attribution window for this query only. */
+ lookbackWindowDays?: 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?: MarketingAnalyticsAttributionQueryResponse | 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;
}
@@ -37126,7 +37250,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 | 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 | 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;
@@ -37152,7 +37276,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 | 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 | 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;
@@ -59751,7 +59875,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 | 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 | 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
@@ -60490,6 +60614,43 @@ export namespace Schemas {
}
export interface QueryResponseAlternative32 {
+ /** Whether this result counted a repeat converter's every conversion, after resolving the query's null against the goal's math. The rate columns are a true share only when this is false, so the table reads it to label them. */
+ allowsMultipleConversionsPerVisitor: boolean;
+ /** The team's configured attribution window, 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 columns. */
+ hasValue: boolean;
+ /** Generated HogQL query. */
+ hogql?: string | null;
+ limit?: number | null;
+ /** Model order for the column groups. */
+ models: AttributionMode[];
+ /** 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: MarketingAnalyticsAttributionRow[];
+ /** Measured timings for different parts of the query generation process */
+ timings?: QueryTiming[] | null;
+ /** Total conversions in range, so the footer can say "N of M". */
+ totalConversions: number;
+ /** Conversions with no touchpoint in the window. Reported in the footer, not in any row. */
+ unattributedConversions: 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 QueryResponseAlternative33 {
columns?: unknown[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -60517,7 +60678,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative33 {
+ export interface QueryResponseAlternative34 {
columns: unknown[];
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -60546,7 +60707,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;
@@ -60574,7 +60735,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;
@@ -60602,7 +60763,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative36 {
+ export interface QueryResponseAlternative37 {
/** Executed ClickHouse query */
clickhouse?: string | null;
/** Returned columns */
@@ -60639,7 +60800,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative37 {
+ export interface QueryResponseAlternative38 {
dateFrom?: string | null;
dateTo?: string | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
@@ -60665,7 +60826,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative38 {
+ export interface QueryResponseAlternative39 {
columns?: unknown[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -60696,7 +60857,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;
@@ -60724,7 +60885,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;
@@ -60751,7 +60912,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;
@@ -60780,7 +60941,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative42 {
+ export interface QueryResponseAlternative43 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -60807,7 +60968,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative43 {
+ export interface QueryResponseAlternative44 {
columns?: unknown[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -60834,7 +60995,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative44 {
+ export interface QueryResponseAlternative45 {
columns: unknown[];
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -60861,7 +61022,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative45 {
+ export interface QueryResponseAlternative46 {
columns?: unknown[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -60889,9 +61050,9 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export type QueryResponseAlternative46Results = {[key: string]: MarketingAnalyticsItem};
+ export type QueryResponseAlternative47Results = {[key: string]: MarketingAnalyticsItem};
- export interface QueryResponseAlternative46 {
+ export interface QueryResponseAlternative47 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -60904,7 +61065,7 @@ export namespace Schemas {
resolved_compare_date_range?: ResolvedDateRangeResponse | null;
/** The date range used for the query */
resolved_date_range?: ResolvedDateRangeResponse | null;
- results: QueryResponseAlternative46Results;
+ results: QueryResponseAlternative47Results;
samplingRate?: SamplingRate | null;
/** Measured timings for different parts of the query generation process */
timings?: QueryTiming[] | null;
@@ -60914,7 +61075,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative47 {
+ export interface QueryResponseAlternative48 {
columns?: unknown[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -60942,7 +61103,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative48 {
+ export interface QueryResponseAlternative49 {
columns?: string[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -60968,19 +61129,19 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export type QueryResponseAlternative50CredibleIntervals = {[key: string]: number[]};
+ export type QueryResponseAlternative51CredibleIntervals = {[key: string]: number[]};
- export type QueryResponseAlternative50InsightItemItem = { [key: string]: unknown };
+ export type QueryResponseAlternative51InsightItemItem = { [key: string]: unknown };
- export type QueryResponseAlternative50Probability = {[key: string]: number};
+ export type QueryResponseAlternative51Probability = {[key: string]: number};
- export interface QueryResponseAlternative50 {
- credible_intervals: QueryResponseAlternative50CredibleIntervals;
+ export interface QueryResponseAlternative51 {
+ credible_intervals: QueryResponseAlternative51CredibleIntervals;
expected_loss: number;
funnels_query?: FunnelsQuery | null;
- insight: QueryResponseAlternative50InsightItemItem[][];
+ insight: QueryResponseAlternative51InsightItemItem[][];
kind?: 'ExperimentFunnelsQuery';
- probability: QueryResponseAlternative50Probability;
+ probability: QueryResponseAlternative51Probability;
significance_code: ExperimentSignificanceCode;
significant: boolean;
stats_version?: number | null;
@@ -60989,20 +61150,20 @@ export namespace Schemas {
warnings?: DataWarehouseSyncWarning[] | null;
}
- export type QueryResponseAlternative51CredibleIntervals = {[key: string]: number[]};
+ export type QueryResponseAlternative52CredibleIntervals = {[key: string]: number[]};
- export type QueryResponseAlternative51InsightItem = { [key: string]: unknown };
+ export type QueryResponseAlternative52InsightItem = { [key: string]: unknown };
- export type QueryResponseAlternative51Probability = {[key: string]: number};
+ export type QueryResponseAlternative52Probability = {[key: string]: number};
- export interface QueryResponseAlternative51 {
+ export interface QueryResponseAlternative52 {
count_query?: TrendsQuery | null;
- credible_intervals: QueryResponseAlternative51CredibleIntervals;
+ credible_intervals: QueryResponseAlternative52CredibleIntervals;
exposure_query?: TrendsQuery | null;
- insight: QueryResponseAlternative51InsightItem[];
+ insight: QueryResponseAlternative52InsightItem[];
kind?: 'ExperimentTrendsQuery';
p_value: number;
- probability: QueryResponseAlternative51Probability;
+ probability: QueryResponseAlternative52Probability;
significance_code: ExperimentSignificanceCode;
significant: boolean;
stats_version?: number | null;
@@ -61011,7 +61172,7 @@ export namespace Schemas {
warnings?: DataWarehouseSyncWarning[] | null;
}
- export interface QueryResponseAlternative52 {
+ export interface QueryResponseAlternative53 {
columns?: string[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -61037,7 +61198,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative54 {
+ export interface QueryResponseAlternative55 {
columns?: unknown[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -61064,7 +61225,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative55 {
+ export interface QueryResponseAlternative56 {
columns: unknown[];
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -61094,9 +61255,9 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export type QueryResponseAlternative56ResultsItem = { [key: string]: unknown };
+ export type QueryResponseAlternative57ResultsItem = { [key: string]: unknown };
- export interface QueryResponseAlternative56 {
+ export interface QueryResponseAlternative57 {
boxplot_data?: BoxPlotDatum[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -61112,7 +61273,7 @@ export namespace Schemas {
resolved_compare_date_range?: ResolvedDateRangeResponse | null;
/** The date range used for the query */
resolved_date_range?: ResolvedDateRangeResponse | null;
- results: QueryResponseAlternative56ResultsItem[];
+ results: QueryResponseAlternative57ResultsItem[];
/** Measured timings for different parts of the query generation process */
timings?: QueryTiming[] | null;
/** Connector-synced data warehouse sources referenced by this query, if any. */
@@ -61121,7 +61282,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative57 {
+ export interface QueryResponseAlternative58 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -61145,7 +61306,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. */
@@ -61167,7 +61328,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. */
@@ -61189,9 +61350,9 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export type QueryResponseAlternative60ResultsItem = { [key: string]: unknown };
+ export type QueryResponseAlternative61ResultsItem = { [key: string]: unknown };
- 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. */
@@ -61204,7 +61365,7 @@ export namespace Schemas {
resolved_compare_date_range?: ResolvedDateRangeResponse | null;
/** The date range used for the query */
resolved_date_range?: ResolvedDateRangeResponse | null;
- results: QueryResponseAlternative60ResultsItem[];
+ results: QueryResponseAlternative61ResultsItem[];
/** Measured timings for different parts of the query generation process */
timings?: QueryTiming[] | null;
/** Connector-synced data warehouse sources referenced by this query, if any. */
@@ -61213,7 +61374,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative62 {
+ export interface QueryResponseAlternative63 {
columns?: unknown[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -61240,14 +61401,14 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export type QueryResponseAlternative63Tables = {[key: string]: DatabaseSchemaPostHogTable | DatabaseSchemaSystemTable | DatabaseSchemaDataWarehouseTable | DatabaseSchemaViewTable | DatabaseSchemaManagedViewTable | DatabaseSchemaBatchExportTable | DatabaseSchemaMaterializedViewTable | DatabaseSchemaEndpointTable};
+ export type QueryResponseAlternative64Tables = {[key: string]: DatabaseSchemaPostHogTable | DatabaseSchemaSystemTable | DatabaseSchemaDataWarehouseTable | DatabaseSchemaViewTable | DatabaseSchemaManagedViewTable | DatabaseSchemaBatchExportTable | DatabaseSchemaMaterializedViewTable | DatabaseSchemaEndpointTable};
- export interface QueryResponseAlternative63 {
+ export interface QueryResponseAlternative64 {
joins: DataWarehouseViewLink[];
- tables: QueryResponseAlternative63Tables;
+ tables: QueryResponseAlternative64Tables;
}
- export interface QueryResponseAlternative64 {
+ export interface QueryResponseAlternative65 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
has_next: boolean;
@@ -61272,7 +61433,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative65 {
+ export interface QueryResponseAlternative66 {
columns?: string[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -61300,7 +61461,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative66 {
+ export interface QueryResponseAlternative67 {
count: number;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -61323,7 +61484,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative67 {
+ export interface QueryResponseAlternative68 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -61345,7 +61506,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. */
@@ -61367,7 +61528,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;
hasMore?: boolean | null;
@@ -61394,7 +61555,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative70 {
+ export interface QueryResponseAlternative71 {
/** 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. */
@@ -61418,7 +61579,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?: SpanTreeNode[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
@@ -61442,7 +61603,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?: AttributeBreakdownRow[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
@@ -61466,13 +61627,13 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative73 {
+ export interface QueryResponseAlternative74 {
questions: string[];
/** Data warehouse sync warnings — see AnalyticsQueryResponseBase.warnings for semantics. */
warnings?: DataWarehouseSyncWarning[] | null;
}
- export interface QueryResponseAlternative74 {
+ export interface QueryResponseAlternative75 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
hasMore?: boolean | null;
@@ -61497,7 +61658,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | 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;
@@ -61522,7 +61683,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;
/** Generated HogQL query. */
@@ -61544,7 +61705,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative77 {
+ export interface QueryResponseAlternative78 {
columns?: string[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -61570,7 +61731,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative80 {
+ export interface QueryResponseAlternative81 {
/** Timestamp of the newer trace */
newerTimestamp?: string | null;
/** ID of the newer trace (chronologically after current) */
@@ -61585,7 +61746,7 @@ export namespace Schemas {
warnings?: DataWarehouseSyncWarning[] | null;
}
- export interface QueryResponseAlternative81 {
+ export interface QueryResponseAlternative82 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -61607,7 +61768,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | 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. */
@@ -61629,7 +61790,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative83 {
+ export interface QueryResponseAlternative84 {
columns: unknown[];
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -61659,7 +61820,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative84 {
+ export interface QueryResponseAlternative85 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -61681,7 +61842,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative85 {
+ export interface QueryResponseAlternative86 {
columns?: unknown[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -61708,9 +61869,9 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export type QueryResponseAlternative86ResultsItem = { [key: string]: unknown };
+ export type QueryResponseAlternative87ResultsItem = { [key: string]: unknown };
- export interface QueryResponseAlternative86 {
+ export interface QueryResponseAlternative87 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -61723,7 +61884,7 @@ export namespace Schemas {
resolved_compare_date_range?: ResolvedDateRangeResponse | null;
/** The date range used for the query */
resolved_date_range?: ResolvedDateRangeResponse | null;
- results: QueryResponseAlternative86ResultsItem[];
+ results: QueryResponseAlternative87ResultsItem[];
/** Measured timings for different parts of the query generation process */
timings?: QueryTiming[] | null;
/** Connector-synced data warehouse sources referenced by this query, if any. */
@@ -61732,7 +61893,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- 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. */
@@ -61754,7 +61915,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. */
@@ -61776,7 +61937,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. */
@@ -61798,7 +61959,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. */
@@ -61820,7 +61981,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. */
@@ -61842,7 +62003,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. */
@@ -61864,7 +62025,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. */
@@ -61887,7 +62048,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. */
@@ -61909,7 +62070,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. */
@@ -61931,7 +62092,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. */
@@ -61953,7 +62114,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. */
@@ -61975,7 +62136,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. */
@@ -61997,7 +62158,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. */
@@ -62019,7 +62180,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. */
@@ -62041,7 +62202,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. */
@@ -62063,7 +62224,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. */
@@ -62085,18 +62246,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 | unknown | QueryResponseAlternative33 | QueryResponseAlternative34 | QueryResponseAlternative35 | QueryResponseAlternative36 | QueryResponseAlternative37 | QueryResponseAlternative38 | QueryResponseAlternative39 | QueryResponseAlternative40 | QueryResponseAlternative41 | QueryResponseAlternative42 | QueryResponseAlternative43 | QueryResponseAlternative44 | QueryResponseAlternative45 | QueryResponseAlternative46 | QueryResponseAlternative47 | QueryResponseAlternative48 | QueryResponseAlternative50 | QueryResponseAlternative51 | QueryResponseAlternative52 | QueryResponseAlternative54 | QueryResponseAlternative55 | QueryResponseAlternative56 | QueryResponseAlternative57 | QueryResponseAlternative58 | QueryResponseAlternative59 | QueryResponseAlternative60 | QueryResponseAlternative62 | QueryResponseAlternative63 | QueryResponseAlternative64 | QueryResponseAlternative65 | QueryResponseAlternative66 | QueryResponseAlternative67 | QueryResponseAlternative68 | QueryResponseAlternative69 | QueryResponseAlternative70 | QueryResponseAlternative71 | QueryResponseAlternative72 | QueryResponseAlternative73 | QueryResponseAlternative74 | QueryResponseAlternative75 | QueryResponseAlternative76 | QueryResponseAlternative77 | QueryResponseAlternative80 | QueryResponseAlternative81 | QueryResponseAlternative82 | QueryResponseAlternative83 | QueryResponseAlternative84 | QueryResponseAlternative85 | QueryResponseAlternative86 | QueryResponseAlternative87 | QueryResponseAlternative88 | QueryResponseAlternative89 | QueryResponseAlternative90 | QueryResponseAlternative91 | QueryResponseAlternative92 | QueryResponseAlternative93 | QueryResponseAlternative94 | QueryResponseAlternative95 | QueryResponseAlternative96 | QueryResponseAlternative97 | QueryResponseAlternative98 | QueryResponseAlternative99 | QueryResponseAlternative100 | QueryResponseAlternative101 | QueryResponseAlternative102;
+ 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 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 | 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 | 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 | 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 | 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 {