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-analytics): acquisition cohort retention query (#86908)

Javier Bahamondes7bdadfb8c912
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 131859f66d55..3990a8e22e72 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -1586,6 +1586,9 @@
{
"$ref": "#/definitions/MarketingAnalyticsAttributionPathsQuery"
},
+ {
+ "$ref": "#/definitions/MarketingAnalyticsRetentionQuery"
+ },
{
"$ref": "#/definitions/NonIntegratedConversionsTableQuery"
},
@@ -11691,6 +11694,138 @@
],
"type": "object"
},
+ "CachedMarketingAnalyticsRetentionQueryResponse": {
+ "additionalProperties": false,
+ "properties": {
+ "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"
+ },
+ "hogql": {
+ "description": "Generated HogQL query.",
+ "type": "string"
+ },
+ "interval": {
+ "$ref": "#/definitions/MarketingAnalyticsRetentionInterval"
+ },
+ "intervalCount": {
+ "$ref": "#/definitions/integer",
+ "description": "Column count. Every row's values array has this length."
+ },
+ "is_cached": {
+ "type": "boolean"
+ },
+ "labels": {
+ "description": "Column headers, e.g. ['Week 0', 'Week 1', ...].",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "last_refresh": {
+ "format": "date-time",
+ "type": "string"
+ },
+ "modifiers": {
+ "$ref": "#/definitions/HogQLQueryModifiers",
+ "description": "Modifiers used when performing the query"
+ },
+ "next_allowed_client_refresh": {
+ "format": "date-time",
+ "type": "string"
+ },
+ "otherBreakdownCount": {
+ "$ref": "#/definitions/integer",
+ "description": "How many breakdown values were folded into 'Other', so the table can say so."
+ },
+ "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/MarketingAnalyticsRetentionRow"
+ },
+ "type": "array"
+ },
+ "timezone": {
+ "type": "string"
+ },
+ "timings": {
+ "description": "Measured timings for different parts of the query generation process",
+ "items": {
+ "$ref": "#/definitions/QueryTiming"
+ },
+ "type": "array"
+ },
+ "totalCohortSize": {
+ "$ref": "#/definitions/integer",
+ "description": "Distinct persons acquired across every cohort and breakdown value."
+ },
+ "truncatedCohorts": {
+ "$ref": "#/definitions/integer",
+ "description": "Older cohorts dropped to bound the matrix. Non-zero means the table covers less than the date range the filter bar shows, so the table has to say so."
+ },
+ "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": [
+ "cache_key",
+ "interval",
+ "intervalCount",
+ "is_cached",
+ "labels",
+ "last_refresh",
+ "next_allowed_client_refresh",
+ "otherBreakdownCount",
+ "results",
+ "timezone",
+ "totalCohortSize",
+ "truncatedCohorts"
+ ],
+ "type": "object"
+ },
"CachedMarketingAnalyticsTableQueryResponse": {
"additionalProperties": false,
"properties": {
@@ -34076,7 +34211,7 @@
"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.",
+ "description": "Dimension a session is sliced by, shared by the Attribution table and the Retention explorer. 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"
},
@@ -34754,6 +34889,250 @@
"minItems": 2,
"type": "array"
},
+ "MarketingAnalyticsRetentionCell": {
+ "additionalProperties": false,
+ "description": "One cohort's activity in one period since acquisition.",
+ "properties": {
+ "complete": {
+ "description": "False when this period has not fully elapsed within the queried range, so a low cell reads as unfinished instead of as churn.",
+ "type": "boolean"
+ },
+ "count": {
+ "$ref": "#/definitions/integer",
+ "description": "Distinct persons from this cohort active in this period."
+ },
+ "rate": {
+ "description": "count / cohortSize. Null when the cohort is empty.",
+ "type": ["number", "null"]
+ }
+ },
+ "required": ["count", "rate", "complete"],
+ "type": "object"
+ },
+ "MarketingAnalyticsRetentionInterval": {
+ "description": "Cohort and column period for the Retention explorer. Narrower than IntervalType, because hour and minute grains produce a matrix nobody can read.",
+ "enum": ["day", "week", "month"],
+ "type": "string"
+ },
+ "MarketingAnalyticsRetentionQuery": {
+ "additionalProperties": false,
+ "description": "The omitted fields are ones this runner ignores, so leaving them settable would let a caller ask for something that does nothing. `interval` goes because `retentionInterval` shadows it, and `conversionGoal` because this table counts return visits rather than conversions.",
+ "properties": {
+ "aggregation_group_type_index": {
+ "anyOf": [
+ {
+ "$ref": "#/definitions/integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Groups aggregation - not used in Web Analytics but required for type compatibility"
+ },
+ "breakdownBy": {
+ "$ref": "#/definitions/MarketingAnalyticsAttributionBreakdown",
+ "description": "Cohort dimension, read off each person's first session. Defaults to channel."
+ },
+ "breakdownLimit": {
+ "$ref": "#/definitions/integer",
+ "description": "Breakdown values kept before the rest roll into 'Other'. Defaults to 20."
+ },
+ "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"
+ },
+ "excludeDirectTraffic": {
+ "description": "Drop direct sessions when deciding first touch, mirroring the attribution explorer.",
+ "type": "boolean"
+ },
+ "excludeUnattributed": {
+ "description": "Drop persons whose first session names nothing for the current breakdown.",
+ "type": "boolean"
+ },
+ "filterTestAccounts": {
+ "type": "boolean"
+ },
+ "includeRevenue": {
+ "deprecated": "ignored, always treated as disabled",
+ "type": "boolean"
+ },
+ "kind": {
+ "const": "MarketingAnalyticsRetentionQuery",
+ "type": "string"
+ },
+ "modifiers": {
+ "$ref": "#/definitions/HogQLQueryModifiers",
+ "description": "Modifiers used when performing the query"
+ },
+ "newUserLookbackDays": {
+ "$ref": "#/definitions/integer",
+ "description": "How far back to look for a prior session. Defaults to 90, clamped to 365."
+ },
+ "onlyNewUsers": {
+ "description": "Only count persons with no session before the range, so a channel's cohorts are not inflated by users it acquired long ago. Defaults to true.",
+ "type": "boolean"
+ },
+ "properties": {
+ "$ref": "#/definitions/WebAnalyticsPropertyFilters"
+ },
+ "response": {
+ "$ref": "#/definitions/MarketingAnalyticsRetentionQueryResponse"
+ },
+ "retentionInterval": {
+ "$ref": "#/definitions/MarketingAnalyticsRetentionInterval",
+ "description": "Period for both the cohort rows and the return columns. Defaults to week."
+ },
+ "tags": {
+ "$ref": "#/definitions/QueryLogTags"
+ },
+ "totalIntervals": {
+ "$ref": "#/definitions/integer",
+ "description": "Return columns, counting period 0. Defaults to 8, clamped to 40."
+ },
+ "useSessionsTable": {
+ "deprecated": "ignored, always treated as enabled *",
+ "type": "boolean"
+ },
+ "version": {
+ "description": "version of the node, used for schema migrations",
+ "type": "number"
+ }
+ },
+ "required": ["kind", "properties"],
+ "type": "object"
+ },
+ "MarketingAnalyticsRetentionQueryResponse": {
+ "additionalProperties": false,
+ "properties": {
+ "error": {
+ "description": "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise.",
+ "type": "string"
+ },
+ "hogql": {
+ "description": "Generated HogQL query.",
+ "type": "string"
+ },
+ "interval": {
+ "$ref": "#/definitions/MarketingAnalyticsRetentionInterval"
+ },
+ "intervalCount": {
+ "$ref": "#/definitions/integer",
+ "description": "Column count. Every row's values array has this length."
+ },
+ "labels": {
+ "description": "Column headers, e.g. ['Week 0', 'Week 1', ...].",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "modifiers": {
+ "$ref": "#/definitions/HogQLQueryModifiers",
+ "description": "Modifiers used when performing the query"
+ },
+ "otherBreakdownCount": {
+ "$ref": "#/definitions/integer",
+ "description": "How many breakdown values were folded into 'Other', so the table can say so."
+ },
+ "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/MarketingAnalyticsRetentionRow"
+ },
+ "type": "array"
+ },
+ "timings": {
+ "description": "Measured timings for different parts of the query generation process",
+ "items": {
+ "$ref": "#/definitions/QueryTiming"
+ },
+ "type": "array"
+ },
+ "totalCohortSize": {
+ "$ref": "#/definitions/integer",
+ "description": "Distinct persons acquired across every cohort and breakdown value."
+ },
+ "truncatedCohorts": {
+ "$ref": "#/definitions/integer",
+ "description": "Older cohorts dropped to bound the matrix. Non-zero means the table covers less than the date range the filter bar shows, so the table has to say so."
+ },
+ "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": [
+ "interval",
+ "intervalCount",
+ "labels",
+ "otherBreakdownCount",
+ "results",
+ "totalCohortSize",
+ "truncatedCohorts"
+ ],
+ "type": "object"
+ },
+ "MarketingAnalyticsRetentionRow": {
+ "additionalProperties": false,
+ "properties": {
+ "breakdownValue": {
+ "type": "string"
+ },
+ "cohortDate": {
+ "description": "Start of the cohort's period, in the team's timezone.",
+ "format": "date-time",
+ "type": "string"
+ },
+ "cohortIndex": {
+ "$ref": "#/definitions/integer",
+ "description": "0-based position of this cohort from the range start."
+ },
+ "cohortSize": {
+ "$ref": "#/definitions/integer",
+ "description": "Persons acquired in this period under this breakdown value. The denominator for every cell."
+ },
+ "values": {
+ "description": "One per column, index = periods since the cohort started. Always intervalCount long.",
+ "items": {
+ "$ref": "#/definitions/MarketingAnalyticsRetentionCell"
+ },
+ "type": "array"
+ }
+ },
+ "required": ["breakdownValue", "cohortDate", "cohortIndex", "cohortSize", "values"],
+ "type": "object"
+ },
"MarketingAnalyticsSchemaField": {
"additionalProperties": false,
"properties": {
@@ -37509,6 +37888,7 @@
"MarketingAnalyticsAggregatedQuery",
"MarketingAnalyticsAttributionQuery",
"MarketingAnalyticsAttributionPathsQuery",
+ "MarketingAnalyticsRetentionQuery",
"NonIntegratedConversionsTableQuery",
"ExperimentMetric",
"ExperimentQuery",
@@ -42435,6 +42815,105 @@
],
"type": "object"
},
+ {
+ "additionalProperties": false,
+ "properties": {
+ "error": {
+ "description": "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise.",
+ "type": "string"
+ },
+ "hogql": {
+ "description": "Generated HogQL query.",
+ "type": "string"
+ },
+ "interval": {
+ "$ref": "#/definitions/MarketingAnalyticsRetentionInterval"
+ },
+ "intervalCount": {
+ "$ref": "#/definitions/integer",
+ "description": "Column count. Every row's values array has this length."
+ },
+ "labels": {
+ "description": "Column headers, e.g. ['Week 0', 'Week 1', ...].",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "modifiers": {
+ "$ref": "#/definitions/HogQLQueryModifiers",
+ "description": "Modifiers used when performing the query"
+ },
+ "otherBreakdownCount": {
+ "$ref": "#/definitions/integer",
+ "description": "How many breakdown values were folded into 'Other', so the table can say so."
+ },
+ "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/MarketingAnalyticsRetentionRow"
+ },
+ "type": "array"
+ },
+ "timings": {
+ "description": "Measured timings for different parts of the query generation process",
+ "items": {
+ "$ref": "#/definitions/QueryTiming"
+ },
+ "type": "array"
+ },
+ "totalCohortSize": {
+ "$ref": "#/definitions/integer",
+ "description": "Distinct persons acquired across every cohort and breakdown value."
+ },
+ "truncatedCohorts": {
+ "$ref": "#/definitions/integer",
+ "description": "Older cohorts dropped to bound the matrix. Non-zero means the table covers less than the date range the filter bar shows, so the table has to say so."
+ },
+ "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": [
+ "interval",
+ "intervalCount",
+ "labels",
+ "otherBreakdownCount",
+ "results",
+ "totalCohortSize",
+ "truncatedCohorts"
+ ],
+ "type": "object"
+ },
{
"additionalProperties": false,
"properties": {
@@ -47989,6 +48468,9 @@
{
"$ref": "#/definitions/MarketingAnalyticsAttributionPathsQuery"
},
+ {
+ "$ref": "#/definitions/MarketingAnalyticsRetentionQuery"
+ },
{
"$ref": "#/definitions/NonIntegratedConversionsTableQuery"
},
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 9001c3d623db..4fd112be8b60 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -157,6 +157,7 @@ export enum NodeKind {
MarketingAnalyticsAggregatedQuery = 'MarketingAnalyticsAggregatedQuery',
MarketingAnalyticsAttributionQuery = 'MarketingAnalyticsAttributionQuery',
MarketingAnalyticsAttributionPathsQuery = 'MarketingAnalyticsAttributionPathsQuery',
+ MarketingAnalyticsRetentionQuery = 'MarketingAnalyticsRetentionQuery',
NonIntegratedConversionsTableQuery = 'NonIntegratedConversionsTableQuery',
// Experiment queries
@@ -238,6 +239,7 @@ export type AnyDataNode =
| MarketingAnalyticsAggregatedQuery
| MarketingAnalyticsAttributionQuery
| MarketingAnalyticsAttributionPathsQuery
+ | MarketingAnalyticsRetentionQuery
| NonIntegratedConversionsTableQuery
| WebOverviewQuery
| WebStatsTableQuery
@@ -352,6 +354,7 @@ export type QuerySchema =
| MarketingAnalyticsAggregatedQuery
| MarketingAnalyticsAttributionQuery
| MarketingAnalyticsAttributionPathsQuery
+ | MarketingAnalyticsRetentionQuery
| NonIntegratedConversionsTableQuery
// Interface nodes
@@ -7205,7 +7208,8 @@ export interface MarketingAnalyticsAggregatedQuery extends Omit<
}
/**
- * Row dimension for the Attribution table. String values match MarketingAnalyticsDrillDownLevel for the
+ * Dimension a session is sliced by, shared by the Attribution table and the Retention explorer. 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.
@@ -7382,6 +7386,94 @@ export interface MarketingAnalyticsAttributionPathsQueryResponse extends Analyti
export type CachedMarketingAnalyticsAttributionPathsQueryResponse =
CachedQueryResponse<MarketingAnalyticsAttributionPathsQueryResponse>
+/**
+ * Cohort and column period for the Retention explorer. Narrower than IntervalType, because hour and
+ * minute grains produce a matrix nobody can read.
+ */
+export enum MarketingAnalyticsRetentionInterval {
+ Day = 'day',
+ Week = 'week',
+ Month = 'month',
+}
+
+/**
+ * The omitted fields are ones this runner ignores, so leaving them settable would let a caller ask for
+ * something that does nothing. `interval` goes because `retentionInterval` shadows it, and
+ * `conversionGoal` because this table counts return visits rather than conversions.
+ */
+export interface MarketingAnalyticsRetentionQuery extends Omit<
+ WebAnalyticsQueryBase<MarketingAnalyticsRetentionQueryResponse>,
+ 'orderBy' | 'compareFilter' | 'interval' | 'conversionGoal' | 'doPathCleaning' | 'sampling' | 'samplingFactor'
+> {
+ kind: NodeKind.MarketingAnalyticsRetentionQuery
+ /** Cohort dimension, read off each person's first session. Defaults to channel. */
+ breakdownBy?: MarketingAnalyticsAttributionBreakdown
+ /** Period for both the cohort rows and the return columns. Defaults to week. */
+ retentionInterval?: MarketingAnalyticsRetentionInterval
+ /** Return columns, counting period 0. Defaults to 8, clamped to 40. */
+ totalIntervals?: integer
+ /** Drop direct sessions when deciding first touch, mirroring the attribution explorer. */
+ excludeDirectTraffic?: boolean
+ /** Drop persons whose first session names nothing for the current breakdown. */
+ excludeUnattributed?: boolean
+ /**
+ * Only count persons with no session before the range, so a channel's cohorts are not inflated by
+ * users it acquired long ago. Defaults to true.
+ */
+ onlyNewUsers?: boolean
+ /** How far back to look for a prior session. Defaults to 90, clamped to 365. */
+ newUserLookbackDays?: integer
+ /** Breakdown values kept before the rest roll into 'Other'. Defaults to 20. */
+ breakdownLimit?: integer
+}
+
+/** One cohort's activity in one period since acquisition. */
+export interface MarketingAnalyticsRetentionCell {
+ /** Distinct persons from this cohort active in this period. */
+ count: integer
+ /** count / cohortSize. Null when the cohort is empty. */
+ rate: number | null
+ /**
+ * False when this period has not fully elapsed within the queried range, so a low cell reads as
+ * unfinished instead of as churn.
+ */
+ complete: boolean
+}
+
+export interface MarketingAnalyticsRetentionRow {
+ breakdownValue: string
+ /** Start of the cohort's period, in the team's timezone. @format date-time */
+ cohortDate: string
+ /** 0-based position of this cohort from the range start. */
+ cohortIndex: integer
+ /** Persons acquired in this period under this breakdown value. The denominator for every cell. */
+ cohortSize: integer
+ /** One per column, index = periods since the cohort started. Always intervalCount long. */
+ values: MarketingAnalyticsRetentionCell[]
+}
+
+export interface MarketingAnalyticsRetentionQueryResponse extends AnalyticsQueryResponseBase {
+ results: MarketingAnalyticsRetentionRow[]
+ /** Column count. Every row's values array has this length. */
+ intervalCount: integer
+ interval: MarketingAnalyticsRetentionInterval
+ /** Column headers, e.g. ['Week 0', 'Week 1', ...]. */
+ labels: string[]
+ /** How many breakdown values were folded into 'Other', so the table can say so. */
+ otherBreakdownCount: integer
+ /**
+ * Older cohorts dropped to bound the matrix. Non-zero means the table covers less than the date
+ * range the filter bar shows, so the table has to say so.
+ */
+ truncatedCohorts: integer
+ /** Distinct persons acquired across every cohort and breakdown value. */
+ totalCohortSize: integer
+ hogql?: string
+}
+
+export type CachedMarketingAnalyticsRetentionQueryResponse =
+ CachedQueryResponse<MarketingAnalyticsRetentionQueryResponse>
+
/** Columns for non-integrated conversions table */
export enum NonIntegratedConversionsColumnsSchemaNames {
Source = 'Source',
diff --git a/frontend/src/scenes/saved-insights/insightTypesMetadata.tsx b/frontend/src/scenes/saved-insights/insightTypesMetadata.tsx
index 633c43d092d9..c6ca67b533d4 100644
--- a/frontend/src/scenes/saved-insights/insightTypesMetadata.tsx
+++ b/frontend/src/scenes/saved-insights/insightTypesMetadata.tsx
@@ -558,6 +558,11 @@ export const QUERY_TYPES_METADATA: Record<NodeKind, InsightTypeMetadata> = {
icon: IconHogQL,
inMenu: false,
},
+ [NodeKind.MarketingAnalyticsRetentionQuery]: {
+ name: 'Marketing Analytics Retention',
+ icon: IconHogQL,
+ inMenu: false,
+ },
[NodeKind.NonIntegratedConversionsTableQuery]: {
name: 'Non-Integrated Conversions Table',
icon: IconHogQL,
diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.py
index 56cad6c7b5fc..bb16ef09faa6 100644
--- a/posthog/clickhouse/query_tagging.py
+++ b/posthog/clickhouse/query_tagging.py
@@ -277,6 +277,7 @@ def kind_fallback_tags(kind: NodeKind) -> FallbackTags | None:
| NodeKind.MARKETING_ANALYTICS_AGGREGATED_QUERY
| NodeKind.MARKETING_ANALYTICS_ATTRIBUTION_QUERY
| NodeKind.MARKETING_ANALYTICS_ATTRIBUTION_PATHS_QUERY
+ | NodeKind.MARKETING_ANALYTICS_RETENTION_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 8df1e64a630f..5b7048e49db9 100644
--- a/posthog/hogql_queries/query_runner.py
+++ b/posthog/hogql_queries/query_runner.py
@@ -1421,6 +1421,20 @@ def get_query_runner(
user=user,
)
+ if kind == NodeKind.MARKETING_ANALYTICS_RETENTION_QUERY:
+ from products.marketing_analytics.backend.hogql_queries.marketing_retention_query_runner import (
+ MarketingAnalyticsRetentionQueryRunner,
+ )
+
+ return MarketingAnalyticsRetentionQueryRunner(
+ query=query,
+ team=team,
+ timings=timings,
+ modifiers=modifiers,
+ limit_context=limit_context,
+ user=user,
+ )
+
if kind == NodeKind.NON_INTEGRATED_CONVERSIONS_TABLE_QUERY:
from products.marketing_analytics.backend.hogql_queries.non_integrated_conversions_table_query_runner import (
NonIntegratedConversionsTableQueryRunner,
diff --git a/posthog/schema.py b/posthog/schema.py
index eca5ff557c37..f5feff685161 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -166,6 +166,7 @@ from posthog.schema_enums import (
MarketingAnalyticsConstants as MarketingAnalyticsConstants,
MarketingAnalyticsDrillDownLevel as MarketingAnalyticsDrillDownLevel,
MarketingAnalyticsOrderByEnum as MarketingAnalyticsOrderByEnum,
+ MarketingAnalyticsRetentionInterval as MarketingAnalyticsRetentionInterval,
MarketingAnalyticsSchemaFieldTypes as MarketingAnalyticsSchemaFieldTypes,
MatchedOn as MatchedOn,
MatchField as MatchField,
@@ -2487,7 +2488,7 @@ class QueryResponseAlternative7(BaseModel):
stdout: str | None = None
-class QueryResponseAlternative80(BaseModel):
+class QueryResponseAlternative81(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -5906,6 +5907,38 @@ class MarketingAnalyticsItem(BaseModel):
value: float | str | None = None
+class MarketingAnalyticsRetentionCell(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ complete: bool = Field(
+ ...,
+ description=(
+ "False when this period has not fully elapsed within the queried range, so"
+ " a low cell reads as unfinished instead of as churn."
+ ),
+ )
+ count: int = Field(..., description="Distinct persons from this cohort active in this period.")
+ rate: float | None = Field(..., description="count / cohortSize. Null when the cohort is empty.")
+
+
+class MarketingAnalyticsRetentionRow(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ breakdownValue: str
+ cohortDate: AwareDatetime = Field(..., description="Start of the cohort's period, in the team's timezone.")
+ cohortIndex: int = Field(..., description="0-based position of this cohort from the range start.")
+ cohortSize: int = Field(
+ ...,
+ description=("Persons acquired in this period under this breakdown value. The denominator for every cell."),
+ )
+ values: list[MarketingAnalyticsRetentionCell] = Field(
+ ...,
+ description=("One per column, index = periods since the cohort started. Always intervalCount long."),
+ )
+
+
class MarketingAnalyticsSchemaField(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -6470,7 +6503,7 @@ class QueryResponseAlternative31(BaseModel):
status: ExternalQueryStatus
-class QueryResponseAlternative87(BaseModel):
+class QueryResponseAlternative88(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -13091,6 +13124,83 @@ class CachedMarketingAnalyticsAttributionQueryResponse(BaseModel):
)
+class CachedMarketingAnalyticsRetentionQueryResponse(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ 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."
+ ),
+ )
+ hogql: str | None = Field(default=None, description="Generated HogQL query.")
+ interval: MarketingAnalyticsRetentionInterval
+ intervalCount: int = Field(..., description="Column count. Every row's values array has this length.")
+ is_cached: bool
+ labels: list[str] = Field(..., description="Column headers, e.g. ['Week 0', 'Week 1', ...].")
+ last_refresh: AwareDatetime
+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
+ next_allowed_client_refresh: AwareDatetime
+ otherBreakdownCount: int = Field(
+ ...,
+ description=("How many breakdown values were folded into 'Other', so the table can say so."),
+ )
+ 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[MarketingAnalyticsRetentionRow]
+ timezone: str
+ timings: list[QueryTiming] | None = Field(
+ default=None,
+ description=("Measured timings for different parts of the query generation process"),
+ )
+ totalCohortSize: int = Field(
+ ...,
+ description=("Distinct persons acquired across every cohort and breakdown value."),
+ )
+ truncatedCohorts: int = Field(
+ ...,
+ description=(
+ "Older cohorts dropped to bound the matrix. Non-zero means the table covers"
+ " less than the date range the filter bar shows, so the table has to"
+ " say so."
+ ),
+ )
+ 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",
@@ -18479,6 +18589,72 @@ class MarketingAnalyticsAttributionQueryResponse(BaseModel):
)
+class MarketingAnalyticsRetentionQueryResponse(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ error: str | None = Field(
+ default=None,
+ description=(
+ "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise."
+ ),
+ )
+ hogql: str | None = Field(default=None, description="Generated HogQL query.")
+ interval: MarketingAnalyticsRetentionInterval
+ intervalCount: int = Field(..., description="Column count. Every row's values array has this length.")
+ labels: list[str] = Field(..., description="Column headers, e.g. ['Week 0', 'Week 1', ...].")
+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
+ otherBreakdownCount: int = Field(
+ ...,
+ description=("How many breakdown values were folded into 'Other', so the table can say so."),
+ )
+ 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[MarketingAnalyticsRetentionRow]
+ timings: list[QueryTiming] | None = Field(
+ default=None,
+ description=("Measured timings for different parts of the query generation process"),
+ )
+ totalCohortSize: int = Field(
+ ...,
+ description=("Distinct persons acquired across every cohort and breakdown value."),
+ )
+ truncatedCohorts: int = Field(
+ ...,
+ description=(
+ "Older cohorts dropped to bound the matrix. Non-zero means the table covers"
+ " less than the date range the filter bar shows, so the table has to"
+ " say so."
+ ),
+ )
+ 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 MarketingAnalyticsTableQueryResponse(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -20204,6 +20380,72 @@ class QueryResponseAlternative36(BaseModel):
class QueryResponseAlternative37(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ error: str | None = Field(
+ default=None,
+ description=(
+ "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise."
+ ),
+ )
+ hogql: str | None = Field(default=None, description="Generated HogQL query.")
+ interval: MarketingAnalyticsRetentionInterval
+ intervalCount: int = Field(..., description="Column count. Every row's values array has this length.")
+ labels: list[str] = Field(..., description="Column headers, e.g. ['Week 0', 'Week 1', ...].")
+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
+ otherBreakdownCount: int = Field(
+ ...,
+ description=("How many breakdown values were folded into 'Other', so the table can say so."),
+ )
+ 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[MarketingAnalyticsRetentionRow]
+ timings: list[QueryTiming] | None = Field(
+ default=None,
+ description=("Measured timings for different parts of the query generation process"),
+ )
+ totalCohortSize: int = Field(
+ ...,
+ description=("Distinct persons acquired across every cohort and breakdown value."),
+ )
+ truncatedCohorts: int = Field(
+ ...,
+ description=(
+ "Older cohorts dropped to bound the matrix. Non-zero means the table covers"
+ " less than the date range the filter bar shows, so the table has to"
+ " say so."
+ ),
+ )
+ 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 QueryResponseAlternative38(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20256,7 +20498,7 @@ class QueryResponseAlternative37(BaseModel):
)
-class QueryResponseAlternative38(BaseModel):
+class QueryResponseAlternative39(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20309,7 +20551,7 @@ class QueryResponseAlternative38(BaseModel):
)
-class QueryResponseAlternative39(BaseModel):
+class QueryResponseAlternative40(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20362,7 +20604,7 @@ class QueryResponseAlternative39(BaseModel):
)
-class QueryResponseAlternative40(BaseModel):
+class QueryResponseAlternative41(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20415,7 +20657,7 @@ class QueryResponseAlternative40(BaseModel):
)
-class QueryResponseAlternative41(BaseModel):
+class QueryResponseAlternative42(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20468,7 +20710,7 @@ class QueryResponseAlternative41(BaseModel):
)
-class QueryResponseAlternative42(BaseModel):
+class QueryResponseAlternative43(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20519,7 +20761,7 @@ class QueryResponseAlternative42(BaseModel):
)
-class QueryResponseAlternative43(BaseModel):
+class QueryResponseAlternative44(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20580,7 +20822,7 @@ class QueryResponseAlternative43(BaseModel):
)
-class QueryResponseAlternative44(BaseModel):
+class QueryResponseAlternative45(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20633,7 +20875,7 @@ class QueryResponseAlternative44(BaseModel):
)
-class QueryResponseAlternative45(BaseModel):
+class QueryResponseAlternative46(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20685,7 +20927,7 @@ class QueryResponseAlternative45(BaseModel):
)
-class QueryResponseAlternative46(BaseModel):
+class QueryResponseAlternative47(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20739,7 +20981,7 @@ class QueryResponseAlternative46(BaseModel):
)
-class QueryResponseAlternative47(BaseModel):
+class QueryResponseAlternative48(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20787,7 +21029,7 @@ class QueryResponseAlternative47(BaseModel):
)
-class QueryResponseAlternative48(BaseModel):
+class QueryResponseAlternative49(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20839,7 +21081,7 @@ class QueryResponseAlternative48(BaseModel):
)
-class QueryResponseAlternative49(BaseModel):
+class QueryResponseAlternative50(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20891,7 +21133,7 @@ class QueryResponseAlternative49(BaseModel):
)
-class QueryResponseAlternative50(BaseModel):
+class QueryResponseAlternative51(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20944,7 +21186,7 @@ class QueryResponseAlternative50(BaseModel):
)
-class QueryResponseAlternative51(BaseModel):
+class QueryResponseAlternative52(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20992,7 +21234,7 @@ class QueryResponseAlternative51(BaseModel):
)
-class QueryResponseAlternative52(BaseModel):
+class QueryResponseAlternative53(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21045,7 +21287,7 @@ class QueryResponseAlternative52(BaseModel):
)
-class QueryResponseAlternative53(BaseModel):
+class QueryResponseAlternative54(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21096,7 +21338,7 @@ class QueryResponseAlternative53(BaseModel):
)
-class QueryResponseAlternative57(BaseModel):
+class QueryResponseAlternative58(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21147,7 +21389,7 @@ class QueryResponseAlternative57(BaseModel):
)
-class QueryResponseAlternative59(BaseModel):
+class QueryResponseAlternative60(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21199,7 +21441,7 @@ class QueryResponseAlternative59(BaseModel):
)
-class QueryResponseAlternative60(BaseModel):
+class QueryResponseAlternative61(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21256,7 +21498,7 @@ class QueryResponseAlternative60(BaseModel):
)
-class QueryResponseAlternative61(BaseModel):
+class QueryResponseAlternative62(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21311,7 +21553,7 @@ class QueryResponseAlternative61(BaseModel):
)
-class QueryResponseAlternative62(BaseModel):
+class QueryResponseAlternative63(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21360,7 +21602,7 @@ class QueryResponseAlternative62(BaseModel):
)
-class QueryResponseAlternative63(BaseModel):
+class QueryResponseAlternative64(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21414,7 +21656,7 @@ class QueryResponseAlternative63(BaseModel):
)
-class QueryResponseAlternative64(BaseModel):
+class QueryResponseAlternative65(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21461,7 +21703,7 @@ class QueryResponseAlternative64(BaseModel):
)
-class QueryResponseAlternative65(BaseModel):
+class QueryResponseAlternative66(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21508,7 +21750,7 @@ class QueryResponseAlternative65(BaseModel):
)
-class QueryResponseAlternative66(BaseModel):
+class QueryResponseAlternative67(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21555,7 +21797,7 @@ class QueryResponseAlternative66(BaseModel):
)
-class QueryResponseAlternative67(BaseModel):
+class QueryResponseAlternative68(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21602,7 +21844,7 @@ class QueryResponseAlternative67(BaseModel):
)
-class QueryResponseAlternative69(BaseModel):
+class QueryResponseAlternative70(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21654,7 +21896,7 @@ class QueryResponseAlternative69(BaseModel):
)
-class QueryResponseAlternative71(BaseModel):
+class QueryResponseAlternative72(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21706,7 +21948,7 @@ class QueryResponseAlternative71(BaseModel):
)
-class QueryResponseAlternative72(BaseModel):
+class QueryResponseAlternative73(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21758,7 +22000,7 @@ class QueryResponseAlternative72(BaseModel):
)
-class QueryResponseAlternative73(BaseModel):
+class QueryResponseAlternative74(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21806,7 +22048,7 @@ class QueryResponseAlternative73(BaseModel):
)
-class QueryResponseAlternative74(BaseModel):
+class QueryResponseAlternative75(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21853,7 +22095,7 @@ class QueryResponseAlternative74(BaseModel):
)
-class QueryResponseAlternative75(BaseModel):
+class QueryResponseAlternative76(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21900,7 +22142,7 @@ class QueryResponseAlternative75(BaseModel):
)
-class QueryResponseAlternative76(BaseModel):
+class QueryResponseAlternative77(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21951,7 +22193,7 @@ class QueryResponseAlternative76(BaseModel):
)
-class QueryResponseAlternative77(BaseModel):
+class QueryResponseAlternative78(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22002,7 +22244,7 @@ class QueryResponseAlternative77(BaseModel):
)
-class QueryResponseAlternative78(BaseModel):
+class QueryResponseAlternative79(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22053,7 +22295,7 @@ class QueryResponseAlternative78(BaseModel):
)
-class QueryResponseAlternative79(BaseModel):
+class QueryResponseAlternative80(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22104,7 +22346,7 @@ class QueryResponseAlternative79(BaseModel):
)
-class QueryResponseAlternative81(BaseModel):
+class QueryResponseAlternative82(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22154,7 +22396,7 @@ class QueryResponseAlternative81(BaseModel):
)
-class QueryResponseAlternative82(BaseModel):
+class QueryResponseAlternative83(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22204,7 +22446,7 @@ class QueryResponseAlternative82(BaseModel):
)
-class QueryResponseAlternative83(BaseModel):
+class QueryResponseAlternative84(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22251,7 +22493,7 @@ class QueryResponseAlternative83(BaseModel):
)
-class QueryResponseAlternative84(BaseModel):
+class QueryResponseAlternative85(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22302,7 +22544,7 @@ class QueryResponseAlternative84(BaseModel):
)
-class QueryResponseAlternative88(BaseModel):
+class QueryResponseAlternative89(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22349,7 +22591,7 @@ class QueryResponseAlternative88(BaseModel):
)
-class QueryResponseAlternative89(BaseModel):
+class QueryResponseAlternative90(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22396,7 +22638,7 @@ class QueryResponseAlternative89(BaseModel):
)
-class QueryResponseAlternative90(BaseModel):
+class QueryResponseAlternative91(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22453,7 +22695,7 @@ class QueryResponseAlternative90(BaseModel):
)
-class QueryResponseAlternative91(BaseModel):
+class QueryResponseAlternative92(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22508,7 +22750,7 @@ class QueryResponseAlternative91(BaseModel):
)
-class QueryResponseAlternative92(BaseModel):
+class QueryResponseAlternative93(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22555,7 +22797,7 @@ class QueryResponseAlternative92(BaseModel):
)
-class QueryResponseAlternative93(BaseModel):
+class QueryResponseAlternative94(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22607,7 +22849,7 @@ class QueryResponseAlternative93(BaseModel):
)
-class QueryResponseAlternative94(BaseModel):
+class QueryResponseAlternative95(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22654,7 +22896,7 @@ class QueryResponseAlternative94(BaseModel):
)
-class QueryResponseAlternative95(BaseModel):
+class QueryResponseAlternative96(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22701,7 +22943,7 @@ class QueryResponseAlternative95(BaseModel):
)
-class QueryResponseAlternative96(BaseModel):
+class QueryResponseAlternative97(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22748,7 +22990,7 @@ class QueryResponseAlternative96(BaseModel):
)
-class QueryResponseAlternative97(BaseModel):
+class QueryResponseAlternative98(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22795,7 +23037,7 @@ class QueryResponseAlternative97(BaseModel):
)
-class QueryResponseAlternative98(BaseModel):
+class QueryResponseAlternative99(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22842,7 +23084,7 @@ class QueryResponseAlternative98(BaseModel):
)
-class QueryResponseAlternative99(BaseModel):
+class QueryResponseAlternative100(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22889,7 +23131,7 @@ class QueryResponseAlternative99(BaseModel):
)
-class QueryResponseAlternative100(BaseModel):
+class QueryResponseAlternative101(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22936,7 +23178,7 @@ class QueryResponseAlternative100(BaseModel):
)
-class QueryResponseAlternative101(BaseModel):
+class QueryResponseAlternative102(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22986,7 +23228,7 @@ class QueryResponseAlternative101(BaseModel):
)
-class QueryResponseAlternative102(BaseModel):
+class QueryResponseAlternative103(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -23033,7 +23275,7 @@ class QueryResponseAlternative102(BaseModel):
)
-class QueryResponseAlternative103(BaseModel):
+class QueryResponseAlternative104(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -23080,7 +23322,7 @@ class QueryResponseAlternative103(BaseModel):
)
-class QueryResponseAlternative104(BaseModel):
+class QueryResponseAlternative105(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -23127,7 +23369,7 @@ class QueryResponseAlternative104(BaseModel):
)
-class QueryResponseAlternative105(BaseModel):
+class QueryResponseAlternative106(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -23174,7 +23416,7 @@ class QueryResponseAlternative105(BaseModel):
)
-class QueryResponseAlternative106(BaseModel):
+class QueryResponseAlternative107(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -23221,7 +23463,7 @@ class QueryResponseAlternative106(BaseModel):
)
-class QueryResponseAlternative107(BaseModel):
+class QueryResponseAlternative108(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -23268,7 +23510,7 @@ class QueryResponseAlternative107(BaseModel):
)
-class QueryResponseAlternative108(BaseModel):
+class QueryResponseAlternative109(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -23315,7 +23557,7 @@ class QueryResponseAlternative108(BaseModel):
)
-class QueryResponseAlternative109(BaseModel):
+class QueryResponseAlternative110(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -23362,7 +23604,7 @@ class QueryResponseAlternative109(BaseModel):
)
-class QueryResponseAlternative110(BaseModel):
+class QueryResponseAlternative111(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -23409,7 +23651,7 @@ class QueryResponseAlternative110(BaseModel):
)
-class QueryResponseAlternative111(BaseModel):
+class QueryResponseAlternative112(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -26646,6 +26888,67 @@ class MarketingAnalyticsConfig(BaseModel):
sources_map: dict[str, SourceMap] | None = None
+class MarketingAnalyticsRetentionQuery(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"),
+ )
+ breakdownBy: MarketingAnalyticsAttributionBreakdown | None = Field(
+ default=None,
+ description=("Cohort dimension, read off each person's first session. Defaults to channel."),
+ )
+ breakdownLimit: int | None = Field(
+ default=None,
+ description=("Breakdown values kept before the rest roll into 'Other'. Defaults to 20."),
+ )
+ 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
+ excludeDirectTraffic: bool | None = Field(
+ default=None,
+ description=("Drop direct sessions when deciding first touch, mirroring the attribution explorer."),
+ )
+ excludeUnattributed: bool | None = Field(
+ default=None,
+ description=("Drop persons whose first session names nothing for the current breakdown."),
+ )
+ filterTestAccounts: bool | None = None
+ includeRevenue: bool | None = None
+ kind: Literal["MarketingAnalyticsRetentionQuery"] = "MarketingAnalyticsRetentionQuery"
+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
+ newUserLookbackDays: int | None = Field(
+ default=None,
+ description=("How far back to look for a prior session. Defaults to 90, clamped to 365."),
+ )
+ onlyNewUsers: bool | None = Field(
+ default=None,
+ description=(
+ "Only count persons with no session before the range, so a channel's"
+ " cohorts are not inflated by users it acquired long ago. Defaults to true."
+ ),
+ )
+ properties: list[EventPropertyFilter | PersonPropertyFilter | SessionPropertyFilter | CohortPropertyFilter]
+ response: MarketingAnalyticsRetentionQueryResponse | None = None
+ retentionInterval: MarketingAnalyticsRetentionInterval | None = Field(
+ default=None,
+ description=("Period for both the cohort rows and the return columns. Defaults to week."),
+ )
+ tags: QueryLogTags | None = None
+ totalIntervals: int | None = Field(
+ default=None,
+ description="Return columns, counting period 0. Defaults to 8, clamped to 40.",
+ )
+ 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",
@@ -28530,7 +28833,7 @@ class PathsV2Query(BaseModel):
version: float | None = Field(default=None, description="version of the node, used for schema migrations")
-class QueryResponseAlternative70(BaseModel):
+class QueryResponseAlternative71(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -29389,7 +29692,7 @@ class QueryResponseAlternative19(BaseModel):
)
-class QueryResponseAlternative55(BaseModel):
+class QueryResponseAlternative56(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -29409,7 +29712,7 @@ class QueryResponseAlternative55(BaseModel):
)
-class QueryResponseAlternative56(BaseModel):
+class QueryResponseAlternative57(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -29469,8 +29772,8 @@ class QueryResponseAlternative(
| QueryResponseAlternative35
| QueryResponseAlternative36
| QueryResponseAlternative37
- | Any
| QueryResponseAlternative38
+ | Any
| QueryResponseAlternative39
| QueryResponseAlternative40
| QueryResponseAlternative41
@@ -29486,10 +29789,10 @@ class QueryResponseAlternative(
| QueryResponseAlternative51
| QueryResponseAlternative52
| QueryResponseAlternative53
- | QueryResponseAlternative55
+ | QueryResponseAlternative54
| QueryResponseAlternative56
| QueryResponseAlternative57
- | QueryResponseAlternative59
+ | QueryResponseAlternative58
| QueryResponseAlternative60
| QueryResponseAlternative61
| QueryResponseAlternative62
@@ -29498,7 +29801,7 @@ class QueryResponseAlternative(
| QueryResponseAlternative65
| QueryResponseAlternative66
| QueryResponseAlternative67
- | QueryResponseAlternative69
+ | QueryResponseAlternative68
| QueryResponseAlternative70
| QueryResponseAlternative71
| QueryResponseAlternative72
@@ -29514,7 +29817,7 @@ class QueryResponseAlternative(
| QueryResponseAlternative82
| QueryResponseAlternative83
| QueryResponseAlternative84
- | QueryResponseAlternative87
+ | QueryResponseAlternative85
| QueryResponseAlternative88
| QueryResponseAlternative89
| QueryResponseAlternative90
@@ -29539,6 +29842,7 @@ class QueryResponseAlternative(
| QueryResponseAlternative109
| QueryResponseAlternative110
| QueryResponseAlternative111
+ | QueryResponseAlternative112
]
):
root: (
@@ -29579,8 +29883,8 @@ class QueryResponseAlternative(
| QueryResponseAlternative35
| QueryResponseAlternative36
| QueryResponseAlternative37
- | Any
| QueryResponseAlternative38
+ | Any
| QueryResponseAlternative39
| QueryResponseAlternative40
| QueryResponseAlternative41
@@ -29596,10 +29900,10 @@ class QueryResponseAlternative(
| QueryResponseAlternative51
| QueryResponseAlternative52
| QueryResponseAlternative53
- | QueryResponseAlternative55
+ | QueryResponseAlternative54
| QueryResponseAlternative56
| QueryResponseAlternative57
- | QueryResponseAlternative59
+ | QueryResponseAlternative58
| QueryResponseAlternative60
| QueryResponseAlternative61
| QueryResponseAlternative62
@@ -29608,7 +29912,7 @@ class QueryResponseAlternative(
| QueryResponseAlternative65
| QueryResponseAlternative66
| QueryResponseAlternative67
- | QueryResponseAlternative69
+ | QueryResponseAlternative68
| QueryResponseAlternative70
| QueryResponseAlternative71
| QueryResponseAlternative72
@@ -29624,7 +29928,7 @@ class QueryResponseAlternative(
| QueryResponseAlternative82
| QueryResponseAlternative83
| QueryResponseAlternative84
- | QueryResponseAlternative87
+ | QueryResponseAlternative85
| QueryResponseAlternative88
| QueryResponseAlternative89
| QueryResponseAlternative90
@@ -29649,6 +29953,7 @@ class QueryResponseAlternative(
| QueryResponseAlternative109
| QueryResponseAlternative110
| QueryResponseAlternative111
+ | QueryResponseAlternative112
)
@@ -30566,6 +30871,7 @@ class HogQLAutocomplete(BaseModel):
| MarketingAnalyticsAggregatedQuery
| MarketingAnalyticsAttributionQuery
| MarketingAnalyticsAttributionPathsQuery
+ | MarketingAnalyticsRetentionQuery
| NonIntegratedConversionsTableQuery
| WebOverviewQuery
| WebStatsTableQuery
@@ -30690,6 +30996,7 @@ class HogQLMetadata(BaseModel):
| MarketingAnalyticsAggregatedQuery
| MarketingAnalyticsAttributionQuery
| MarketingAnalyticsAttributionPathsQuery
+ | MarketingAnalyticsRetentionQuery
| NonIntegratedConversionsTableQuery
| WebOverviewQuery
| WebStatsTableQuery
@@ -30838,6 +31145,7 @@ class MaxInsightContext(BaseModel):
| MarketingAnalyticsAggregatedQuery
| MarketingAnalyticsAttributionQuery
| MarketingAnalyticsAttributionPathsQuery
+ | MarketingAnalyticsRetentionQuery
| NonIntegratedConversionsTableQuery
| DataVisualizationNode
| DataTableNode
@@ -30978,6 +31286,7 @@ class QueryRequest(BaseModel):
| MarketingAnalyticsAggregatedQuery
| MarketingAnalyticsAttributionQuery
| MarketingAnalyticsAttributionPathsQuery
+ | MarketingAnalyticsRetentionQuery
| NonIntegratedConversionsTableQuery
| DataVisualizationNode
| DataTableNode
@@ -31110,6 +31419,7 @@ class QuerySchemaRoot(
| MarketingAnalyticsAggregatedQuery
| MarketingAnalyticsAttributionQuery
| MarketingAnalyticsAttributionPathsQuery
+ | MarketingAnalyticsRetentionQuery
| NonIntegratedConversionsTableQuery
| DataVisualizationNode
| DataTableNode
@@ -31212,6 +31522,7 @@ class QuerySchemaRoot(
| MarketingAnalyticsAggregatedQuery
| MarketingAnalyticsAttributionQuery
| MarketingAnalyticsAttributionPathsQuery
+ | MarketingAnalyticsRetentionQuery
| NonIntegratedConversionsTableQuery
| DataVisualizationNode
| DataTableNode
@@ -31319,6 +31630,7 @@ class QueryUpgradeRequest(BaseModel):
| MarketingAnalyticsAggregatedQuery
| MarketingAnalyticsAttributionQuery
| MarketingAnalyticsAttributionPathsQuery
+ | MarketingAnalyticsRetentionQuery
| NonIntegratedConversionsTableQuery
| DataVisualizationNode
| DataTableNode
@@ -31426,6 +31738,7 @@ class QueryUpgradeResponse(BaseModel):
| MarketingAnalyticsAggregatedQuery
| MarketingAnalyticsAttributionQuery
| MarketingAnalyticsAttributionPathsQuery
+ | MarketingAnalyticsRetentionQuery
| NonIntegratedConversionsTableQuery
| DataVisualizationNode
| DataTableNode
@@ -31719,6 +32032,7 @@ class VisualizationArtifactContent(BaseModel):
| MarketingAnalyticsAggregatedQuery
| MarketingAnalyticsAttributionQuery
| MarketingAnalyticsAttributionPathsQuery
+ | MarketingAnalyticsRetentionQuery
| NonIntegratedConversionsTableQuery
| DataVisualizationNode
| DataTableNode
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index 9da3a44231e4..448950155fd1 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -3166,6 +3166,12 @@ class MarketingAnalyticsOrderByEnum(StrEnum):
DESC = "DESC"
+class MarketingAnalyticsRetentionInterval(StrEnum):
+ DAY = "day"
+ WEEK = "week"
+ MONTH = "month"
+
+
class MarketingAnalyticsSchemaFieldTypes(StrEnum):
STRING = "string"
INTEGER = "integer"
@@ -3378,6 +3384,7 @@ class NodeKind(StrEnum):
MARKETING_ANALYTICS_AGGREGATED_QUERY = "MarketingAnalyticsAggregatedQuery"
MARKETING_ANALYTICS_ATTRIBUTION_QUERY = "MarketingAnalyticsAttributionQuery"
MARKETING_ANALYTICS_ATTRIBUTION_PATHS_QUERY = "MarketingAnalyticsAttributionPathsQuery"
+ MARKETING_ANALYTICS_RETENTION_QUERY = "MarketingAnalyticsRetentionQuery"
NON_INTEGRATED_CONVERSIONS_TABLE_QUERY = "NonIntegratedConversionsTableQuery"
EXPERIMENT_METRIC = "ExperimentMetric"
EXPERIMENT_QUERY = "ExperimentQuery"
diff --git a/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_marketing_retention_query_runner.ambr b/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_marketing_retention_query_runner.ambr
new file mode 100644
index 000000000000..ea9fd8caffa7
--- /dev/null
+++ b/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_marketing_retention_query_runner.ambr
@@ -0,0 +1,126 @@
+# serializer version: 1
+# name: TestMarketingAnalyticsRetentionQueryRunner.test_query_shape
+ '''
+ WITH
+ acquisition AS MATERIALIZED (
+ SELECT
+ events.person_id AS actor_id,
+ min(events.session.$start_timestamp) AS cohort_at,
+ argMin(if(in(lower(if(notEmpty(ifNull(events.session.$entry_utm_source, '')), events.session.$entry_utm_source, 'organic')), ['microsoft', 'msads', 'bing_video']), 'bing', if(in(lower(if(notEmpty(ifNull(events.session.$entry_utm_source, '')), events.session.$entry_utm_source, 'organic')), ['facebook', 'instagram', 'messenger', 'fb', 'whatsapp', 'audience_network', 'facebook_marketplace', 'threads']), 'meta', if(in(lower(if(notEmpty(ifNull(events.session.$entry_utm_source, '')), events.session.$entry_utm_source, 'organic')), ['li']), 'linkedin', if(in(lower(if(notEmpty(ifNull(events.session.$entry_utm_source, '')), events.session.$entry_utm_source, 'organic')), ['adwords', 'youtube', 'display', 'gmail', 'google_maps', 'google_play', 'google_discover', 'admob', 'waze']), 'google', if(notEmpty(ifNull(events.session.$entry_utm_source, '')), events.session.$entry_utm_source, 'organic'))))), events.session.$start_timestamp) AS breakdown_value
+ FROM
+ events
+ WHERE
+ and(and(equals(events.event, '$pageview'), notEmpty(events.$session_id), greater(toUnixTimestamp(events.session.$start_timestamp), 0)), greaterOrEquals(events.timestamp, toDateTime('2023-01-01 00:00:00')), lessOrEquals(events.timestamp, toDateTime('2023-01-29 23:59:59')), greaterOrEquals(events.session.$start_timestamp, toDateTime('2023-01-01 00:00:00')), lessOrEquals(events.session.$start_timestamp, toDateTime('2023-01-29 23:59:59')), globalNotIn(events.person_id, (
+ SELECT
+ DISTINCT events.person_id
+ FROM
+ events
+ WHERE
+ and(equals(events.event, '$pageview'), notEmpty(events.$session_id), greaterOrEquals(events.timestamp, minus(toDateTime('2023-01-01 00:00:00'), toIntervalDay(90))), less(events.timestamp, toDateTime('2023-01-01 00:00:00'))))))
+ GROUP BY
+ actor_id),
+ activity AS (
+ SELECT
+ events.person_id AS actor_id,
+ dateDiff('week', toStartOfWeek(toDateTime('2023-01-01 00:00:00'), 0), toStartOfWeek(events.timestamp, 0)) AS activity_index
+ FROM
+ events
+ WHERE
+ and(equals(events.event, '$pageview'), greaterOrEquals(events.timestamp, toDateTime('2023-01-01 00:00:00')), lessOrEquals(events.timestamp, toDateTime('2023-01-29 23:59:59')), globalIn(events.person_id, (
+ SELECT
+ actor_id
+ FROM
+ acquisition)))
+ GROUP BY
+ actor_id,
+ activity_index),
+ cohort_sizes AS MATERIALIZED (
+ SELECT
+ breakdown_value,
+ dateDiff('week', toStartOfWeek(toDateTime('2023-01-01 00:00:00'), 0), toStartOfWeek(cohort_at, 0)) AS cohort_index,
+ count(actor_id) AS cohort_size
+ FROM
+ acquisition
+ GROUP BY
+ breakdown_value,
+ cohort_index),
+ matrix AS (
+ SELECT
+ acquisition.breakdown_value,
+ dateDiff('week', toStartOfWeek(toDateTime('2023-01-01 00:00:00'), 0), toStartOfWeek(acquisition.cohort_at, 0)) AS cohort_index,
+ minus(activity.activity_index, dateDiff('week', toStartOfWeek(toDateTime('2023-01-01 00:00:00'), 0), toStartOfWeek(acquisition.cohort_at, 0))) AS intervals_from_base,
+ count(DISTINCT acquisition.actor_id) AS count
+ FROM
+ acquisition
+ INNER JOIN activity ON equals(activity.actor_id, acquisition.actor_id)
+ GROUP BY
+ acquisition.breakdown_value,
+ cohort_index,
+ intervals_from_base
+ HAVING
+ and(greaterOrEquals(intervals_from_base, 0), less(intervals_from_base, 4))),
+ folded_sizes AS (
+ SELECT
+ if(globalIn(breakdown_value, (
+ SELECT
+ breakdown_value
+ FROM
+ cohort_sizes
+ GROUP BY
+ breakdown_value
+ ORDER BY
+ sum(cohort_size) DESC,
+ breakdown_value ASC
+ LIMIT 20)), breakdown_value, '$$_posthog_breakdown_other_$$') AS breakdown_value,
+ cohort_index,
+ sum(cohort_size) AS cohort_size
+ FROM
+ cohort_sizes
+ GROUP BY
+ breakdown_value,
+ cohort_index),
+ folded_matrix AS (
+ SELECT
+ if(globalIn(breakdown_value, (
+ SELECT
+ breakdown_value
+ FROM
+ cohort_sizes
+ GROUP BY
+ breakdown_value
+ ORDER BY
+ sum(cohort_size) DESC,
+ breakdown_value ASC
+ LIMIT 20)), breakdown_value, '$$_posthog_breakdown_other_$$') AS breakdown_value,
+ cohort_index,
+ intervals_from_base,
+ sum(count) AS count
+ FROM
+ matrix
+ GROUP BY
+ breakdown_value,
+ cohort_index,
+ intervals_from_base),
+ summary AS (
+ SELECT
+ uniqExact(breakdown_value) AS distinct_breakdowns
+ FROM
+ cohort_sizes)
+ SELECT
+ folded_sizes.breakdown_value AS breakdown_value,
+ folded_sizes.cohort_index AS cohort_index,
+ folded_sizes.cohort_size AS cohort_size,
+ folded_matrix.intervals_from_base AS intervals_from_base,
+ folded_matrix.count AS count,
+ summary.distinct_breakdowns AS distinct_breakdowns
+ FROM
+ folded_sizes
+ LEFT JOIN folded_matrix ON and(equals(folded_matrix.breakdown_value, folded_sizes.breakdown_value), equals(folded_matrix.cohort_index, folded_sizes.cohort_index))
+ CROSS JOIN summary
+ ORDER BY
+ breakdown_value ASC,
+ cohort_index ASC,
+ intervals_from_base ASC
+ LIMIT 421
+ '''
+# ---
diff --git a/products/marketing_analytics/backend/hogql_queries/attribution_base.py b/products/marketing_analytics/backend/hogql_queries/attribution_base.py
index 61709c83fdd9..829840a5ea6e 100644
--- a/products/marketing_analytics/backend/hogql_queries/attribution_base.py
+++ b/products/marketing_analytics/backend/hogql_queries/attribution_base.py
@@ -9,7 +9,15 @@ drifting on what a journey is.
from functools import cached_property
from typing import Generic
-from posthog.schema import BaseMathType, MarketingAnalyticsAttributionPathsQuery, MarketingAnalyticsAttributionQuery
+from posthog.schema import (
+ BaseMathType,
+ ConversionGoalFilter1,
+ ConversionGoalFilter2,
+ ConversionGoalFilter3,
+ MarketingAnalyticsAttributionPathsQuery,
+ MarketingAnalyticsAttributionQuery,
+ PropertyMathType,
+)
from posthog.hogql import ast
@@ -17,9 +25,12 @@ from posthog.hogql_queries.utils.query_date_range import QueryDateRange
from posthog.models.team.team_marketing_analytics_config import MAX_ATTRIBUTION_WINDOW_DAYS, MIN_ATTRIBUTION_WINDOW_DAYS
from .attribution_weights import DAY_IN_SECONDS
+from .conversion_goal_conditions import conversion_goal_condition
from .marketing_analytics_base_query_runner import ResponseType
from .session_breakdown_base import MarketingSessionBreakdownQueryRunnerBase
+ConversionGoal = ConversionGoalFilter1 | ConversionGoalFilter2 | ConversionGoalFilter3
+
# Both runners collect per-person arrays under this name before diverging.
PERSON_ARRAYS_CTE = "person_arrays"
@@ -36,6 +47,78 @@ class AttributionQueryRunnerBase(MarketingSessionBreakdownQueryRunnerBase[Respon
# Narrower than the session-breakdown base's union: everything below reads attribution-only fields.
query: MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery
+ @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 these queries collect conversions from one `events`
+ scan grouped by person_id, so there is nothing to join them on here.
+ """
+ all_goals = self._get_team_conversion_goals()
+ goals, skipped_goals = self._filter_invalid_conversion_goals(all_goals)
+ self._valid_conversion_goals_count = len(goals)
+
+ for goal in goals:
+ if goal.conversion_goal_id == self.query.conversionGoalId:
+ if goal.kind == "DataWarehouseNode":
+ raise ValueError(
+ f"Conversion goal '{goal.conversion_goal_name}' is backed by a data warehouse table, "
+ "which attribution doesn't support yet. Pick an event or action goal."
+ )
+ return goal
+
+ # Only one goal is queried at a time, so another goal being unusable is not this query's problem.
+ # Only report it when it's the goal that was actually asked for.
+ skipped = next((g for g in all_goals if g.conversion_goal_id == self.query.conversionGoalId), None)
+ if skipped is not None:
+ reason = next(
+ (s.message for s in skipped_goals if s.conversion_goal_id == self.query.conversionGoalId), None
+ )
+ raise ValueError(reason or f"Conversion goal '{skipped.conversion_goal_name}' can't be attributed")
+
+ raise ValueError(f"Conversion goal '{self.query.conversionGoalId}' not found for this team")
+
+ @cached_property
+ def conversion_condition(self) -> ast.Expr:
+ """True for an event row that counts as a conversion for this goal.
+
+ Shared with the Dashboard's pipeline so the two can't drift on what a conversion is, which
+ includes the goal's own property filters: a goal scoped to purchases over $100 has to mean that
+ here too, or this table reports a different number than the Dashboard for the same goal.
+
+ Cached because the query references it three times, and the action branch hits Postgres.
+ """
+ goal = self.goal
+ condition = conversion_goal_condition(goal, self.team)
+ if condition is None:
+ # Validation already rejected the goals with nothing to match on, so what's left is an
+ # action-based goal whose action was deleted.
+ raise ValueError(
+ f"Conversion goal '{goal.conversion_goal_name}' points to an action that no longer exists. "
+ "Update the goal in marketing analytics settings, or pick another goal."
+ )
+ return condition
+
+ 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)])
+
@property
def lookback_window_days(self) -> int:
"""The window this query attributes over, bounded the same way the team setting is.
diff --git a/products/marketing_analytics/backend/hogql_queries/marketing_retention_query_runner.py b/products/marketing_analytics/backend/hogql_queries/marketing_retention_query_runner.py
new file mode 100644
index 000000000000..f8a6e554df38
--- /dev/null
+++ b/products/marketing_analytics/backend/hogql_queries/marketing_retention_query_runner.py
@@ -0,0 +1,744 @@
+"""Retention explorer: how well the users each channel brings in stick around.
+
+Cohorting is by acquisition, not by activity. A person is bucketed once, by the dimension of their first
+session, which is what a plain `RetentionQuery` with a session-property breakdown cannot express: it
+slices events by whatever tag each one carries, spreading a person across every channel that re-touched
+them.
+
+Cells are a share of the cohort, matching `retentionReference: 'total'` in core retention.
+"""
+
+from datetime import datetime, timedelta
+from functools import cached_property
+from typing import Any
+
+from posthog.schema import (
+ CachedMarketingAnalyticsRetentionQueryResponse,
+ IntervalType,
+ MarketingAnalyticsRetentionCell,
+ MarketingAnalyticsRetentionInterval,
+ MarketingAnalyticsRetentionQuery,
+ MarketingAnalyticsRetentionQueryResponse,
+ MarketingAnalyticsRetentionRow,
+)
+
+from posthog.hogql import ast
+from posthog.hogql.constants import MAX_BYTES_BEFORE_EXTERNAL_GROUP_BY, HogQLGlobalSettings, LimitContext
+from posthog.hogql.property import property_to_expr
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.hogql_queries.insights.utils.breakdowns import BREAKDOWN_OTHER_STRING_LABEL
+from posthog.hogql_queries.insights.utils.utils import get_start_of_interval_hogql
+from posthog.hogql_queries.utils.query_date_range import QueryDateRange, date_to_start_of_interval
+
+from .session_breakdown_base import MarketingSessionBreakdownQueryRunnerBase
+
+# Weekly by default, because a daily grain over a 90-day range is 90 cohort rows per breakdown value.
+DEFAULT_INTERVAL = MarketingAnalyticsRetentionInterval.WEEK
+DEFAULT_TOTAL_INTERVALS = 8
+DEFAULT_BREAKDOWN_LIMIT = 20
+DEFAULT_NEW_USER_LOOKBACK_DAYS = 90
+
+# These must multiply out under `MAX_SELECT_RETENTION_LIMIT`, since the outer select emits one row per
+# cell plus the folded row: (40 + 1) x 60 x 40 + 1 is under 100k. Raise one without checking that product
+# and the printer's row cap starts dropping whole breakdown values.
+MAX_TOTAL_INTERVALS = 40
+MAX_COHORTS = 60
+MAX_BREAKDOWN_LIMIT = 40
+MAX_NEW_USER_LOOKBACK_DAYS = 365
+
+# Shared with core retention so both surfaces print the same label for the folded tail.
+_OTHER = BREAKDOWN_OTHER_STRING_LABEL
+
+_INTERVAL_TO_TYPE: dict[MarketingAnalyticsRetentionInterval, IntervalType] = {
+ MarketingAnalyticsRetentionInterval.DAY: IntervalType.DAY,
+ MarketingAnalyticsRetentionInterval.WEEK: IntervalType.WEEK,
+ MarketingAnalyticsRetentionInterval.MONTH: IntervalType.MONTH,
+}
+
+_INTERVAL_LABEL: dict[MarketingAnalyticsRetentionInterval, str] = {
+ MarketingAnalyticsRetentionInterval.DAY: "Day",
+ MarketingAnalyticsRetentionInterval.WEEK: "Week",
+ MarketingAnalyticsRetentionInterval.MONTH: "Month",
+}
+
+
+# CTE names.
+_ACQUISITION_CTE = "acquisition"
+_ACTIVITY_CTE = "activity"
+_COHORT_SIZES_CTE = "cohort_sizes"
+_MATRIX_CTE = "matrix"
+_FOLDED_SIZES_CTE = "folded_sizes"
+_FOLDED_MATRIX_CTE = "folded_matrix"
+_SUMMARY_CTE = "summary"
+
+# Column names, shared between the SQL builders and `_calculate`.
+_ACTOR_ID = "actor_id"
+_BREAKDOWN_VALUE = "breakdown_value"
+_FIRST_SESSION_AT = "first_session_at"
+# What decides a person's cohort row. Named apart from `first_session_at`, which always means the session
+# the breakdown value is read off.
+_COHORT_AT = "cohort_at"
+_ACTIVITY_INDEX = "activity_index"
+_COHORT_INDEX = "cohort_index"
+_COHORT_SIZE = "cohort_size"
+_INTERVALS_FROM_BASE = "intervals_from_base"
+_COUNT = "count"
+_DISTINCT_BREAKDOWNS = "distinct_breakdowns"
+
+
+class MarketingAnalyticsRetentionQueryRunner(
+ MarketingSessionBreakdownQueryRunnerBase[MarketingAnalyticsRetentionQueryResponse]
+):
+ query: MarketingAnalyticsRetentionQuery
+ response: MarketingAnalyticsRetentionQueryResponse
+ cached_response: CachedMarketingAnalyticsRetentionQueryResponse
+
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
+ super().__init__(*args, **kwargs)
+ # A cohorts x columns matrix per breakdown value passes the default row cap long before the result
+ # is unreasonable, so escalate the same way `RetentionQueryRunner` does.
+ if self.limit_context in (LimitContext.QUERY, LimitContext.QUERY_ASYNC):
+ self.limit_context = LimitContext.RETENTION
+
+ # ------------------------------------------------------------------ options
+
+ @property
+ def retention_interval(self) -> MarketingAnalyticsRetentionInterval:
+ return self.query.retentionInterval or DEFAULT_INTERVAL
+
+ @property
+ def only_new_users(self) -> bool:
+ return True if self.query.onlyNewUsers is None else self.query.onlyNewUsers
+
+ @property
+ def new_user_lookback_days(self) -> int:
+ requested = self.query.newUserLookbackDays or DEFAULT_NEW_USER_LOOKBACK_DAYS
+ return max(1, min(requested, MAX_NEW_USER_LOOKBACK_DAYS))
+
+ @property
+ def breakdown_limit(self) -> int:
+ requested = self.query.breakdownLimit or DEFAULT_BREAKDOWN_LIMIT
+ return max(1, min(requested, MAX_BREAKDOWN_LIMIT))
+
+ @cached_property
+ def query_date_range(self) -> QueryDateRange:
+ """Overrides the base runner's interval-less range, because every expression here buckets by
+ period, so the range has to know which interval it counts in."""
+ return QueryDateRange(
+ date_range=self.query.dateRange,
+ team=self.team,
+ interval=_INTERVAL_TO_TYPE[self.retention_interval],
+ now=datetime.now(),
+ )
+
+ @cached_property
+ def _period_count(self) -> int:
+ """Aligned periods the requested range spans, before the cohort clamp.
+
+ Computed arithmetically instead of by enumerating the range, because `dateRange` is
+ caller-controlled: a daily grain over years 0001-9999 would materialize millions of datetimes to
+ slice off the last MAX_COHORTS. Zero or negative on an inverted range, which `cohort_starts`
+ floors at one.
+ """
+ start = self._aligned(self.query_date_range.date_from())
+ end = self._aligned(self.query_date_range.date_to())
+ if self.retention_interval == MarketingAnalyticsRetentionInterval.MONTH:
+ spans = (end.year - start.year) * 12 + end.month - start.month
+ elif self.retention_interval == MarketingAnalyticsRetentionInterval.WEEK:
+ spans = (end - start).days // 7
+ else:
+ spans = (end - start).days
+ return spans + 1
+
+ def _aligned(self, moment: datetime) -> datetime:
+ interval = _INTERVAL_TO_TYPE[self.retention_interval]
+ return date_to_start_of_interval(moment, interval, self.team)
+
+ @cached_property
+ def cohort_starts(self) -> list[datetime]:
+ """One entry per cohort row: the aligned start of each acquisition period in the range.
+
+ The first entry aligns backwards off `date_from`, so it can start before the range the filter bar
+ shows: a Monday-to-Sunday request on a team whose weeks start on Sunday opens its first cohort the
+ day before. That is deliberate, because a cohort cut short at its start understates its own
+ intake, and the whole first row would then read as a drop that never happened. The trailing edge
+ gets no such treatment, which is what `MarketingAnalyticsRetentionCell.complete` reports.
+
+ Truncated to the most recent MAX_COHORTS, because an old cohort with few columns left to show is
+ the least interesting part of a range someone widened by accident.
+
+ Always at least one entry. An inverted range spans no periods, and every expression below anchors
+ on `cohort_starts[0]`, so an empty list would fail the query on an index error instead of
+ returning the empty table the range describes.
+ """
+ kept = max(1, min(self._period_count, MAX_COHORTS))
+ end = self._aligned(self.query_date_range.date_to())
+ step = self.query_date_range.interval_relativedelta()
+ return [end - step * offset for offset in reversed(range(kept))]
+
+ @property
+ def truncated_cohorts(self) -> int:
+ """Older cohorts the clamp dropped. Reported because the clamp also pulls the scan's lower bound
+ forward, so the table then covers less than the date range the filter bar shows."""
+ return max(self._period_count - len(self.cohort_starts), 0)
+
+ @property
+ def interval_count(self) -> int:
+ """Capped at the cohort count, since a wider matrix is all cells the range cannot fill."""
+ requested = self.query.totalIntervals or DEFAULT_TOTAL_INTERVALS
+ clamped = max(1, min(requested, MAX_TOTAL_INTERVALS))
+ return min(clamped, len(self.cohort_starts))
+
+ # ------------------------------------------------------------------ expressions
+
+ def _interval_index_expr(self, source: ast.Expr) -> ast.Expr:
+ """How many periods `source` sits after the first cohort's start.
+
+ Both ends go through `get_start_of_interval_hogql`, so a team whose week starts on Sunday gets the
+ same boundaries here as in core retention.
+ """
+ interval = _INTERVAL_TO_TYPE[self.retention_interval].value
+ return ast.Call(
+ name="dateDiff",
+ args=[
+ ast.Constant(value=interval),
+ get_start_of_interval_hogql(
+ interval,
+ team=self.team,
+ source=ast.Call(name="toDateTime", args=[ast.Constant(value=self._cohort_window_start_str)]),
+ ),
+ get_start_of_interval_hogql(interval, team=self.team, source=source),
+ ],
+ )
+
+ @property
+ def _cohort_window_start_str(self) -> str:
+ return self.query_date_range.format_date(self.cohort_starts[0])
+
+ @property
+ def _cohort_window_end_str(self) -> str:
+ return self.query_date_range.date_to_str
+
+ def _range_conditions(self, field: ast.Expr) -> list[ast.Expr]:
+ return [
+ ast.CompareOperation(
+ left=field,
+ op=ast.CompareOperationOp.GtEq,
+ right=ast.Call(name="toDateTime", args=[ast.Constant(value=self._cohort_window_start_str)]),
+ ),
+ ast.CompareOperation(
+ left=field,
+ op=ast.CompareOperationOp.LtEq,
+ right=ast.Call(name="toDateTime", args=[ast.Constant(value=self._cohort_window_end_str)]),
+ ),
+ ]
+
+ def _event_filters(self) -> list[ast.Expr]:
+ """Applied to every arm, so the cohort side and the activity side select the same population."""
+ exprs: list[ast.Expr] = []
+ if self.query.properties:
+ exprs.append(property_to_expr(self.query.properties, self.team))
+ if self.query.filterTestAccounts and self.team.test_account_filters:
+ exprs.extend(property_to_expr(prop, self.team) for prop in self.team.test_account_filters)
+ return exprs
+
+ # ------------------------------------------------------------------ CTEs
+
+ def _build_pre_existing_select(self) -> ast.SelectQuery:
+ """(A) Persons who were already here before the range started.
+
+ A bare pageview instead of `_touchpoint_condition()`, because "has this person been here before"
+ must not depend on `excludeDirectTraffic`. Otherwise excluding direct makes every direct-acquired
+ returning visitor look brand new and inflates the paid channels' cohorts.
+
+ `_event_filters()` is applied, though, because a property filter narrows the whole question to a
+ segment, so "new" has to mean new to that segment.
+ """
+ return ast.SelectQuery(
+ select=[ast.Field(chain=["events", "person_id"])],
+ distinct=True,
+ select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),
+ where=ast.And(
+ exprs=[
+ self._pageview_condition(),
+ ast.Call(name="notEmpty", args=[ast.Field(chain=["events", "$session_id"])]),
+ ast.CompareOperation(
+ left=ast.Field(chain=["events", "timestamp"]),
+ op=ast.CompareOperationOp.GtEq,
+ right=ast.ArithmeticOperation(
+ left=ast.Call(name="toDateTime", args=[ast.Constant(value=self._cohort_window_start_str)]),
+ op=ast.ArithmeticOperationOp.Sub,
+ right=ast.Call(
+ name="toIntervalDay", args=[ast.Constant(value=self.new_user_lookback_days)]
+ ),
+ ),
+ ),
+ ast.CompareOperation(
+ left=ast.Field(chain=["events", "timestamp"]),
+ op=ast.CompareOperationOp.Lt,
+ right=ast.Call(name="toDateTime", args=[ast.Constant(value=self._cohort_window_start_str)]),
+ ),
+ *self._event_filters(),
+ ]
+ ),
+ )
+
+ def _build_first_session_select(self) -> ast.SelectQuery:
+ """(B) One row per acquired person: when they first arrived, and what brought them.
+
+ Both timestamp bounds are needed. The `events.timestamp` pair prunes parts on the table's order
+ key. The `session.$start_timestamp` pair defines "acquired in this window": without it a person
+ whose first session sits before the range gets pulled in by a later pageview.
+ """
+ session_start = ast.Field(chain=["events", "session", "$start_timestamp"])
+
+ conditions: list[ast.Expr] = [
+ self._touchpoint_condition(),
+ *self._range_conditions(ast.Field(chain=["events", "timestamp"])),
+ *self._range_conditions(session_start),
+ *self._event_filters(),
+ ]
+ if self.only_new_users:
+ conditions.append(
+ ast.CompareOperation(
+ left=ast.Field(chain=["events", "person_id"]),
+ op=ast.CompareOperationOp.NotIn,
+ right=self._build_pre_existing_select(),
+ )
+ )
+
+ return ast.SelectQuery(
+ select=[
+ ast.Alias(alias=_ACTOR_ID, expr=ast.Field(chain=["events", "person_id"])),
+ ast.Alias(alias=_FIRST_SESSION_AT, expr=ast.Call(name="min", args=[session_start])),
+ ast.Alias(
+ alias=_BREAKDOWN_VALUE,
+ expr=ast.Call(name="argMin", args=[self._breakdown_expr(), session_start]),
+ ),
+ ],
+ select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),
+ where=ast.And(exprs=conditions),
+ group_by=[ast.Field(chain=[_ACTOR_ID])],
+ )
+
+ def _build_acquisition_select(self) -> ast.SelectQuery:
+ """(C) One row per person in the table: the period they arrived in, and under which value.
+
+ The first session relabelled, because arriving is the acquisition.
+ """
+ first_session = self._build_first_session_select()
+ for column in first_session.select:
+ if isinstance(column, ast.Alias) and column.alias == _FIRST_SESSION_AT:
+ column.alias = _COHORT_AT
+ return first_session
+
+ def _build_activity_select(self) -> ast.SelectQuery:
+ """(D) One row per person per period they came back in.
+
+ Collapsed to (person, period) here instead of at the join, so the join below fans out by periods
+ a person was active in rather than by their every event.
+
+ Restricted to the acquired persons, which the matrix join would discard anyway. It matters
+ because this is the join's build side: without the restriction it holds every active person in
+ the range, and under `onlyNewUsers` the cohort can be a small fraction of that.
+ """
+ return ast.SelectQuery(
+ select=[
+ ast.Alias(alias=_ACTOR_ID, expr=ast.Field(chain=["events", "person_id"])),
+ ast.Alias(
+ alias=_ACTIVITY_INDEX,
+ expr=self._interval_index_expr(ast.Field(chain=["events", "timestamp"])),
+ ),
+ ],
+ select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),
+ where=ast.And(
+ exprs=[
+ self._pageview_condition(),
+ *self._range_conditions(ast.Field(chain=["events", "timestamp"])),
+ ast.CompareOperation(
+ left=ast.Field(chain=["events", "person_id"]),
+ op=ast.CompareOperationOp.In,
+ right=ast.SelectQuery(
+ select=[ast.Field(chain=[_ACTOR_ID])],
+ select_from=ast.JoinExpr(table=ast.Field(chain=[_ACQUISITION_CTE])),
+ ),
+ ),
+ *self._event_filters(),
+ ]
+ ),
+ group_by=[ast.Field(chain=[_ACTOR_ID]), ast.Field(chain=[_ACTIVITY_INDEX])],
+ )
+
+ def _build_cohort_sizes_select(self) -> ast.SelectQuery:
+ """(E) How many people each channel brought in, per acquisition period.
+
+ A plain `count` rather than a distinct one: `acquisition` groups by person and both columns
+ grouped on here are functions of that row, so a person reaches exactly one group once. Anything
+ that fans `acquisition` out per person breaks that.
+ """
+ return ast.SelectQuery(
+ select=[
+ ast.Field(chain=[_BREAKDOWN_VALUE]),
+ ast.Alias(alias=_COHORT_INDEX, expr=self._interval_index_expr(ast.Field(chain=[_COHORT_AT]))),
+ ast.Alias(alias=_COHORT_SIZE, expr=ast.Call(name="count", args=[ast.Field(chain=[_ACTOR_ID])])),
+ ],
+ select_from=ast.JoinExpr(table=ast.Field(chain=[_ACQUISITION_CTE])),
+ group_by=[ast.Field(chain=[_BREAKDOWN_VALUE]), ast.Field(chain=[_COHORT_INDEX])],
+ )
+
+ def _build_matrix_select(self) -> ast.SelectQuery:
+ """(F) The cells: people from one cohort seen again N periods later.
+
+ Counted distinctly, unlike `cohort_sizes`. The join fans out by the periods a person was active
+ in, and it is the grouping alone that pins each person back to one row per period, so a count
+ here is one refactor away from double-counting.
+ """
+ cohort_index = self._interval_index_expr(ast.Field(chain=[_ACQUISITION_CTE, _COHORT_AT]))
+ intervals_from_base = ast.ArithmeticOperation(
+ left=ast.Field(chain=[_ACTIVITY_CTE, _ACTIVITY_INDEX]),
+ op=ast.ArithmeticOperationOp.Sub,
+ right=cohort_index,
+ )
+
+ return ast.SelectQuery(
+ select=[
+ ast.Field(chain=[_ACQUISITION_CTE, _BREAKDOWN_VALUE]),
+ ast.Alias(alias=_COHORT_INDEX, expr=cohort_index),
+ ast.Alias(alias=_INTERVALS_FROM_BASE, expr=intervals_from_base),
+ ast.Alias(
+ alias=_COUNT,
+ expr=ast.Call(name="count", args=[ast.Field(chain=[_ACQUISITION_CTE, _ACTOR_ID])], distinct=True),
+ ),
+ ],
+ select_from=ast.JoinExpr(
+ table=ast.Field(chain=[_ACQUISITION_CTE]),
+ next_join=ast.JoinExpr(
+ join_type="INNER JOIN",
+ table=ast.Field(chain=[_ACTIVITY_CTE]),
+ constraint=ast.JoinConstraint(
+ expr=ast.CompareOperation(
+ left=ast.Field(chain=[_ACTIVITY_CTE, _ACTOR_ID]),
+ op=ast.CompareOperationOp.Eq,
+ right=ast.Field(chain=[_ACQUISITION_CTE, _ACTOR_ID]),
+ ),
+ constraint_type="ON",
+ ),
+ ),
+ ),
+ group_by=[
+ ast.Field(chain=[_ACQUISITION_CTE, _BREAKDOWN_VALUE]),
+ ast.Field(chain=[_COHORT_INDEX]),
+ ast.Field(chain=[_INTERVALS_FROM_BASE]),
+ ],
+ having=ast.And(
+ exprs=[
+ ast.CompareOperation(
+ left=ast.Field(chain=[_INTERVALS_FROM_BASE]),
+ op=ast.CompareOperationOp.GtEq,
+ right=ast.Constant(value=0),
+ ),
+ ast.CompareOperation(
+ left=ast.Field(chain=[_INTERVALS_FROM_BASE]),
+ op=ast.CompareOperationOp.Lt,
+ right=ast.Constant(value=self.interval_count),
+ ),
+ ]
+ ),
+ )
+
+ def _build_top_breakdowns_select(self) -> ast.SelectQuery:
+ """(G) The breakdown values big enough to get their own rows."""
+ return ast.SelectQuery(
+ select=[ast.Field(chain=[_BREAKDOWN_VALUE])],
+ select_from=ast.JoinExpr(table=ast.Field(chain=[_COHORT_SIZES_CTE])),
+ group_by=[ast.Field(chain=[_BREAKDOWN_VALUE])],
+ order_by=[
+ ast.OrderExpr(expr=ast.Call(name="sum", args=[ast.Field(chain=[_COHORT_SIZE])]), order="DESC"),
+ # Ties broken by name so the same data always folds the same way.
+ ast.OrderExpr(expr=ast.Field(chain=[_BREAKDOWN_VALUE]), order="ASC"),
+ ],
+ limit=ast.Constant(value=self.breakdown_limit),
+ )
+
+ def _display_value_expr(self, field: ast.Expr) -> ast.Expr:
+ """The label a breakdown value renders under: itself, or 'Other'.
+
+ Folded in SQL rather than over the rows a cap returned. Landing page produces far more rows than
+ any cap keeps, and truncating by the outer ORDER BY drops whole values alphabetically, so they
+ end up neither shown nor counted as folded.
+ """
+ return ast.Call(
+ name="if",
+ args=[
+ ast.CompareOperation(
+ left=field, op=ast.CompareOperationOp.In, right=self._build_top_breakdowns_select()
+ ),
+ field,
+ ast.Constant(value=_OTHER),
+ ],
+ )
+
+ def _build_folded_sizes_select(self) -> ast.SelectQuery:
+ """(H) Cohort sizes after folding. Summed, because several values can share the 'Other' label."""
+ return ast.SelectQuery(
+ select=[
+ ast.Alias(alias=_BREAKDOWN_VALUE, expr=self._display_value_expr(ast.Field(chain=[_BREAKDOWN_VALUE]))),
+ ast.Field(chain=[_COHORT_INDEX]),
+ ast.Alias(alias=_COHORT_SIZE, expr=ast.Call(name="sum", args=[ast.Field(chain=[_COHORT_SIZE])])),
+ ],
+ select_from=ast.JoinExpr(table=ast.Field(chain=[_COHORT_SIZES_CTE])),
+ group_by=[ast.Field(chain=[_BREAKDOWN_VALUE]), ast.Field(chain=[_COHORT_INDEX])],
+ )
+
+ def _build_folded_matrix_select(self) -> ast.SelectQuery:
+ """(I) Cells after folding.
+
+ Summing counts across folded values is exact, because a person has one acquisition breakdown
+ value, so no one is counted under two of the values being merged.
+ """
+ return ast.SelectQuery(
+ select=[
+ ast.Alias(alias=_BREAKDOWN_VALUE, expr=self._display_value_expr(ast.Field(chain=[_BREAKDOWN_VALUE]))),
+ ast.Field(chain=[_COHORT_INDEX]),
+ ast.Field(chain=[_INTERVALS_FROM_BASE]),
+ ast.Alias(alias=_COUNT, expr=ast.Call(name="sum", args=[ast.Field(chain=[_COUNT])])),
+ ],
+ select_from=ast.JoinExpr(table=ast.Field(chain=[_MATRIX_CTE])),
+ group_by=[
+ ast.Field(chain=[_BREAKDOWN_VALUE]),
+ ast.Field(chain=[_COHORT_INDEX]),
+ ast.Field(chain=[_INTERVALS_FROM_BASE]),
+ ],
+ )
+
+ def _build_summary_select(self) -> ast.SelectQuery:
+ """(J) One row saying how many breakdown values existed before folding.
+
+ Its own CTE rather than a SELECT-list scalar, which would be evaluated per output row and would
+ report nothing when there are no rows to attach it to.
+ """
+ return ast.SelectQuery(
+ select=[
+ ast.Alias(
+ alias=_DISTINCT_BREAKDOWNS,
+ expr=ast.Call(name="uniqExact", args=[ast.Field(chain=[_BREAKDOWN_VALUE])]),
+ ),
+ ],
+ select_from=ast.JoinExpr(table=ast.Field(chain=[_COHORT_SIZES_CTE])),
+ )
+
+ def _build_outer_select(self) -> ast.SelectQuery:
+ """(K) Cohort sizes with their cells attached.
+
+ LEFT from the sizes, so a cohort nobody came back to still emits one row carrying its size.
+ Otherwise a channel with terrible retention vanishes from the table, which reads as "no data"
+ instead of as the finding it is.
+ """
+ return ast.SelectQuery(
+ select=[
+ ast.Alias(alias=_BREAKDOWN_VALUE, expr=ast.Field(chain=[_FOLDED_SIZES_CTE, _BREAKDOWN_VALUE])),
+ ast.Alias(alias=_COHORT_INDEX, expr=ast.Field(chain=[_FOLDED_SIZES_CTE, _COHORT_INDEX])),
+ ast.Alias(alias=_COHORT_SIZE, expr=ast.Field(chain=[_FOLDED_SIZES_CTE, _COHORT_SIZE])),
+ ast.Alias(alias=_INTERVALS_FROM_BASE, expr=ast.Field(chain=[_FOLDED_MATRIX_CTE, _INTERVALS_FROM_BASE])),
+ ast.Alias(alias=_COUNT, expr=ast.Field(chain=[_FOLDED_MATRIX_CTE, _COUNT])),
+ ast.Alias(alias=_DISTINCT_BREAKDOWNS, expr=ast.Field(chain=[_SUMMARY_CTE, _DISTINCT_BREAKDOWNS])),
+ ],
+ select_from=ast.JoinExpr(
+ table=ast.Field(chain=[_FOLDED_SIZES_CTE]),
+ next_join=ast.JoinExpr(
+ join_type="LEFT JOIN",
+ table=ast.Field(chain=[_FOLDED_MATRIX_CTE]),
+ constraint=ast.JoinConstraint(
+ expr=ast.And(
+ exprs=[
+ ast.CompareOperation(
+ left=ast.Field(chain=[_FOLDED_MATRIX_CTE, _BREAKDOWN_VALUE]),
+ op=ast.CompareOperationOp.Eq,
+ right=ast.Field(chain=[_FOLDED_SIZES_CTE, _BREAKDOWN_VALUE]),
+ ),
+ ast.CompareOperation(
+ left=ast.Field(chain=[_FOLDED_MATRIX_CTE, _COHORT_INDEX]),
+ op=ast.CompareOperationOp.Eq,
+ right=ast.Field(chain=[_FOLDED_SIZES_CTE, _COHORT_INDEX]),
+ ),
+ ]
+ ),
+ constraint_type="ON",
+ ),
+ next_join=ast.JoinExpr(
+ join_type="CROSS JOIN",
+ table=ast.Field(chain=[_SUMMARY_CTE]),
+ ),
+ ),
+ ),
+ order_by=[
+ ast.OrderExpr(expr=ast.Field(chain=[_BREAKDOWN_VALUE]), order="ASC"),
+ ast.OrderExpr(expr=ast.Field(chain=[_COHORT_INDEX]), order="ASC"),
+ ast.OrderExpr(expr=ast.Field(chain=[_INTERVALS_FROM_BASE]), order="ASC"),
+ ],
+ # Folding caps the rows at (breakdown_limit + 1) x cohorts x columns, so this is a backstop
+ # that only bites if one of those clamps is raised without the others.
+ limit=ast.Constant(value=(self.breakdown_limit + 1) * len(self.cohort_starts) * self.interval_count + 1),
+ )
+
+ # ------------------------------------------------------------------ main query
+
+ def to_query(self) -> ast.SelectQuery:
+ ctes: dict[str, ast.CTE] = {}
+
+ # Materialized because both `cohort_sizes` and `matrix` read it, and ClickHouse re-evaluates an
+ # unmaterialized CTE at each reference, so the events scan underneath would run twice.
+ with self.timings.measure("retention_acquisition_cte"):
+ ctes[_ACQUISITION_CTE] = ast.CTE(
+ name=_ACQUISITION_CTE,
+ expr=self._build_acquisition_select(),
+ cte_type="subquery",
+ materialized=True,
+ )
+ with self.timings.measure("retention_activity_cte"):
+ ctes[_ACTIVITY_CTE] = ast.CTE(name=_ACTIVITY_CTE, expr=self._build_activity_select(), cte_type="subquery")
+ # Materialized for the same reason. Four references read it: `summary`, `folded_sizes`, and the
+ # `top_breakdowns` subquery that both folding CTEs inline.
+ ctes[_COHORT_SIZES_CTE] = ast.CTE(
+ name=_COHORT_SIZES_CTE,
+ expr=self._build_cohort_sizes_select(),
+ cte_type="subquery",
+ materialized=True,
+ )
+ ctes[_MATRIX_CTE] = ast.CTE(name=_MATRIX_CTE, expr=self._build_matrix_select(), cte_type="subquery")
+ ctes[_FOLDED_SIZES_CTE] = ast.CTE(
+ name=_FOLDED_SIZES_CTE, expr=self._build_folded_sizes_select(), cte_type="subquery"
+ )
+ ctes[_FOLDED_MATRIX_CTE] = ast.CTE(
+ name=_FOLDED_MATRIX_CTE, expr=self._build_folded_matrix_select(), cte_type="subquery"
+ )
+ ctes[_SUMMARY_CTE] = ast.CTE(name=_SUMMARY_CTE, expr=self._build_summary_select(), cte_type="subquery")
+
+ query = self._build_outer_select()
+ query.ctes = ctes
+ return query
+
+ # ------------------------------------------------------------------ execution
+
+ def _calculate(self) -> MarketingAnalyticsRetentionQueryResponse:
+ if self._period_count <= 0:
+ # An inverted range spans no periods. `cohort_starts` still floors itself at one entry so the
+ # expressions have an anchor to read, and that lone cohort opens at the aligned start of
+ # `date_to`, which sits BEFORE `date_to` itself. Running the query would report whoever
+ # arrived in that gap, so a range ending before it starts would return real retention data.
+ return self._empty_response()
+
+ query = self.to_query()
+
+ response = execute_hogql_query(
+ query_type="marketing_analytics_retention_query",
+ query=query,
+ team=self.team,
+ user=self.user,
+ timings=self.timings,
+ modifiers=self.modifiers,
+ limit_context=self.limit_context or LimitContext.RETENTION,
+ context=self._shared_hogql_context,
+ settings=HogQLGlobalSettings(max_bytes_before_external_group_by=MAX_BYTES_BEFORE_EXTERNAL_GROUP_BY),
+ )
+
+ # Mapped by column name, not tuple position, so adding a column cannot shift every later one.
+ columns = response.columns or []
+ named_results = [dict(zip(columns, row)) for row in response.results or []]
+
+ # The CROSS JOIN puts the same pre-folding count on every row, so read it off the first one.
+ distinct_breakdowns = int(named_results[0].get(_DISTINCT_BREAKDOWNS) or 0) if named_results else 0
+ rows = self._build_rows(named_results)
+
+ return MarketingAnalyticsRetentionQueryResponse(
+ results=rows,
+ intervalCount=self.interval_count,
+ interval=self.retention_interval,
+ labels=[f"{_INTERVAL_LABEL[self.retention_interval]} {i}" for i in range(self.interval_count)],
+ otherBreakdownCount=max(distinct_breakdowns - self.breakdown_limit, 0),
+ truncatedCohorts=self.truncated_cohorts,
+ totalCohortSize=sum(row.cohortSize for row in rows),
+ hogql=response.hogql,
+ timings=response.timings,
+ modifiers=self.modifiers,
+ )
+
+ def _empty_response(self) -> MarketingAnalyticsRetentionQueryResponse:
+ """The table a range that spans no periods describes, without paying for a scan."""
+ return MarketingAnalyticsRetentionQueryResponse(
+ results=[],
+ intervalCount=self.interval_count,
+ interval=self.retention_interval,
+ labels=[f"{_INTERVAL_LABEL[self.retention_interval]} {i}" for i in range(self.interval_count)],
+ otherBreakdownCount=0,
+ truncatedCohorts=0,
+ totalCohortSize=0,
+ modifiers=self.modifiers,
+ )
+
+ def _build_rows(self, rows: list[dict[str, Any]]) -> list[MarketingAnalyticsRetentionRow]:
+ """Collapse the flat cell list into one dense row per (breakdown value, cohort).
+
+ Every row gets exactly `interval_count` cells, zero-filled, so the table never has to check
+ whether a column exists before rendering it.
+ """
+ cohort_starts = self.cohort_starts
+ step = self.query_date_range.interval_relativedelta()
+ # Two bounds, because either one alone is wrong. `date_to()` is the last instant of the range, so
+ # an interval ending exactly there reads as unfinished and greys out the final column of every
+ # historical range. On an open-ended range `date_to()` is the end of today, which is in the
+ # future, so only the wall clock closes a period still being lived through.
+ range_end = min(
+ self.query_date_range.date_to() + timedelta(microseconds=1),
+ self.query_date_range.now_with_timezone,
+ )
+
+ sizes: dict[tuple[str, int], int] = {}
+ counts: dict[tuple[str, int], dict[int, int]] = {}
+ for row in rows:
+ cohort_index = int(row.get(_COHORT_INDEX) or 0)
+ if not 0 <= cohort_index < len(cohort_starts):
+ # Unreachable: the WHERE clause already bounds the session start to the cohort window.
+ # Guards the `cohort_starts` index below.
+ continue
+ key = (str(row.get(_BREAKDOWN_VALUE) or ""), cohort_index)
+ # Folded in SQL already, so the size repeats identically across a cohort's cells.
+ sizes[key] = int(row.get(_COHORT_SIZE) or 0)
+ offset = row.get(_INTERVALS_FROM_BASE)
+ if offset is not None:
+ counts.setdefault(key, {})[int(offset)] = int(row.get(_COUNT) or 0)
+
+ results: list[MarketingAnalyticsRetentionRow] = []
+ for value, cohort_index in sorted(sizes):
+ cohort_size = sizes[(value, cohort_index)]
+ bucket = counts.get((value, cohort_index), {})
+ values: list[MarketingAnalyticsRetentionCell] = []
+ for offset in range(self.interval_count):
+ count = bucket.get(offset, 0)
+ absolute = cohort_index + offset
+ # Without this the newest cohorts show a real-looking 0%, which reads as churn instead of
+ # as a period that has not happened yet.
+ complete = absolute < len(cohort_starts) and cohort_starts[absolute] + step <= range_end
+ values.append(
+ MarketingAnalyticsRetentionCell(
+ count=count,
+ rate=(count / cohort_size) if cohort_size else None,
+ complete=complete,
+ )
+ )
+ results.append(
+ MarketingAnalyticsRetentionRow(
+ breakdownValue=value,
+ cohortDate=cohort_starts[cohort_index].isoformat(),
+ cohortIndex=cohort_index,
+ cohortSize=cohort_size,
+ values=values,
+ )
+ )
+ return results
+
+ def _build_main_select_query(self, conversion_aggregator: Any) -> ast.SelectQuery:
+ """The base hook slots a SELECT into its ad-cost-joined table query. This runner overrides
+ `to_query` and builds its own CTE chain, so there is nothing to hook."""
+ raise NotImplementedError(f"{type(self).__name__} builds its query in to_query")
diff --git a/products/marketing_analytics/backend/hogql_queries/session_breakdown_base.py b/products/marketing_analytics/backend/hogql_queries/session_breakdown_base.py
index 8f8130d7756f..b8b600d4b4c7 100644
--- a/products/marketing_analytics/backend/hogql_queries/session_breakdown_base.py
+++ b/products/marketing_analytics/backend/hogql_queries/session_breakdown_base.py
@@ -8,27 +8,20 @@ what stops a channel row on one tab from meaning something different than the id
another.
"""
-from functools import cached_property
from typing import Generic
from posthog.schema import (
- ConversionGoalFilter1,
- ConversionGoalFilter2,
- ConversionGoalFilter3,
MarketingAnalyticsAttributionBreakdown,
MarketingAnalyticsAttributionPathsQuery,
MarketingAnalyticsAttributionQuery,
- PropertyMathType,
+ MarketingAnalyticsRetentionQuery,
)
from posthog.hogql import ast
from .constants import DIRECT_REFERRING_DOMAIN, UNKNOWN_CHANNEL
-from .conversion_goal_conditions import conversion_goal_condition
from .marketing_analytics_base_query_runner import MarketingAnalyticsBaseQueryRunner, ResponseType
-ConversionGoal = ConversionGoalFilter1 | ConversionGoalFilter2 | ConversionGoalFilter3
-
# Session field backing each breakdown. Read through the events->sessions lazy join, so a team on
# sessions v2 or v3 gets whichever version its modifiers select.
BREAKDOWN_SESSION_FIELDS: dict[MarketingAnalyticsAttributionBreakdown, str] = {
@@ -55,84 +48,14 @@ UNATTRIBUTED_SESSION_VALUES: dict[MarketingAnalyticsAttributionBreakdown, tuple[
class MarketingSessionBreakdownQueryRunnerBase(MarketingAnalyticsBaseQueryRunner[ResponseType], Generic[ResponseType]):
- query: MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery
+ query: (
+ MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | MarketingAnalyticsRetentionQuery
+ )
@property
def breakdown(self) -> MarketingAnalyticsAttributionBreakdown:
return self.query.breakdownBy or MarketingAnalyticsAttributionBreakdown.CHANNEL
- @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 these queries collect conversions from one `events`
- scan grouped by person_id, so there is nothing to join them on here.
- """
- all_goals = self._get_team_conversion_goals()
- goals, skipped_goals = self._filter_invalid_conversion_goals(all_goals)
- self._valid_conversion_goals_count = len(goals)
-
- for goal in goals:
- if goal.conversion_goal_id == self.query.conversionGoalId:
- if goal.kind == "DataWarehouseNode":
- raise ValueError(
- f"Conversion goal '{goal.conversion_goal_name}' is backed by a data warehouse table, "
- "which attribution doesn't support yet. Pick an event or action goal."
- )
- return goal
-
- # Only one goal is queried at a time, so another goal being unusable is not this query's problem.
- # Only report it when it's the goal that was actually asked for.
- skipped = next((g for g in all_goals if g.conversion_goal_id == self.query.conversionGoalId), None)
- if skipped is not None:
- reason = next(
- (s.message for s in skipped_goals if s.conversion_goal_id == self.query.conversionGoalId), None
- )
- raise ValueError(reason or f"Conversion goal '{skipped.conversion_goal_name}' can't be attributed")
-
- raise ValueError(f"Conversion goal '{self.query.conversionGoalId}' not found for this team")
-
- @cached_property
- def conversion_condition(self) -> ast.Expr:
- """True for an event row that counts as a conversion for this goal.
-
- Shared with the Dashboard's pipeline so the two can't drift on what a conversion is, which
- includes the goal's own property filters: a goal scoped to purchases over $100 has to mean that
- here too, or this table reports a different number than the Dashboard for the same goal.
-
- Cached because the query references it three times, and the action branch hits Postgres.
- """
- goal = self.goal
- condition = conversion_goal_condition(goal, self.team)
- if condition is None:
- # Validation already rejected the goals with nothing to match on, so what's left is an
- # action-based goal whose action was deleted.
- raise ValueError(
- f"Conversion goal '{goal.conversion_goal_name}' points to an action that no longer exists. "
- "Update the goal in marketing analytics settings, or pick another goal."
- )
- return condition
-
- def _conversion_value_expr(self) -> ast.Expr:
- """Value of one conversion: the goal's math property under SUM math, otherwise 1.
-
- Mirrors `ConversionGoalProcessor._get_conversion_value_expr` — these must stay in lockstep, or
- the same goal would report different revenue on the Dashboard and here.
- """
- goal = self.goal
- math_type = goal.math
- if math_type in ["sum", PropertyMathType.SUM] or str(math_type).endswith("_sum"):
- if goal.math_property:
- return ast.Call(
- name="coalesce",
- args=[
- ast.Call(name="toFloat", args=[ast.Field(chain=["events", "properties", goal.math_property])]),
- ast.Constant(value=0.0),
- ],
- )
- return ast.Call(name="toFloat", args=[ast.Constant(value=1)])
-
def _breakdown_expr(self) -> ast.Expr:
"""The dimension a touchpoint reports as, read off the session it belongs to.
diff --git a/products/marketing_analytics/backend/hogql_queries/test_marketing_retention_query_runner.py b/products/marketing_analytics/backend/hogql_queries/test_marketing_retention_query_runner.py
new file mode 100644
index 000000000000..6b3a05573cab
--- /dev/null
+++ b/products/marketing_analytics/backend/hogql_queries/test_marketing_retention_query_runner.py
@@ -0,0 +1,403 @@
+import pytest
+from freezegun import freeze_time
+from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
+
+from parameterized import parameterized
+
+from posthog.schema import (
+ DateRange,
+ EventPropertyFilter,
+ MarketingAnalyticsAttributionBreakdown,
+ MarketingAnalyticsRetentionInterval,
+ MarketingAnalyticsRetentionQuery,
+ PropertyOperator,
+)
+
+from posthog.hogql.constants import MAX_SELECT_RETENTION_LIMIT
+from posthog.hogql.test.utils import pretty_print_in_tests
+
+from posthog.hogql_queries.insights.utils.breakdowns import BREAKDOWN_OTHER_STRING_LABEL
+from posthog.models.team import WeekStartDay
+from posthog.models.utils import uuid7
+from posthog.test.persons import create_person
+
+from products.marketing_analytics.backend.hogql_queries.marketing_retention_query_runner import (
+ MAX_BREAKDOWN_LIMIT,
+ MAX_COHORTS,
+ MAX_TOTAL_INTERVALS,
+ MarketingAnalyticsRetentionQueryRunner,
+)
+
+# Every timestamp below is a Wednesday, so a cohort can't drift into the neighbouring week whichever
+# day the team's week starts on.
+WEEK_0 = "2023-01-04T12:00:00Z"
+WEEK_1 = "2023-01-11T12:00:00Z"
+WEEK_2 = "2023-01-18T12:00:00Z"
+WEEK_3 = "2023-01-25T12:00:00Z"
+BEFORE_RANGE = "2022-12-14T12:00:00Z"
+
+DATE_FROM = "2023-01-02"
+DATE_TO = "2023-01-29"
+
+
+class TestMarketingAnalyticsRetentionQueryRunner(ClickhouseTestMixin, BaseTest):
+ maxDiff = None
+ CLASS_DATA_LEVEL_SETUP = False
+
+ def _session(
+ self,
+ distinct_id: str,
+ started_at: str,
+ *,
+ utm_source: str | None = None,
+ utm_campaign: str | None = None,
+ referring_domain: str | None = "$direct",
+ path: str = "/",
+ ) -> None:
+ # uuid7 seeds the session id so `$start_timestamp` lands on `started_at`, which is what the
+ # acquisition window filters against. `$referring_domain` defaults to the `$direct` sentinel the
+ # SDKs send when there is no referrer, without which `$channel_type` classifies as Unknown.
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id=distinct_id,
+ timestamp=started_at,
+ properties={
+ "$session_id": str(uuid7(started_at)),
+ "$current_url": f"https://example.com{path}",
+ "$pathname": path,
+ **({"$referring_domain": referring_domain} if referring_domain is not None else {}),
+ **({"utm_source": utm_source} if utm_source else {}),
+ **({"utm_campaign": utm_campaign} if utm_campaign else {}),
+ },
+ )
+
+ def _query(
+ self,
+ breakdown: MarketingAnalyticsAttributionBreakdown = MarketingAnalyticsAttributionBreakdown.SOURCE,
+ *,
+ date_from: str = DATE_FROM,
+ date_to: str | None = DATE_TO,
+ interval: MarketingAnalyticsRetentionInterval = MarketingAnalyticsRetentionInterval.WEEK,
+ total_intervals: int = 4,
+ only_new_users: bool = True,
+ exclude_direct: bool = False,
+ exclude_unattributed: bool = False,
+ breakdown_limit: int | None = None,
+ new_user_lookback_days: int | None = None,
+ properties: list | None = None,
+ ) -> MarketingAnalyticsRetentionQuery:
+ return MarketingAnalyticsRetentionQuery(
+ dateRange=DateRange(date_from=date_from, date_to=date_to),
+ breakdownBy=breakdown,
+ retentionInterval=interval,
+ totalIntervals=total_intervals,
+ onlyNewUsers=only_new_users,
+ excludeDirectTraffic=exclude_direct,
+ excludeUnattributed=exclude_unattributed,
+ breakdownLimit=breakdown_limit,
+ newUserLookbackDays=new_user_lookback_days,
+ properties=properties or [],
+ )
+
+ def _run(self, *args, **kwargs):
+ flush_persons_and_events()
+ return MarketingAnalyticsRetentionQueryRunner(query=self._query(*args, **kwargs), team=self.team).calculate()
+
+ @staticmethod
+ def _rows_by_value(response) -> dict[str, list]:
+ rows: dict[str, list] = {}
+ for row in response.results:
+ rows.setdefault(row.breakdownValue, []).append(row)
+ return rows
+
+ def test_cohort_takes_the_first_sessions_source_not_the_last(self):
+ create_person(team=self.team, distinct_ids=["p1"])
+ self._session("p1", WEEK_0, utm_source="google")
+ self._session("p1", WEEK_1, utm_source="bing")
+
+ response = self._run()
+
+ rows = self._rows_by_value(response)
+ self.assertEqual(list(rows), ["google"])
+ self.assertEqual(rows["google"][0].cohortSize, 1)
+
+ def test_person_acquired_in_week_one_is_absent_from_week_zero(self):
+ create_person(team=self.team, distinct_ids=["p1"])
+ create_person(team=self.team, distinct_ids=["p2"])
+ self._session("p1", WEEK_0, utm_source="google")
+ self._session("p2", WEEK_1, utm_source="google")
+
+ response = self._run()
+
+ by_index = {row.cohortIndex: row.cohortSize for row in response.results}
+ self.assertEqual(by_index, {0: 1, 1: 1})
+
+ def test_returning_in_a_later_period_fills_that_column(self):
+ create_person(team=self.team, distinct_ids=["p1"])
+ self._session("p1", WEEK_0, utm_source="google")
+ self._session("p1", WEEK_2, utm_source="google")
+
+ response = self._run()
+
+ row = next(r for r in response.results if r.cohortIndex == 0)
+ self.assertEqual([cell.count for cell in row.values], [1, 0, 1, 0])
+ self.assertEqual(row.values[0].rate, 1.0)
+
+ @parameterized.expand([("only_new_users", True, 1), ("all_users", False, 2)])
+ def test_only_new_users_excludes_people_who_were_here_before(self, _name, only_new_users, expected_size):
+ create_person(team=self.team, distinct_ids=["new"])
+ create_person(team=self.team, distinct_ids=["returning"])
+ self._session("new", WEEK_0, utm_source="google")
+ self._session("returning", BEFORE_RANGE, utm_source="google")
+ self._session("returning", WEEK_0, utm_source="google")
+
+ response = self._run(only_new_users=only_new_users)
+
+ self.assertEqual(response.results[0].cohortSize, expected_size)
+
+ def test_only_new_users_still_excludes_a_prior_direct_visitor_when_direct_is_excluded(self):
+ # A user whose earlier visits were all direct must not count as newly acquired by the paid
+ # channel that re-touched them.
+ create_person(team=self.team, distinct_ids=["p1"])
+ self._session("p1", BEFORE_RANGE, utm_source=None, referring_domain="$direct")
+ self._session("p1", WEEK_0, utm_source="google", referring_domain="ads.example.com")
+
+ response = self._run(exclude_direct=True)
+
+ self.assertEqual(response.results, [])
+
+ @parameterized.expand(
+ [
+ (MarketingAnalyticsAttributionBreakdown.CHANNEL, {"referring_domain": None}),
+ (MarketingAnalyticsAttributionBreakdown.REFERRING_DOMAIN, {"referring_domain": "$direct"}),
+ (MarketingAnalyticsAttributionBreakdown.CAMPAIGN, {}),
+ ]
+ )
+ def test_exclude_unattributed_drops_the_sentinel_for_each_breakdown(self, breakdown, session_kwargs):
+ # Each breakdown has its own sentinel for "names nothing": the channel classifier's Unknown, the
+ # $direct referring domain, and an empty campaign.
+ create_person(team=self.team, distinct_ids=["p1"])
+ self._session("p1", WEEK_0, **session_kwargs)
+
+ self.assertEqual(self._run(breakdown, exclude_unattributed=True).results, [])
+ self.assertEqual(len(self._run(breakdown, exclude_unattributed=False).results), 1)
+
+ def test_breakdown_limit_folds_the_tail_into_other_and_keeps_the_sizes(self):
+ for i in range(4):
+ create_person(team=self.team, distinct_ids=[f"p{i}"])
+ self._session(f"p{i}", WEEK_0, utm_source=f"source-{i}")
+
+ response = self._run(breakdown_limit=2)
+
+ rows = self._rows_by_value(response)
+ self.assertEqual(response.otherBreakdownCount, 2)
+ self.assertEqual(rows[BREAKDOWN_OTHER_STRING_LABEL][0].cohortSize, 2)
+ self.assertEqual(response.totalCohortSize, 4)
+
+ def test_activity_after_the_range_does_not_count(self):
+ create_person(team=self.team, distinct_ids=["p1"])
+ self._session("p1", WEEK_0, utm_source="google")
+ self._session("p1", "2023-02-15T12:00:00Z", utm_source="google")
+
+ response = self._run()
+
+ self.assertEqual([cell.count for cell in response.results[0].values], [1, 0, 0, 0])
+
+ def test_a_session_that_never_resolved_produces_no_cohort_row(self):
+ # An unresolved session id yields an epoch-zero $start_timestamp rather than null, which would
+ # bucket the person tens of thousands of periods before the range.
+ create_person(team=self.team, distinct_ids=["p1"])
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id="p1",
+ timestamp=WEEK_0,
+ properties={"$session_id": "not-a-uuid7", "$referring_domain": "$direct"},
+ )
+
+ response = self._run()
+
+ self.assertEqual(response.results, [])
+
+ @parameterized.expand(
+ [
+ (MarketingAnalyticsRetentionInterval.WEEK, 4),
+ (MarketingAnalyticsRetentionInterval.MONTH, 1),
+ ]
+ )
+ def test_interval_controls_the_cohort_grain(self, interval, expected_cohorts):
+ for i, at in enumerate([WEEK_0, WEEK_1, WEEK_2, WEEK_3]):
+ create_person(team=self.team, distinct_ids=[f"p{i}"])
+ self._session(f"p{i}", at, utm_source="google")
+
+ response = self._run(interval=interval)
+
+ self.assertEqual(len({row.cohortIndex for row in response.results}), expected_cohorts)
+ self.assertEqual(response.interval, interval)
+
+ @parameterized.expand([("sunday_weeks", WeekStartDay.SUNDAY), ("monday_weeks", WeekStartDay.MONDAY)])
+ def test_elapsed_periods_are_complete_and_unlived_ones_are_not(self, _name, week_start_day):
+ # Both directions at once, so the test cannot pass by greying out everything or nothing.
+ # Parameterized over week start because that shifts every cohort boundary by a day.
+ self.team.week_start_day = week_start_day
+ self.team.save()
+ create_person(team=self.team, distinct_ids=["early"])
+ create_person(team=self.team, distinct_ids=["late"])
+ self._session("early", WEEK_0, utm_source="google")
+ self._session("late", DATE_TO + "T12:00:00Z", utm_source="google")
+
+ response = self._run()
+
+ by_index = {row.cohortIndex: row for row in response.results}
+ oldest, newest = by_index[min(by_index)], by_index[max(by_index)]
+ self.assertTrue(all(cell.complete for cell in oldest.values))
+ # The newest cohort's last column sits past the end of the range under either week start.
+ self.assertFalse(newest.values[-1].complete)
+
+ def test_the_final_fully_elapsed_period_is_complete(self):
+ # Comparing the cohort's end against an inclusive `date_to` renders the whole table as "–".
+ create_person(team=self.team, distinct_ids=["p1"])
+ self._session("p1", WEEK_0, utm_source="google")
+
+ response = self._run(date_from="2023-01-02", date_to="2023-01-08", total_intervals=1)
+
+ self.assertTrue(response.results[0].values[0].complete)
+
+ @freeze_time("2023-01-11T10:00:00Z")
+ def test_the_period_still_being_lived_through_is_incomplete(self):
+ # On an open-ended range `date_to` is the end of today, which is in the future, so comparing
+ # against it alone marks today complete and renders a partial day as a finished number.
+ create_person(team=self.team, distinct_ids=["p1"])
+ self._session("p1", "2023-01-04T12:00:00Z", utm_source="google")
+
+ response = self._run(
+ date_from="-7d",
+ date_to=None,
+ interval=MarketingAnalyticsRetentionInterval.DAY,
+ total_intervals=8,
+ )
+
+ row = next(r for r in response.results if r.cohortIndex == 0)
+ # Column 6 covers yesterday, column 7 covers today. Both asserted, so the test cannot pass by
+ # greying out everything.
+ self.assertTrue(row.values[6].complete)
+ self.assertFalse(row.values[7].complete)
+
+ def test_cohorts_beyond_the_cap_are_dropped_and_reported(self):
+ # The clamp pulls the scan's lower bound forward, so the table covers less than the date range
+ # the filter bar shows unless the dropped count comes back with it.
+ create_person(team=self.team, distinct_ids=["p1"])
+ self._session("p1", "2023-03-01T12:00:00Z", utm_source="google")
+
+ response = self._run(
+ date_from="2023-01-01",
+ date_to="2023-03-31",
+ interval=MarketingAnalyticsRetentionInterval.DAY,
+ total_intervals=1,
+ )
+
+ self.assertEqual(response.truncatedCohorts, 90 - MAX_COHORTS)
+ self.assertTrue(all(0 <= row.cohortIndex < MAX_COHORTS for row in response.results))
+
+ @parameterized.expand(
+ [
+ ("session_outside_the_aligned_window", "2023-01-01", WEEK_0),
+ # `cohort_starts` floors itself at one entry, and that cohort opens at the aligned start of
+ # date_to, which is days BEFORE date_to. A session in that gap is what an inverted range
+ # would still report on, and the case above cannot catch it: its session sits outside.
+ ("session_inside_the_aligned_window", "2023-01-11", "2023-01-09T12:00:00Z"),
+ ]
+ )
+ def test_an_inverted_date_range_returns_an_empty_table_instead_of_raising(self, _name, date_to, session_at):
+ # A range ending before it starts spans no periods, and every expression anchors on the first
+ # cohort start, so an empty cohort list would crash the query on an index error.
+ create_person(team=self.team, distinct_ids=["p1"])
+ self._session("p1", session_at, utm_source="google")
+
+ response = self._run(date_from="2023-03-01", date_to=date_to)
+
+ self.assertEqual(response.results, [])
+ self.assertEqual(response.totalCohortSize, 0)
+
+ @parameterized.expand(
+ [
+ ("interval_count_negative", {"total_intervals": -1}, "interval_count", 1),
+ ("interval_count_over_max", {"total_intervals": 9999}, "interval_count", MAX_TOTAL_INTERVALS),
+ ("breakdown_limit_negative", {"breakdown_limit": -5}, "breakdown_limit", 1),
+ ("breakdown_limit_over_max", {"breakdown_limit": 10_000}, "breakdown_limit", MAX_BREAKDOWN_LIMIT),
+ ("lookback_over_max", {"new_user_lookback_days": 9999}, "new_user_lookback_days", 365),
+ ]
+ )
+ def test_out_of_range_options_are_clamped_not_rejected(self, _name, overrides, attribute, expected):
+ # The range is wide enough that the interval clamp bites, not the cohort count.
+ query = self._query(
+ date_from="2023-01-01", date_to="2023-03-31", interval=MarketingAnalyticsRetentionInterval.DAY, **overrides
+ )
+ runner = MarketingAnalyticsRetentionQueryRunner(query=query, team=self.team)
+
+ self.assertEqual(getattr(runner, attribute), expected)
+
+ def test_the_widest_matrix_stays_under_the_printers_row_cap(self):
+ # The outer select's limit only stays a backstop while the three clamps multiply out below the
+ # printer's cap. Past that the printer keeps the first 100k rows in breakdown-value order and
+ # drops whole values off the end of the alphabet, the failure folding exists to prevent.
+ widest_matrix = (MAX_BREAKDOWN_LIMIT + 1) * MAX_COHORTS * MAX_TOTAL_INTERVALS + 1
+
+ self.assertLessEqual(widest_matrix, MAX_SELECT_RETENTION_LIMIT)
+
+ def test_folding_a_high_cardinality_breakdown_keeps_every_cell_inside_its_cohort(self):
+ # Sizes and cells fold through separate CTEs, so a value landing in "Other" on one side and not
+ # the other gives a cell counting more people than the cohort holds.
+ for i in range(6):
+ create_person(team=self.team, distinct_ids=[f"p{i}"])
+ self._session(f"p{i}", WEEK_0, path=f"/page-{i}")
+ self._session(f"p{i}", WEEK_1, path=f"/page-{i}")
+
+ response = self._run(MarketingAnalyticsAttributionBreakdown.LANDING_PAGE, breakdown_limit=2)
+
+ rows = self._rows_by_value(response)
+ self.assertEqual(len(rows), 3)
+ self.assertEqual(response.otherBreakdownCount, 4)
+ self.assertEqual(rows[BREAKDOWN_OTHER_STRING_LABEL][0].cohortSize, 4)
+ self.assertEqual(response.totalCohortSize, 6)
+ self.assertTrue(all(cell.count <= row.cohortSize for row in response.results for cell in row.values))
+
+ def test_property_filters_narrow_the_cohort_and_the_return(self):
+ # Applied only to the cohort side, a filtered-out person still fills return cells. Applied only
+ # to the return side, they inflate the cohort instead.
+ create_person(team=self.team, distinct_ids=["desktop"])
+ create_person(team=self.team, distinct_ids=["mobile"])
+ for distinct_id, device in (("desktop", "Desktop"), ("mobile", "Mobile")):
+ for at in (WEEK_0, WEEK_1):
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id=distinct_id,
+ timestamp=at,
+ properties={
+ "$session_id": str(uuid7(at)),
+ "$referring_domain": "$direct",
+ "utm_source": "google",
+ "$device_type": device,
+ },
+ )
+
+ response = self._run(
+ properties=[EventPropertyFilter(key="$device_type", value=["Desktop"], operator=PropertyOperator.EXACT)]
+ )
+
+ row = response.results[0]
+ self.assertEqual(row.cohortSize, 1)
+ self.assertEqual([cell.count for cell in row.values], [1, 1, 0, 0])
+
+ @pytest.mark.usefixtures("unittest_snapshot")
+ def test_query_shape(self):
+ # The assertions above all read the response, which cannot see the query's shape. Three
+ # regressions hide there: `acquisition` or `cohort_sizes` losing MATERIALIZED, which re-runs the
+ # events scan at each of their 2 and 4 references; `activity` losing the restriction to acquired
+ # persons, which leaves every active person in the range on the join's build side; and the two
+ # arms drifting apart on which filters they apply.
+ response = self._run()
+
+ assert pretty_print_in_tests(response.hogql, self.team.pk) == self.snapshot
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index a6b78dd479dc..1754782a62c3 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -43048,6 +43048,104 @@ export namespace Schemas {
version?: number | null;
}
+ export type MarketingAnalyticsRetentionInterval = typeof MarketingAnalyticsRetentionInterval[keyof typeof MarketingAnalyticsRetentionInterval];
+
+
+ export const MarketingAnalyticsRetentionInterval = {
+ Day: 'day',
+ Week: 'week',
+ Month: 'month',
+ } as const;
+
+ export interface MarketingAnalyticsRetentionCell {
+ /** False when this period has not fully elapsed within the queried range, so a low cell reads as unfinished instead of as churn. */
+ complete: boolean;
+ /** Distinct persons from this cohort active in this period. */
+ count: number;
+ /** count / cohortSize. Null when the cohort is empty. */
+ rate: number | null;
+ }
+
+ export interface MarketingAnalyticsRetentionRow {
+ breakdownValue: string;
+ /** Start of the cohort's period, in the team's timezone. */
+ cohortDate: string;
+ /** 0-based position of this cohort from the range start. */
+ cohortIndex: number;
+ /** Persons acquired in this period under this breakdown value. The denominator for every cell. */
+ cohortSize: number;
+ /** One per column, index = periods since the cohort started. Always intervalCount long. */
+ values: MarketingAnalyticsRetentionCell[];
+ }
+
+ export interface MarketingAnalyticsRetentionQueryResponse {
+ /** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
+ error?: string | null;
+ /** Generated HogQL query. */
+ hogql?: string | null;
+ interval: MarketingAnalyticsRetentionInterval;
+ /** Column count. Every row's values array has this length. */
+ intervalCount: number;
+ /** Column headers, e.g. ['Week 0', 'Week 1', ...]. */
+ labels: string[];
+ /** Modifiers used when performing the query */
+ modifiers?: HogQLQueryModifiers | null;
+ /** How many breakdown values were folded into 'Other', so the table can say so. */
+ otherBreakdownCount: number;
+ /** 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: MarketingAnalyticsRetentionRow[];
+ /** Measured timings for different parts of the query generation process */
+ timings?: QueryTiming[] | null;
+ /** Distinct persons acquired across every cohort and breakdown value. */
+ totalCohortSize: number;
+ /** Older cohorts dropped to bound the matrix. Non-zero means the table covers less than the date range the filter bar shows, so the table has to say so. */
+ truncatedCohorts: 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 MarketingAnalyticsRetentionQuery {
+ /** Groups aggregation - not used in Web Analytics but required for type compatibility */
+ aggregation_group_type_index?: number | null;
+ /** Cohort dimension, read off each person's first session. Defaults to channel. */
+ breakdownBy?: MarketingAnalyticsAttributionBreakdown | null;
+ /** Breakdown values kept before the rest roll into 'Other'. Defaults to 20. */
+ breakdownLimit?: number | null;
+ /** Colors used in the insight's visualization - not used in Web Analytics but required for type compatibility */
+ dataColorTheme?: number | null;
+ dateRange?: DateRange | null;
+ /** Drop direct sessions when deciding first touch, mirroring the attribution explorer. */
+ excludeDirectTraffic?: boolean | null;
+ /** Drop persons whose first session names nothing for the current breakdown. */
+ excludeUnattributed?: boolean | null;
+ filterTestAccounts?: boolean | null;
+ includeRevenue?: boolean | null;
+ kind?: 'MarketingAnalyticsRetentionQuery';
+ /** Modifiers used when performing the query */
+ modifiers?: HogQLQueryModifiers | null;
+ /** How far back to look for a prior session. Defaults to 90, clamped to 365. */
+ newUserLookbackDays?: number | null;
+ /** Only count persons with no session before the range, so a channel's cohorts are not inflated by users it acquired long ago. Defaults to true. */
+ onlyNewUsers?: boolean | null;
+ properties: (EventPropertyFilter | PersonPropertyFilter | SessionPropertyFilter | CohortPropertyFilter)[];
+ response?: MarketingAnalyticsRetentionQueryResponse | null;
+ /** Period for both the cohort rows and the return columns. Defaults to week. */
+ retentionInterval?: MarketingAnalyticsRetentionInterval | null;
+ tags?: QueryLogTags | null;
+ /** Return columns, counting period 0. Defaults to 8, clamped to 40. */
+ totalIntervals?: number | null;
+ useSessionsTable?: boolean | null;
+ /** version of the node, used for schema migrations */
+ version?: number | null;
+ }
+
export type WebAgentContentGrouping = typeof WebAgentContentGrouping[keyof typeof WebAgentContentGrouping];
@@ -44936,7 +45034,7 @@ export namespace Schemas {
query: string;
response?: HogQLMetadataResponse | null;
/** Query within which "expr" and "template" are validated. Defaults to "select * from events" */
- sourceQuery?: EventsNode | ActionsNode | PersonsNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | NonIntegratedConversionsTableQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebAgentAnalyticsQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingFingerprintProjectionQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingReleasesQuery | ErrorTrackingIssueCorrelationQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | CalendarHeatmapQuery | RecordingsQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolCategoryMapQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | null;
+ sourceQuery?: EventsNode | ActionsNode | PersonsNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | MarketingAnalyticsRetentionQuery | NonIntegratedConversionsTableQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebAgentAnalyticsQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingFingerprintProjectionQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingReleasesQuery | ErrorTrackingIssueCorrelationQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | CalendarHeatmapQuery | RecordingsQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolCategoryMapQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | null;
tags?: QueryLogTags | null;
/** Variables to be subsituted into the query */
variables?: HogQLMetadataVariables;
@@ -44962,7 +45060,7 @@ export namespace Schemas {
query: string;
response?: HogQLAutocompleteResponse | null;
/** Query in whose context to validate. */
- sourceQuery?: EventsNode | ActionsNode | PersonsNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | NonIntegratedConversionsTableQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebAgentAnalyticsQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingFingerprintProjectionQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingReleasesQuery | ErrorTrackingIssueCorrelationQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | CalendarHeatmapQuery | RecordingsQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolCategoryMapQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | null;
+ sourceQuery?: EventsNode | ActionsNode | PersonsNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | MarketingAnalyticsRetentionQuery | NonIntegratedConversionsTableQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebAgentAnalyticsQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingFingerprintProjectionQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingReleasesQuery | ErrorTrackingIssueCorrelationQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | CalendarHeatmapQuery | RecordingsQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolCategoryMapQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | null;
/** Start position of the editor word */
startPosition: number;
tags?: QueryLogTags | null;
@@ -70510,7 +70608,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 | ErrorTrackingFingerprintProjectionQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingReleasesQuery | ErrorTrackingIssueCorrelationQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebAgentAnalyticsQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | NonIntegratedConversionsTableQuery | DataVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | PathsV2Query | StickinessQuery | LifecycleQuery | FunnelCorrelationQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolCategoryMapQuery | 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 | ErrorTrackingFingerprintProjectionQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingReleasesQuery | ErrorTrackingIssueCorrelationQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebAgentAnalyticsQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | MarketingAnalyticsRetentionQuery | NonIntegratedConversionsTableQuery | DataVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | PathsV2Query | StickinessQuery | LifecycleQuery | FunnelCorrelationQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolCategoryMapQuery | 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
@@ -71384,6 +71482,39 @@ export namespace Schemas {
}
export interface QueryResponseAlternative37 {
+ /** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
+ error?: string | null;
+ /** Generated HogQL query. */
+ hogql?: string | null;
+ interval: MarketingAnalyticsRetentionInterval;
+ /** Column count. Every row's values array has this length. */
+ intervalCount: number;
+ /** Column headers, e.g. ['Week 0', 'Week 1', ...]. */
+ labels: string[];
+ /** Modifiers used when performing the query */
+ modifiers?: HogQLQueryModifiers | null;
+ /** How many breakdown values were folded into 'Other', so the table can say so. */
+ otherBreakdownCount: number;
+ /** 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: MarketingAnalyticsRetentionRow[];
+ /** Measured timings for different parts of the query generation process */
+ timings?: QueryTiming[] | null;
+ /** Distinct persons acquired across every cohort and breakdown value. */
+ totalCohortSize: number;
+ /** Older cohorts dropped to bound the matrix. Non-zero means the table covers less than the date range the filter bar shows, so the table has to say so. */
+ truncatedCohorts: 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 QueryResponseAlternative38 {
columns?: unknown[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -71411,7 +71542,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative38 {
+ export interface QueryResponseAlternative39 {
columns: unknown[];
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -71440,7 +71571,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative39 {
+ export interface QueryResponseAlternative40 {
columns: unknown[];
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -71468,7 +71599,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative40 {
+ export interface QueryResponseAlternative41 {
columns: unknown[];
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -71496,7 +71627,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative41 {
+ export interface QueryResponseAlternative42 {
/** Executed ClickHouse query */
clickhouse?: string | null;
/** Returned columns */
@@ -71533,7 +71664,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative42 {
+ export interface QueryResponseAlternative43 {
dateFrom?: string | null;
dateTo?: string | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
@@ -71559,7 +71690,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;
@@ -71590,7 +71721,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative44 {
+ export interface QueryResponseAlternative45 {
columns?: unknown[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -71618,7 +71749,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;
@@ -71645,7 +71776,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative46 {
+ export interface QueryResponseAlternative47 {
columns?: unknown[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -71674,7 +71805,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative47 {
+ export interface QueryResponseAlternative48 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -71701,7 +71832,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative48 {
+ export interface QueryResponseAlternative49 {
columns?: unknown[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -71728,7 +71859,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative49 {
+ export interface QueryResponseAlternative50 {
columns: unknown[];
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -71755,7 +71886,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative50 {
+ export interface QueryResponseAlternative51 {
columns?: unknown[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -71783,9 +71914,9 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export type QueryResponseAlternative51Results = {[key: string]: MarketingAnalyticsItem};
+ export type QueryResponseAlternative52Results = {[key: string]: MarketingAnalyticsItem};
- export interface QueryResponseAlternative51 {
+ export interface QueryResponseAlternative52 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -71798,7 +71929,7 @@ export namespace Schemas {
resolved_compare_date_range?: ResolvedDateRangeResponse | null;
/** The date range used for the query */
resolved_date_range?: ResolvedDateRangeResponse | null;
- results: QueryResponseAlternative51Results;
+ results: QueryResponseAlternative52Results;
samplingRate?: SamplingRate | null;
/** Measured timings for different parts of the query generation process */
timings?: QueryTiming[] | null;
@@ -71808,7 +71939,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative52 {
+ export interface QueryResponseAlternative53 {
columns?: unknown[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -71836,7 +71967,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative53 {
+ export interface QueryResponseAlternative54 {
columns?: string[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -71862,19 +71993,19 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export type QueryResponseAlternative55CredibleIntervals = {[key: string]: number[]};
+ export type QueryResponseAlternative56CredibleIntervals = {[key: string]: number[]};
- export type QueryResponseAlternative55InsightItemItem = { [key: string]: unknown };
+ export type QueryResponseAlternative56InsightItemItem = { [key: string]: unknown };
- export type QueryResponseAlternative55Probability = {[key: string]: number};
+ export type QueryResponseAlternative56Probability = {[key: string]: number};
- export interface QueryResponseAlternative55 {
- credible_intervals: QueryResponseAlternative55CredibleIntervals;
+ export interface QueryResponseAlternative56 {
+ credible_intervals: QueryResponseAlternative56CredibleIntervals;
expected_loss: number;
funnels_query?: FunnelsQuery | null;
- insight: QueryResponseAlternative55InsightItemItem[][];
+ insight: QueryResponseAlternative56InsightItemItem[][];
kind?: 'ExperimentFunnelsQuery';
- probability: QueryResponseAlternative55Probability;
+ probability: QueryResponseAlternative56Probability;
significance_code: ExperimentSignificanceCode;
significant: boolean;
stats_version?: number | null;
@@ -71883,20 +72014,20 @@ export namespace Schemas {
warnings?: DataWarehouseSyncWarning[] | null;
}
- export type QueryResponseAlternative56CredibleIntervals = {[key: string]: number[]};
+ export type QueryResponseAlternative57CredibleIntervals = {[key: string]: number[]};
- export type QueryResponseAlternative56InsightItem = { [key: string]: unknown };
+ export type QueryResponseAlternative57InsightItem = { [key: string]: unknown };
- export type QueryResponseAlternative56Probability = {[key: string]: number};
+ export type QueryResponseAlternative57Probability = {[key: string]: number};
- export interface QueryResponseAlternative56 {
+ export interface QueryResponseAlternative57 {
count_query?: TrendsQuery | null;
- credible_intervals: QueryResponseAlternative56CredibleIntervals;
+ credible_intervals: QueryResponseAlternative57CredibleIntervals;
exposure_query?: TrendsQuery | null;
- insight: QueryResponseAlternative56InsightItem[];
+ insight: QueryResponseAlternative57InsightItem[];
kind?: 'ExperimentTrendsQuery';
p_value: number;
- probability: QueryResponseAlternative56Probability;
+ probability: QueryResponseAlternative57Probability;
significance_code: ExperimentSignificanceCode;
significant: boolean;
stats_version?: number | null;
@@ -71905,7 +72036,7 @@ export namespace Schemas {
warnings?: DataWarehouseSyncWarning[] | null;
}
- export interface QueryResponseAlternative57 {
+ export interface QueryResponseAlternative58 {
columns?: string[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -71931,7 +72062,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative59 {
+ export interface QueryResponseAlternative60 {
columns?: unknown[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -71958,7 +72089,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative60 {
+ export interface QueryResponseAlternative61 {
columns: unknown[];
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -71988,7 +72119,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative61 {
+ export interface QueryResponseAlternative62 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
hasMore: boolean;
@@ -72016,9 +72147,9 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export type QueryResponseAlternative62ResultsItem = { [key: string]: unknown };
+ export type QueryResponseAlternative63ResultsItem = { [key: string]: unknown };
- export interface QueryResponseAlternative62 {
+ export interface QueryResponseAlternative63 {
boxplot_data?: BoxPlotDatum[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -72034,7 +72165,7 @@ export namespace Schemas {
resolved_compare_date_range?: ResolvedDateRangeResponse | null;
/** The date range used for the query */
resolved_date_range?: ResolvedDateRangeResponse | null;
- results: QueryResponseAlternative62ResultsItem[];
+ results: QueryResponseAlternative63ResultsItem[];
/** Measured timings for different parts of the query generation process */
timings?: QueryTiming[] | null;
/** Connector-synced data warehouse sources referenced by this query, if any. */
@@ -72043,7 +72174,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative63 {
+ export interface QueryResponseAlternative64 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -72067,7 +72198,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative64 {
+ export interface QueryResponseAlternative65 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -72089,7 +72220,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative65 {
+ export interface QueryResponseAlternative66 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -72111,7 +72242,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative66 {
+ export interface QueryResponseAlternative67 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -72133,9 +72264,9 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export type QueryResponseAlternative67ResultsItem = { [key: string]: unknown };
+ export type QueryResponseAlternative68ResultsItem = { [key: string]: unknown };
- 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. */
@@ -72148,7 +72279,7 @@ export namespace Schemas {
resolved_compare_date_range?: ResolvedDateRangeResponse | null;
/** The date range used for the query */
resolved_date_range?: ResolvedDateRangeResponse | null;
- results: QueryResponseAlternative67ResultsItem[];
+ results: QueryResponseAlternative68ResultsItem[];
/** Measured timings for different parts of the query generation process */
timings?: QueryTiming[] | null;
/** Connector-synced data warehouse sources referenced by this query, if any. */
@@ -72157,7 +72288,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative69 {
+ export interface QueryResponseAlternative70 {
columns?: unknown[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -72184,14 +72315,14 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export type QueryResponseAlternative70Tables = {[key: string]: DatabaseSchemaPostHogTable | DatabaseSchemaSystemTable | DatabaseSchemaDataWarehouseTable | DatabaseSchemaViewTable | DatabaseSchemaManagedViewTable | DatabaseSchemaBatchExportTable | DatabaseSchemaMaterializedViewTable | DatabaseSchemaEndpointTable};
+ export type QueryResponseAlternative71Tables = {[key: string]: DatabaseSchemaPostHogTable | DatabaseSchemaSystemTable | DatabaseSchemaDataWarehouseTable | DatabaseSchemaViewTable | DatabaseSchemaManagedViewTable | DatabaseSchemaBatchExportTable | DatabaseSchemaMaterializedViewTable | DatabaseSchemaEndpointTable};
- export interface QueryResponseAlternative70 {
+ export interface QueryResponseAlternative71 {
joins: DataWarehouseViewLink[];
- tables: QueryResponseAlternative70Tables;
+ tables: QueryResponseAlternative71Tables;
}
- export interface QueryResponseAlternative71 {
+ export interface QueryResponseAlternative72 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
has_next: boolean;
@@ -72216,7 +72347,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative72 {
+ export interface QueryResponseAlternative73 {
columns?: string[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -72244,7 +72375,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative73 {
+ export interface QueryResponseAlternative74 {
count: number;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -72267,7 +72398,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | 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;
/** Generated HogQL query. */
@@ -72289,7 +72420,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;
/** Generated HogQL query. */
@@ -72311,7 +72442,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative76 {
+ export interface QueryResponseAlternative77 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
hasMore?: boolean | null;
@@ -72338,7 +72469,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative77 {
+ export interface QueryResponseAlternative78 {
/** 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. */
@@ -72362,7 +72493,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative78 {
+ export interface QueryResponseAlternative79 {
/** 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. */
@@ -72386,7 +72517,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative79 {
+ export interface QueryResponseAlternative80 {
/** 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. */
@@ -72410,13 +72541,13 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative80 {
+ export interface QueryResponseAlternative81 {
questions: string[];
/** Data warehouse sync warnings — see AnalyticsQueryResponseBase.warnings for semantics. */
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;
hasMore?: boolean | null;
@@ -72441,7 +72572,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;
hasMore?: boolean | null;
@@ -72466,7 +72597,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative83 {
+ export interface QueryResponseAlternative84 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -72488,7 +72619,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative84 {
+ export interface QueryResponseAlternative85 {
columns?: string[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -72514,7 +72645,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative87 {
+ export interface QueryResponseAlternative88 {
/** Timestamp of the newer trace */
newerTimestamp?: string | null;
/** ID of the newer trace (chronologically after current) */
@@ -72529,7 +72660,7 @@ export namespace Schemas {
warnings?: DataWarehouseSyncWarning[] | 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. */
@@ -72551,7 +72682,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. */
@@ -72573,7 +72704,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative90 {
+ export interface QueryResponseAlternative91 {
columns: unknown[];
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -72603,7 +72734,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;
hasMore: boolean;
@@ -72631,7 +72762,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. */
@@ -72653,7 +72784,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative93 {
+ export interface QueryResponseAlternative94 {
columns?: unknown[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -72680,9 +72811,9 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export type QueryResponseAlternative94ResultsItem = { [key: string]: unknown };
+ export type QueryResponseAlternative95ResultsItem = { [key: string]: unknown };
- 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. */
@@ -72695,7 +72826,7 @@ export namespace Schemas {
resolved_compare_date_range?: ResolvedDateRangeResponse | null;
/** The date range used for the query */
resolved_date_range?: ResolvedDateRangeResponse | null;
- results: QueryResponseAlternative94ResultsItem[];
+ results: QueryResponseAlternative95ResultsItem[];
/** Measured timings for different parts of the query generation process */
timings?: QueryTiming[] | null;
/** Connector-synced data warehouse sources referenced by this query, if any. */
@@ -72704,7 +72835,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. */
@@ -72726,7 +72857,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. */
@@ -72748,7 +72879,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. */
@@ -72770,7 +72901,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. */
@@ -72792,7 +72923,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. */
@@ -72814,7 +72945,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. */
@@ -72836,7 +72967,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. */
@@ -72859,7 +72990,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. */
@@ -72881,7 +73012,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative103 {
+ export interface QueryResponseAlternative104 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -72903,7 +73034,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative104 {
+ export interface QueryResponseAlternative105 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -72925,7 +73056,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative105 {
+ export interface QueryResponseAlternative106 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -72947,7 +73078,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative106 {
+ export interface QueryResponseAlternative107 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -72969,7 +73100,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative107 {
+ export interface QueryResponseAlternative108 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -72991,7 +73122,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative108 {
+ export interface QueryResponseAlternative109 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -73013,7 +73144,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative109 {
+ export interface QueryResponseAlternative110 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -73035,7 +73166,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative110 {
+ export interface QueryResponseAlternative111 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -73057,7 +73188,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative111 {
+ export interface QueryResponseAlternative112 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -73079,18 +73210,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 | QueryResponseAlternative28 | QueryResponseAlternative29 | QueryResponseAlternative30 | QueryResponseAlternative31 | QueryResponseAlternative32 | QueryResponseAlternative33 | QueryResponseAlternative34 | QueryResponseAlternative35 | QueryResponseAlternative36 | QueryResponseAlternative37 | unknown | QueryResponseAlternative38 | QueryResponseAlternative39 | QueryResponseAlternative40 | QueryResponseAlternative41 | QueryResponseAlternative42 | QueryResponseAlternative43 | QueryResponseAlternative44 | QueryResponseAlternative45 | QueryResponseAlternative46 | QueryResponseAlternative47 | QueryResponseAlternative48 | QueryResponseAlternative49 | QueryResponseAlternative50 | QueryResponseAlternative51 | QueryResponseAlternative52 | QueryResponseAlternative53 | QueryResponseAlternative55 | QueryResponseAlternative56 | QueryResponseAlternative57 | QueryResponseAlternative59 | QueryResponseAlternative60 | QueryResponseAlternative61 | QueryResponseAlternative62 | QueryResponseAlternative63 | QueryResponseAlternative64 | QueryResponseAlternative65 | QueryResponseAlternative66 | QueryResponseAlternative67 | QueryResponseAlternative69 | QueryResponseAlternative70 | QueryResponseAlternative71 | QueryResponseAlternative72 | QueryResponseAlternative73 | QueryResponseAlternative74 | QueryResponseAlternative75 | QueryResponseAlternative76 | QueryResponseAlternative77 | QueryResponseAlternative78 | QueryResponseAlternative79 | QueryResponseAlternative80 | QueryResponseAlternative81 | QueryResponseAlternative82 | QueryResponseAlternative83 | QueryResponseAlternative84 | QueryResponseAlternative87 | QueryResponseAlternative88 | QueryResponseAlternative89 | QueryResponseAlternative90 | QueryResponseAlternative91 | QueryResponseAlternative92 | QueryResponseAlternative93 | QueryResponseAlternative94 | QueryResponseAlternative95 | QueryResponseAlternative96 | QueryResponseAlternative97 | QueryResponseAlternative98 | QueryResponseAlternative99 | QueryResponseAlternative100 | QueryResponseAlternative101 | QueryResponseAlternative102 | QueryResponseAlternative103 | QueryResponseAlternative104 | QueryResponseAlternative105 | QueryResponseAlternative106 | QueryResponseAlternative107 | QueryResponseAlternative108 | QueryResponseAlternative109 | QueryResponseAlternative110 | QueryResponseAlternative111;
+ 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 | QueryResponseAlternative28 | QueryResponseAlternative29 | QueryResponseAlternative30 | QueryResponseAlternative31 | QueryResponseAlternative32 | QueryResponseAlternative33 | QueryResponseAlternative34 | QueryResponseAlternative35 | QueryResponseAlternative36 | QueryResponseAlternative37 | QueryResponseAlternative38 | unknown | QueryResponseAlternative39 | QueryResponseAlternative40 | QueryResponseAlternative41 | QueryResponseAlternative42 | QueryResponseAlternative43 | QueryResponseAlternative44 | QueryResponseAlternative45 | QueryResponseAlternative46 | QueryResponseAlternative47 | QueryResponseAlternative48 | QueryResponseAlternative49 | QueryResponseAlternative50 | QueryResponseAlternative51 | QueryResponseAlternative52 | QueryResponseAlternative53 | QueryResponseAlternative54 | QueryResponseAlternative56 | QueryResponseAlternative57 | QueryResponseAlternative58 | QueryResponseAlternative60 | QueryResponseAlternative61 | QueryResponseAlternative62 | QueryResponseAlternative63 | QueryResponseAlternative64 | QueryResponseAlternative65 | QueryResponseAlternative66 | QueryResponseAlternative67 | QueryResponseAlternative68 | QueryResponseAlternative70 | QueryResponseAlternative71 | QueryResponseAlternative72 | QueryResponseAlternative73 | QueryResponseAlternative74 | QueryResponseAlternative75 | QueryResponseAlternative76 | QueryResponseAlternative77 | QueryResponseAlternative78 | QueryResponseAlternative79 | QueryResponseAlternative80 | QueryResponseAlternative81 | QueryResponseAlternative82 | QueryResponseAlternative83 | QueryResponseAlternative84 | QueryResponseAlternative85 | QueryResponseAlternative88 | QueryResponseAlternative89 | QueryResponseAlternative90 | QueryResponseAlternative91 | QueryResponseAlternative92 | QueryResponseAlternative93 | QueryResponseAlternative94 | QueryResponseAlternative95 | QueryResponseAlternative96 | QueryResponseAlternative97 | QueryResponseAlternative98 | QueryResponseAlternative99 | QueryResponseAlternative100 | QueryResponseAlternative101 | QueryResponseAlternative102 | QueryResponseAlternative103 | QueryResponseAlternative104 | QueryResponseAlternative105 | QueryResponseAlternative106 | QueryResponseAlternative107 | QueryResponseAlternative108 | QueryResponseAlternative109 | QueryResponseAlternative110 | QueryResponseAlternative111 | QueryResponseAlternative112;
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 | ErrorTrackingFingerprintProjectionQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingReleasesQuery | ErrorTrackingIssueCorrelationQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebAgentAnalyticsQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | NonIntegratedConversionsTableQuery | DataVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | PathsV2Query | StickinessQuery | LifecycleQuery | FunnelCorrelationQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolCategoryMapQuery | 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 | ErrorTrackingFingerprintProjectionQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingReleasesQuery | ErrorTrackingIssueCorrelationQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebAgentAnalyticsQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | MarketingAnalyticsRetentionQuery | NonIntegratedConversionsTableQuery | DataVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | PathsV2Query | StickinessQuery | LifecycleQuery | FunnelCorrelationQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolCategoryMapQuery | 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 | ErrorTrackingFingerprintProjectionQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingReleasesQuery | ErrorTrackingIssueCorrelationQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebAgentAnalyticsQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | NonIntegratedConversionsTableQuery | DataVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | PathsV2Query | StickinessQuery | LifecycleQuery | FunnelCorrelationQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolCategoryMapQuery | 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 | ErrorTrackingFingerprintProjectionQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingReleasesQuery | ErrorTrackingIssueCorrelationQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebAgentAnalyticsQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | MarketingAnalyticsRetentionQuery | NonIntegratedConversionsTableQuery | DataVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | PathsV2Query | StickinessQuery | LifecycleQuery | FunnelCorrelationQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolCategoryMapQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | PropertyValuesQuery;
}
export interface QuotaResourceLimit {