Skip to content

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

feat(marketing): add search recommendations query and mcp tool (#124396)

Javier Bahamondes0ef630e5d577
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 5cc1dbd9422c..c89cfaf18256 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -1896,6 +1896,9 @@
{
"$ref": "#/definitions/MarketingAnalyticsSearchQuery"
},
+ {
+ "$ref": "#/definitions/MarketingAnalyticsRecommendationsQuery"
+ },
{
"$ref": "#/definitions/WebOverviewQuery"
},
@@ -13067,6 +13070,115 @@
],
"type": "object"
},
+ "CachedMarketingAnalyticsRecommendationsQueryResponse": {
+ "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"
+ },
+ "disclaimer": {
+ "description": "Caveat to show with the results. The results are suggestions, and impact figures are estimates.",
+ "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"
+ },
+ "is_cached": {
+ "type": "boolean"
+ },
+ "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"
+ },
+ "query_metadata": {
+ "type": "object"
+ },
+ "query_scan": {
+ "$ref": "#/definitions/QueryScanSummary",
+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."
+ },
+ "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/MarketingAnalyticsRecommendation"
+ },
+ "type": "array"
+ },
+ "timezone": {
+ "type": "string"
+ },
+ "timings": {
+ "description": "Measured timings for different parts of the query generation process",
+ "items": {
+ "$ref": "#/definitions/QueryTiming"
+ },
+ "type": "array"
+ },
+ "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",
+ "disclaimer",
+ "is_cached",
+ "last_refresh",
+ "next_allowed_client_refresh",
+ "results",
+ "timezone"
+ ],
+ "type": "object"
+ },
"CachedMarketingAnalyticsRetentionQueryResponse": {
"additionalProperties": false,
"properties": {
@@ -36139,6 +36251,227 @@
"minItems": 2,
"type": "array"
},
+ "MarketingAnalyticsRecommendation": {
+ "additionalProperties": false,
+ "properties": {
+ "action": {
+ "type": "string"
+ },
+ "campaign": {
+ "description": "The campaign a search term recommendation applies to, when it applies to one.",
+ "type": ["string", "null"]
+ },
+ "currency": {
+ "type": ["string", "null"]
+ },
+ "impact": {
+ "description": "Monthly money impact in the account currency. Null when the rule has no money impact.",
+ "type": ["number", "null"]
+ },
+ "impactDirection": {
+ "$ref": "#/definitions/MarketingAnalyticsRecommendationImpactDirection"
+ },
+ "impactType": {
+ "$ref": "#/definitions/MarketingAnalyticsRecommendationImpactType"
+ },
+ "level": {
+ "$ref": "#/definitions/MarketingAnalyticsRecommendationLevel"
+ },
+ "reason": {
+ "type": "string"
+ },
+ "rule": {
+ "$ref": "#/definitions/MarketingAnalyticsRecommendationRule"
+ },
+ "subject": {
+ "description": "The campaign name or the search term the recommendation is about.",
+ "type": "string"
+ }
+ },
+ "required": ["rule", "level", "subject", "action", "reason", "impactDirection", "impactType"],
+ "type": "object"
+ },
+ "MarketingAnalyticsRecommendationImpactDirection": {
+ "enum": ["save", "gain", "invest", "keep"],
+ "type": "string"
+ },
+ "MarketingAnalyticsRecommendationImpactType": {
+ "enum": ["measured", "estimated"],
+ "type": "string"
+ },
+ "MarketingAnalyticsRecommendationLevel": {
+ "enum": ["campaign", "search_term"],
+ "type": "string"
+ },
+ "MarketingAnalyticsRecommendationRule": {
+ "enum": [
+ "budget_constrained",
+ "brand_leak",
+ "scale_campaign",
+ "review_campaign",
+ "policy_limited",
+ "brand_overlap",
+ "content_gap",
+ "keyword_gap",
+ "spend_without_conversions",
+ "striking_distance"
+ ],
+ "type": "string"
+ },
+ "MarketingAnalyticsRecommendationsQuery": {
+ "additionalProperties": false,
+ "properties": {
+ "dateRange": {
+ "$ref": "#/definitions/DateRange"
+ },
+ "kind": {
+ "const": "MarketingAnalyticsRecommendationsQuery",
+ "type": "string"
+ },
+ "modifiers": {
+ "$ref": "#/definitions/HogQLQueryModifiers",
+ "description": "Modifiers used when performing the query"
+ },
+ "response": {
+ "$ref": "#/definitions/MarketingAnalyticsRecommendationsQueryResponse"
+ },
+ "sources": {
+ "description": "Tables to read. Omit to read every synced Google Ads and Google Search Console source in the project.",
+ "items": {
+ "$ref": "#/definitions/MarketingAnalyticsRecommendationsSource"
+ },
+ "type": "array"
+ },
+ "tags": {
+ "$ref": "#/definitions/QueryLogTags"
+ },
+ "version": {
+ "description": "version of the node, used for schema migrations",
+ "type": "number"
+ }
+ },
+ "required": ["kind"],
+ "type": "object"
+ },
+ "MarketingAnalyticsRecommendationsQueryResponse": {
+ "additionalProperties": false,
+ "properties": {
+ "disclaimer": {
+ "description": "Caveat to show with the results. The results are suggestions, and impact figures are estimates.",
+ "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"
+ },
+ "modifiers": {
+ "$ref": "#/definitions/HogQLQueryModifiers",
+ "description": "Modifiers used when performing the query"
+ },
+ "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/MarketingAnalyticsRecommendation"
+ },
+ "type": "array"
+ },
+ "timings": {
+ "description": "Measured timings for different parts of the query generation process",
+ "items": {
+ "$ref": "#/definitions/QueryTiming"
+ },
+ "type": "array"
+ },
+ "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": ["disclaimer", "results"],
+ "type": "object"
+ },
+ "MarketingAnalyticsRecommendationsSource": {
+ "additionalProperties": false,
+ "properties": {
+ "campaignImpressionShareTable": {
+ "description": "Google Ads daily campaign impression share table.",
+ "type": "string"
+ },
+ "campaignStatsTable": {
+ "description": "Google Ads daily campaign stats table.",
+ "type": "string"
+ },
+ "campaignTable": {
+ "description": "Google Ads campaign table.",
+ "type": "string"
+ },
+ "customerTable": {
+ "description": "Google Ads customer table, used for the account currency.",
+ "type": "string"
+ },
+ "performanceMaxSearchTermTable": {
+ "description": "Google Ads search term table for Performance Max campaigns.",
+ "type": "string"
+ },
+ "queryTable": {
+ "description": "Google Search Console table with one row per query, or per query and page.",
+ "type": "string"
+ },
+ "searchTermKeywordTable": {
+ "description": "Google Ads search term table split by the keyword that matched each term.",
+ "type": "string"
+ },
+ "searchTermTable": {
+ "description": "Google Ads search term table for Search campaigns.",
+ "type": "string"
+ },
+ "sitesTable": {
+ "description": "Google Search Console sites table, used to infer the brand name.",
+ "type": "string"
+ },
+ "sourceType": {
+ "$ref": "#/definitions/MarketingAnalyticsRecommendationsSourceType"
+ }
+ },
+ "required": ["sourceType"],
+ "type": "object"
+ },
+ "MarketingAnalyticsRecommendationsSourceType": {
+ "enum": ["GoogleAds", "GoogleSearchConsole"],
+ "type": "string"
+ },
"MarketingAnalyticsRetentionCell": {
"additionalProperties": false,
"description": "One cohort's activity in one period since acquisition.",
@@ -40339,6 +40672,7 @@
"MarketingAnalyticsAttributionPathsQuery",
"MarketingAnalyticsRetentionQuery",
"MarketingAnalyticsSearchQuery",
+ "MarketingAnalyticsRecommendationsQuery",
"ExperimentMetric",
"ExperimentQuery",
"ExperimentExposureQuery",
@@ -45267,6 +45601,75 @@
"required": ["results"],
"type": "object"
},
+ {
+ "additionalProperties": false,
+ "properties": {
+ "disclaimer": {
+ "description": "Caveat to show with the results. The results are suggestions, and impact figures are estimates.",
+ "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"
+ },
+ "modifiers": {
+ "$ref": "#/definitions/HogQLQueryModifiers",
+ "description": "Modifiers used when performing the query"
+ },
+ "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/MarketingAnalyticsRecommendation"
+ },
+ "type": "array"
+ },
+ "timings": {
+ "description": "Measured timings for different parts of the query generation process",
+ "items": {
+ "$ref": "#/definitions/QueryTiming"
+ },
+ "type": "array"
+ },
+ "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": ["disclaimer", "results"],
+ "type": "object"
+ },
{
"properties": {},
"type": "object"
@@ -50961,6 +51364,9 @@
{
"$ref": "#/definitions/MarketingAnalyticsSearchQuery"
},
+ {
+ "$ref": "#/definitions/MarketingAnalyticsRecommendationsQuery"
+ },
{
"$ref": "#/definitions/DataVisualizationNode"
},
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 71f54cf34754..56acb55ce56a 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -167,6 +167,7 @@ export enum NodeKind {
MarketingAnalyticsAttributionPathsQuery = 'MarketingAnalyticsAttributionPathsQuery',
MarketingAnalyticsRetentionQuery = 'MarketingAnalyticsRetentionQuery',
MarketingAnalyticsSearchQuery = 'MarketingAnalyticsSearchQuery',
+ MarketingAnalyticsRecommendationsQuery = 'MarketingAnalyticsRecommendationsQuery',
// Experiment queries
ExperimentMetric = 'ExperimentMetric',
@@ -256,6 +257,7 @@ export type AnyDataNode =
| MarketingAnalyticsAttributionPathsQuery
| MarketingAnalyticsRetentionQuery
| MarketingAnalyticsSearchQuery
+ | MarketingAnalyticsRecommendationsQuery
| WebOverviewQuery
| WebStatsTableQuery
| WebExternalClicksTableQuery
@@ -375,6 +377,7 @@ export type QuerySchema =
| MarketingAnalyticsAttributionPathsQuery
| MarketingAnalyticsRetentionQuery
| MarketingAnalyticsSearchQuery
+ | MarketingAnalyticsRecommendationsQuery
// Interface nodes
| DataVisualizationNode
@@ -8524,6 +8527,80 @@ export interface MarketingAnalyticsSearchQueryResponse extends AnalyticsQueryRes
export type CachedMarketingAnalyticsSearchQueryResponse = CachedQueryResponse<MarketingAnalyticsSearchQueryResponse>
+export type MarketingAnalyticsRecommendationsSourceType = 'GoogleAds' | 'GoogleSearchConsole'
+
+export interface MarketingAnalyticsRecommendationsSource {
+ sourceType: MarketingAnalyticsRecommendationsSourceType
+ /** Google Ads campaign table. */
+ campaignTable?: string
+ /** Google Ads daily campaign stats table. */
+ campaignStatsTable?: string
+ /** Google Ads daily campaign impression share table. */
+ campaignImpressionShareTable?: string
+ /** Google Ads customer table, used for the account currency. */
+ customerTable?: string
+ /** Google Ads search term table for Search campaigns. */
+ searchTermTable?: string
+ /** Google Ads search term table split by the keyword that matched each term. */
+ searchTermKeywordTable?: string
+ /** Google Ads search term table for Performance Max campaigns. */
+ performanceMaxSearchTermTable?: string
+ /** Google Search Console table with one row per query, or per query and page. */
+ queryTable?: string
+ /** Google Search Console sites table, used to infer the brand name. */
+ sitesTable?: string
+}
+
+export interface MarketingAnalyticsRecommendationsQuery extends DataNode<MarketingAnalyticsRecommendationsQueryResponse> {
+ kind: NodeKind.MarketingAnalyticsRecommendationsQuery
+ dateRange?: DateRange
+ /** Tables to read. Omit to read every synced Google Ads and Google Search Console source in the project. */
+ sources?: MarketingAnalyticsRecommendationsSource[]
+}
+
+export type MarketingAnalyticsRecommendationRule =
+ | 'budget_constrained'
+ | 'brand_leak'
+ | 'scale_campaign'
+ | 'review_campaign'
+ | 'policy_limited'
+ | 'brand_overlap'
+ | 'content_gap'
+ | 'keyword_gap'
+ | 'spend_without_conversions'
+ | 'striking_distance'
+
+export type MarketingAnalyticsRecommendationLevel = 'campaign' | 'search_term'
+
+export type MarketingAnalyticsRecommendationImpactDirection = 'save' | 'gain' | 'invest' | 'keep'
+
+export type MarketingAnalyticsRecommendationImpactType = 'measured' | 'estimated'
+
+export interface MarketingAnalyticsRecommendation {
+ rule: MarketingAnalyticsRecommendationRule
+ level: MarketingAnalyticsRecommendationLevel
+ /** The campaign name or the search term the recommendation is about. */
+ subject: string
+ /** The campaign a search term recommendation applies to, when it applies to one. */
+ campaign?: string | null
+ action: string
+ reason: string
+ /** Monthly money impact in the account currency. Null when the rule has no money impact. */
+ impact?: number | null
+ impactDirection: MarketingAnalyticsRecommendationImpactDirection
+ impactType: MarketingAnalyticsRecommendationImpactType
+ currency?: string | null
+}
+
+export interface MarketingAnalyticsRecommendationsQueryResponse extends AnalyticsQueryResponseBase {
+ results: MarketingAnalyticsRecommendation[]
+ /** Caveat to show with the results. The results are suggestions, and impact figures are estimates. */
+ disclaimer: string
+}
+
+export type CachedMarketingAnalyticsRecommendationsQueryResponse =
+ CachedQueryResponse<MarketingAnalyticsRecommendationsQueryResponse>
+
export interface WebAnalyticsExternalSummaryRequest {
date_from: string
date_to: string
diff --git a/frontend/src/scenes/saved-insights/insightTypesMetadata.tsx b/frontend/src/scenes/saved-insights/insightTypesMetadata.tsx
index 2f0be1c85946..7129d2e2c753 100644
--- a/frontend/src/scenes/saved-insights/insightTypesMetadata.tsx
+++ b/frontend/src/scenes/saved-insights/insightTypesMetadata.tsx
@@ -598,6 +598,11 @@ export const QUERY_TYPES_METADATA: Record<NodeKind, InsightTypeMetadata> = {
icon: IconHogQL,
inMenu: false,
},
+ [NodeKind.MarketingAnalyticsRecommendationsQuery]: {
+ name: 'Marketing analytics recommendations',
+ icon: IconHogQL,
+ inMenu: false,
+ },
[NodeKind.UsageMetricsQuery]: {
name: 'Usage Metrics',
icon: IconPieChart,
diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.py
index 167f8f1506d8..eb93bc6dad6b 100644
--- a/posthog/clickhouse/query_tagging.py
+++ b/posthog/clickhouse/query_tagging.py
@@ -292,6 +292,7 @@ def kind_fallback_tags(kind: NodeKind) -> FallbackTags | None:
| NodeKind.MARKETING_ANALYTICS_ATTRIBUTION_PATHS_QUERY
| NodeKind.MARKETING_ANALYTICS_RETENTION_QUERY
| NodeKind.MARKETING_ANALYTICS_SEARCH_QUERY
+ | NodeKind.MARKETING_ANALYTICS_RECOMMENDATIONS_QUERY
):
return {"product": Product.MARKETING_ANALYTICS}
case (
diff --git a/posthog/hogql_queries/access_controlled_resources.py b/posthog/hogql_queries/access_controlled_resources.py
index 94f4fcae11c2..76b570ac33af 100644
--- a/posthog/hogql_queries/access_controlled_resources.py
+++ b/posthog/hogql_queries/access_controlled_resources.py
@@ -13,6 +13,7 @@ from posthog.schema import (
FunnelsDataWarehouseNode,
HogQLQuery,
LifecycleDataWarehouseNode,
+ MarketingAnalyticsRecommendationsQuery,
MarketingAnalyticsSearchQuery,
RetentionEntity,
)
@@ -351,6 +352,9 @@ def _references_data_warehouse(value) -> bool:
return True
if isinstance(value, MarketingAnalyticsSearchQuery):
return bool(value.sources)
+ if isinstance(value, MarketingAnalyticsRecommendationsQuery):
+ # No sources means the runner reads every synced source in the project.
+ return value.sources is None or bool(value.sources)
if isinstance(value, RetentionEntity) and value.type == EntityType.DATA_WAREHOUSE:
return True
if isinstance(value, BaseModel):
diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.py
index fdbfe390ab21..cc9cdb59c186 100644
--- a/posthog/hogql_queries/query_runner.py
+++ b/posthog/hogql_queries/query_runner.py
@@ -71,6 +71,7 @@ from posthog.schema import (
LifecycleQuery,
LifecycleQueryResponse,
MarketingAnalyticsAggregatedQuery,
+ MarketingAnalyticsRecommendationsQuery,
MarketingAnalyticsSearchQuery,
MarketingAnalyticsTableQuery,
MCPHarnessBreakdownQuery,
@@ -666,6 +667,7 @@ RunnableQueryNode = Union[
WebNotableChangesQuery,
SessionAttributionExplorerQuery,
MarketingAnalyticsTableQuery,
+ MarketingAnalyticsRecommendationsQuery,
MarketingAnalyticsSearchQuery,
MarketingAnalyticsAggregatedQuery,
ActorsPropertyTaxonomyQuery,
@@ -1657,6 +1659,15 @@ def get_query_runner(
user=user,
)
+ if kind == NodeKind.MARKETING_ANALYTICS_RECOMMENDATIONS_QUERY:
+ from products.marketing_analytics.backend.hogql_queries.marketing_recommendations_query_runner import (
+ MarketingAnalyticsRecommendationsQueryRunner,
+ )
+
+ return MarketingAnalyticsRecommendationsQueryRunner(
+ query=query, team=team, timings=timings, modifiers=modifiers, limit_context=limit_context, user=user
+ )
+
if kind == NodeKind.MARKETING_ANALYTICS_SEARCH_QUERY:
from products.marketing_analytics.backend.hogql_queries.marketing_search_query_runner import (
MarketingAnalyticsSearchQueryRunner,
diff --git a/posthog/hogql_queries/test/test_access_controlled_resources.py b/posthog/hogql_queries/test/test_access_controlled_resources.py
index 035f4396f50b..377e9fc8180c 100644
--- a/posthog/hogql_queries/test/test_access_controlled_resources.py
+++ b/posthog/hogql_queries/test/test_access_controlled_resources.py
@@ -17,6 +17,8 @@ from posthog.schema import (
HogQLQuery,
InsightActorsQuery,
LifecycleDataWarehouseNode,
+ MarketingAnalyticsRecommendationsQuery,
+ MarketingAnalyticsSearchQuery,
RetentionEntity,
RetentionFilter,
RetentionQuery,
@@ -220,6 +222,18 @@ class TestQueriedAccessControlledResources(BaseTest):
)
assert queried_access_controlled_resources(query, self.team) == set()
+ @parameterized.expand(
+ [
+ ("recommendations_without_sources", MarketingAnalyticsRecommendationsQuery(), True),
+ ("recommendations_with_empty_sources", MarketingAnalyticsRecommendationsQuery(sources=[]), False),
+ ("search_with_empty_sources", MarketingAnalyticsSearchQuery(sources=[]), False),
+ ]
+ )
+ def test_marketing_queries_partition_on_warehouse_scopes(self, _name, query, reads_warehouse):
+ scopes = queried_access_controlled_resources(query, self.team)
+ assert scopes is not None
+ assert ({"warehouse_table", "warehouse_view"} <= scopes) is reads_warehouse
+
def test_references_data_warehouse_covers_all_variants_and_nesting(self):
variants = [
DataWarehouseNode(id="t", id_field="id", distinct_id_field="d", table_name="t", timestamp_field="ts"),
diff --git a/posthog/schema.py b/posthog/schema.py
index 0bf1c8366694..ce2ed635e2e3 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -196,6 +196,11 @@ from posthog.schema_enums import (
MarketingAnalyticsConstants as MarketingAnalyticsConstants,
MarketingAnalyticsDrillDownLevel as MarketingAnalyticsDrillDownLevel,
MarketingAnalyticsOrderByEnum as MarketingAnalyticsOrderByEnum,
+ MarketingAnalyticsRecommendationImpactDirection as MarketingAnalyticsRecommendationImpactDirection,
+ MarketingAnalyticsRecommendationImpactType as MarketingAnalyticsRecommendationImpactType,
+ MarketingAnalyticsRecommendationLevel as MarketingAnalyticsRecommendationLevel,
+ MarketingAnalyticsRecommendationRule as MarketingAnalyticsRecommendationRule,
+ MarketingAnalyticsRecommendationsSourceType as MarketingAnalyticsRecommendationsSourceType,
MarketingAnalyticsRetentionInterval as MarketingAnalyticsRetentionInterval,
MarketingAnalyticsSchemaFieldTypes as MarketingAnalyticsSchemaFieldTypes,
MatchedOn as MatchedOn,
@@ -3118,7 +3123,7 @@ class QueryResponseAlternative7(BaseModel):
stdout: str | None = None
-class QueryResponseAlternative78(BaseModel):
+class QueryResponseAlternative79(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -6880,6 +6885,64 @@ class MarketingAnalyticsItem(BaseModel):
value: float | str | None = None
+class MarketingAnalyticsRecommendation(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ action: str
+ campaign: str | None = Field(
+ default=None,
+ description=("The campaign a search term recommendation applies to, when it applies to one."),
+ )
+ currency: str | None = None
+ impact: float | None = Field(
+ default=None,
+ description=("Monthly money impact in the account currency. Null when the rule has no money impact."),
+ )
+ impactDirection: MarketingAnalyticsRecommendationImpactDirection
+ impactType: MarketingAnalyticsRecommendationImpactType
+ level: MarketingAnalyticsRecommendationLevel
+ reason: str
+ rule: MarketingAnalyticsRecommendationRule
+ subject: str = Field(
+ ...,
+ description="The campaign name or the search term the recommendation is about.",
+ )
+
+
+class MarketingAnalyticsRecommendationsSource(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ campaignImpressionShareTable: str | None = Field(
+ default=None, description="Google Ads daily campaign impression share table."
+ )
+ campaignStatsTable: str | None = Field(default=None, description="Google Ads daily campaign stats table.")
+ campaignTable: str | None = Field(default=None, description="Google Ads campaign table.")
+ customerTable: str | None = Field(
+ default=None,
+ description="Google Ads customer table, used for the account currency.",
+ )
+ performanceMaxSearchTermTable: str | None = Field(
+ default=None,
+ description="Google Ads search term table for Performance Max campaigns.",
+ )
+ queryTable: str | None = Field(
+ default=None,
+ description=("Google Search Console table with one row per query, or per query and page."),
+ )
+ searchTermKeywordTable: str | None = Field(
+ default=None,
+ description=("Google Ads search term table split by the keyword that matched each term."),
+ )
+ searchTermTable: str | None = Field(default=None, description="Google Ads search term table for Search campaigns.")
+ sitesTable: str | None = Field(
+ default=None,
+ description="Google Search Console sites table, used to infer the brand name.",
+ )
+ sourceType: MarketingAnalyticsRecommendationsSourceType
+
+
class MarketingAnalyticsRetentionCell(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -7604,7 +7667,7 @@ class QueryResponseAlternative31(BaseModel):
status: ExternalQueryStatus
-class QueryResponseAlternative85(BaseModel):
+class QueryResponseAlternative86(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -14677,6 +14740,72 @@ class CachedMarketingAnalyticsAttributionQueryResponse(BaseModel):
)
+class CachedMarketingAnalyticsRecommendationsQueryResponse(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"),
+ )
+ disclaimer: str = Field(
+ ...,
+ description=("Caveat to show with the results. The results are suggestions, and impact figures are estimates."),
+ )
+ 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.")
+ is_cached: bool
+ last_refresh: AwareDatetime
+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
+ next_allowed_client_refresh: AwareDatetime
+ query_metadata: dict[str, Any] | None = None
+ query_scan: QueryScanSummary | None = Field(
+ default=None,
+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),
+ )
+ 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[MarketingAnalyticsRecommendation]
+ timezone: str
+ timings: list[QueryTiming] | None = Field(
+ default=None,
+ description=("Measured timings for different parts of the query generation process"),
+ )
+ 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 CachedMarketingAnalyticsRetentionQueryResponse(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -20885,6 +21014,57 @@ class MarketingAnalyticsAttributionQueryResponse(BaseModel):
)
+class MarketingAnalyticsRecommendationsQueryResponse(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ disclaimer: str = Field(
+ ...,
+ description=("Caveat to show with the results. The results are suggestions, and impact figures are estimates."),
+ )
+ 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.")
+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
+ 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[MarketingAnalyticsRecommendation]
+ timings: list[QueryTiming] | None = Field(
+ default=None,
+ description=("Measured timings for different parts of the query generation process"),
+ )
+ 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 MarketingAnalyticsRetentionQueryResponse(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -23080,6 +23260,57 @@ class QueryResponseAlternative38(BaseModel):
class QueryResponseAlternative39(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ disclaimer: str = Field(
+ ...,
+ description=("Caveat to show with the results. The results are suggestions, and impact figures are estimates."),
+ )
+ 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.")
+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
+ 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[MarketingAnalyticsRecommendation]
+ timings: list[QueryTiming] | None = Field(
+ default=None,
+ description=("Measured timings for different parts of the query generation process"),
+ )
+ 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 QueryResponseAlternative40(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -23132,7 +23363,7 @@ class QueryResponseAlternative39(BaseModel):
)
-class QueryResponseAlternative40(BaseModel):
+class QueryResponseAlternative41(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -23185,7 +23416,7 @@ class QueryResponseAlternative40(BaseModel):
)
-class QueryResponseAlternative41(BaseModel):
+class QueryResponseAlternative42(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -23238,7 +23469,7 @@ class QueryResponseAlternative41(BaseModel):
)
-class QueryResponseAlternative43(BaseModel):
+class QueryResponseAlternative44(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -23307,7 +23538,7 @@ class QueryResponseAlternative43(BaseModel):
)
-class QueryResponseAlternative44(BaseModel):
+class QueryResponseAlternative45(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -23379,7 +23610,7 @@ class QueryResponseAlternative44(BaseModel):
)
-class QueryResponseAlternative45(BaseModel):
+class QueryResponseAlternative46(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -23432,7 +23663,7 @@ class QueryResponseAlternative45(BaseModel):
)
-class QueryResponseAlternative46(BaseModel):
+class QueryResponseAlternative47(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -23484,7 +23715,7 @@ class QueryResponseAlternative46(BaseModel):
)
-class QueryResponseAlternative47(BaseModel):
+class QueryResponseAlternative48(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -23556,7 +23787,7 @@ class QueryResponseAlternative47(BaseModel):
)
-class QueryResponseAlternative48(BaseModel):
+class QueryResponseAlternative49(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -23622,7 +23853,7 @@ class QueryResponseAlternative48(BaseModel):
)
-class QueryResponseAlternative49(BaseModel):
+class QueryResponseAlternative50(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -23674,7 +23905,7 @@ class QueryResponseAlternative49(BaseModel):
)
-class QueryResponseAlternative50(BaseModel):
+class QueryResponseAlternative51(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -23726,7 +23957,7 @@ class QueryResponseAlternative50(BaseModel):
)
-class QueryResponseAlternative51(BaseModel):
+class QueryResponseAlternative52(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -23791,7 +24022,7 @@ class QueryResponseAlternative51(BaseModel):
)
-class QueryResponseAlternative52(BaseModel):
+class QueryResponseAlternative53(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -23851,7 +24082,7 @@ class QueryResponseAlternative52(BaseModel):
)
-class QueryResponseAlternative53(BaseModel):
+class QueryResponseAlternative54(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -23902,7 +24133,7 @@ class QueryResponseAlternative53(BaseModel):
)
-class QueryResponseAlternative55(BaseModel):
+class QueryResponseAlternative56(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -23953,7 +24184,7 @@ class QueryResponseAlternative55(BaseModel):
)
-class QueryResponseAlternative57(BaseModel):
+class QueryResponseAlternative58(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -24005,7 +24236,7 @@ class QueryResponseAlternative57(BaseModel):
)
-class QueryResponseAlternative58(BaseModel):
+class QueryResponseAlternative59(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -24062,7 +24293,7 @@ class QueryResponseAlternative58(BaseModel):
)
-class QueryResponseAlternative59(BaseModel):
+class QueryResponseAlternative60(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -24130,7 +24361,7 @@ class QueryResponseAlternative59(BaseModel):
)
-class QueryResponseAlternative60(BaseModel):
+class QueryResponseAlternative61(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -24187,7 +24418,7 @@ class QueryResponseAlternative60(BaseModel):
)
-class QueryResponseAlternative61(BaseModel):
+class QueryResponseAlternative62(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -24241,7 +24472,7 @@ class QueryResponseAlternative61(BaseModel):
)
-class QueryResponseAlternative62(BaseModel):
+class QueryResponseAlternative63(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -24288,7 +24519,7 @@ class QueryResponseAlternative62(BaseModel):
)
-class QueryResponseAlternative63(BaseModel):
+class QueryResponseAlternative64(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -24335,7 +24566,7 @@ class QueryResponseAlternative63(BaseModel):
)
-class QueryResponseAlternative64(BaseModel):
+class QueryResponseAlternative65(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -24382,7 +24613,7 @@ class QueryResponseAlternative64(BaseModel):
)
-class QueryResponseAlternative65(BaseModel):
+class QueryResponseAlternative66(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -24437,7 +24668,7 @@ class QueryResponseAlternative65(BaseModel):
)
-class QueryResponseAlternative68(BaseModel):
+class QueryResponseAlternative69(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -24489,7 +24720,7 @@ class QueryResponseAlternative68(BaseModel):
)
-class QueryResponseAlternative69(BaseModel):
+class QueryResponseAlternative70(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -24541,7 +24772,7 @@ class QueryResponseAlternative69(BaseModel):
)
-class QueryResponseAlternative70(BaseModel):
+class QueryResponseAlternative71(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -24589,7 +24820,7 @@ class QueryResponseAlternative70(BaseModel):
)
-class QueryResponseAlternative71(BaseModel):
+class QueryResponseAlternative72(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -24636,7 +24867,7 @@ class QueryResponseAlternative71(BaseModel):
)
-class QueryResponseAlternative72(BaseModel):
+class QueryResponseAlternative73(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -24683,7 +24914,7 @@ class QueryResponseAlternative72(BaseModel):
)
-class QueryResponseAlternative73(BaseModel):
+class QueryResponseAlternative74(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -24736,7 +24967,7 @@ class QueryResponseAlternative73(BaseModel):
)
-class QueryResponseAlternative74(BaseModel):
+class QueryResponseAlternative75(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -24787,7 +25018,7 @@ class QueryResponseAlternative74(BaseModel):
)
-class QueryResponseAlternative75(BaseModel):
+class QueryResponseAlternative76(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -24838,7 +25069,7 @@ class QueryResponseAlternative75(BaseModel):
)
-class QueryResponseAlternative76(BaseModel):
+class QueryResponseAlternative77(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -24889,7 +25120,7 @@ class QueryResponseAlternative76(BaseModel):
)
-class QueryResponseAlternative77(BaseModel):
+class QueryResponseAlternative78(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -24940,7 +25171,7 @@ class QueryResponseAlternative77(BaseModel):
)
-class QueryResponseAlternative79(BaseModel):
+class QueryResponseAlternative80(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -24990,7 +25221,7 @@ class QueryResponseAlternative79(BaseModel):
)
-class QueryResponseAlternative80(BaseModel):
+class QueryResponseAlternative81(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -25040,7 +25271,7 @@ class QueryResponseAlternative80(BaseModel):
)
-class QueryResponseAlternative81(BaseModel):
+class QueryResponseAlternative82(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -25087,7 +25318,7 @@ class QueryResponseAlternative81(BaseModel):
)
-class QueryResponseAlternative82(BaseModel):
+class QueryResponseAlternative83(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -25138,7 +25369,7 @@ class QueryResponseAlternative82(BaseModel):
)
-class QueryResponseAlternative86(BaseModel):
+class QueryResponseAlternative87(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -25185,7 +25416,7 @@ class QueryResponseAlternative86(BaseModel):
)
-class QueryResponseAlternative87(BaseModel):
+class QueryResponseAlternative88(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -25232,7 +25463,7 @@ class QueryResponseAlternative87(BaseModel):
)
-class QueryResponseAlternative88(BaseModel):
+class QueryResponseAlternative89(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -25289,7 +25520,7 @@ class QueryResponseAlternative88(BaseModel):
)
-class QueryResponseAlternative89(BaseModel):
+class QueryResponseAlternative90(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -25357,7 +25588,7 @@ class QueryResponseAlternative89(BaseModel):
)
-class QueryResponseAlternative90(BaseModel):
+class QueryResponseAlternative91(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -25404,7 +25635,7 @@ class QueryResponseAlternative90(BaseModel):
)
-class QueryResponseAlternative91(BaseModel):
+class QueryResponseAlternative92(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -25456,7 +25687,7 @@ class QueryResponseAlternative91(BaseModel):
)
-class QueryResponseAlternative92(BaseModel):
+class QueryResponseAlternative93(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -25503,7 +25734,7 @@ class QueryResponseAlternative92(BaseModel):
)
-class QueryResponseAlternative93(BaseModel):
+class QueryResponseAlternative94(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -25550,7 +25781,7 @@ class QueryResponseAlternative93(BaseModel):
)
-class QueryResponseAlternative94(BaseModel):
+class QueryResponseAlternative95(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -25597,7 +25828,7 @@ class QueryResponseAlternative94(BaseModel):
)
-class QueryResponseAlternative95(BaseModel):
+class QueryResponseAlternative96(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -25644,7 +25875,7 @@ class QueryResponseAlternative95(BaseModel):
)
-class QueryResponseAlternative96(BaseModel):
+class QueryResponseAlternative97(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -25695,7 +25926,7 @@ class QueryResponseAlternative96(BaseModel):
)
-class QueryResponseAlternative97(BaseModel):
+class QueryResponseAlternative98(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -25742,7 +25973,7 @@ class QueryResponseAlternative97(BaseModel):
)
-class QueryResponseAlternative98(BaseModel):
+class QueryResponseAlternative99(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -25789,7 +26020,7 @@ class QueryResponseAlternative98(BaseModel):
)
-class QueryResponseAlternative99(BaseModel):
+class QueryResponseAlternative100(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -25836,7 +26067,7 @@ class QueryResponseAlternative99(BaseModel):
)
-class QueryResponseAlternative100(BaseModel):
+class QueryResponseAlternative101(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -25883,7 +26114,7 @@ class QueryResponseAlternative100(BaseModel):
)
-class QueryResponseAlternative101(BaseModel):
+class QueryResponseAlternative102(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -25933,7 +26164,7 @@ class QueryResponseAlternative101(BaseModel):
)
-class QueryResponseAlternative102(BaseModel):
+class QueryResponseAlternative103(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -25980,7 +26211,7 @@ class QueryResponseAlternative102(BaseModel):
)
-class QueryResponseAlternative103(BaseModel):
+class QueryResponseAlternative104(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -26042,7 +26273,7 @@ class QueryResponseAlternative103(BaseModel):
)
-class QueryResponseAlternative104(BaseModel):
+class QueryResponseAlternative105(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -26089,7 +26320,7 @@ class QueryResponseAlternative104(BaseModel):
)
-class QueryResponseAlternative105(BaseModel):
+class QueryResponseAlternative106(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -26136,7 +26367,7 @@ class QueryResponseAlternative105(BaseModel):
)
-class QueryResponseAlternative106(BaseModel):
+class QueryResponseAlternative107(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -26183,7 +26414,7 @@ class QueryResponseAlternative106(BaseModel):
)
-class QueryResponseAlternative107(BaseModel):
+class QueryResponseAlternative108(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -26230,7 +26461,7 @@ class QueryResponseAlternative107(BaseModel):
)
-class QueryResponseAlternative108(BaseModel):
+class QueryResponseAlternative109(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -26277,7 +26508,7 @@ class QueryResponseAlternative108(BaseModel):
)
-class QueryResponseAlternative109(BaseModel):
+class QueryResponseAlternative110(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -26324,7 +26555,7 @@ class QueryResponseAlternative109(BaseModel):
)
-class QueryResponseAlternative110(BaseModel):
+class QueryResponseAlternative111(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -26371,7 +26602,7 @@ class QueryResponseAlternative110(BaseModel):
)
-class QueryResponseAlternative111(BaseModel):
+class QueryResponseAlternative112(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -26419,7 +26650,7 @@ class QueryResponseAlternative111(BaseModel):
)
-class QueryResponseAlternative112(BaseModel):
+class QueryResponseAlternative113(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -29956,6 +30187,24 @@ class MarketingAnalyticsCostFallback(BaseModel):
sourceIds: list[str] = Field(..., max_length=200, min_length=1)
+class MarketingAnalyticsRecommendationsQuery(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ dateRange: DateRange | None = None
+ kind: Literal["MarketingAnalyticsRecommendationsQuery"] = "MarketingAnalyticsRecommendationsQuery"
+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
+ response: MarketingAnalyticsRecommendationsQueryResponse | None = None
+ sources: list[MarketingAnalyticsRecommendationsSource] | None = Field(
+ default=None,
+ description=(
+ "Tables to read. Omit to read every synced Google Ads and Google Search Console source in the project."
+ ),
+ )
+ tags: QueryLogTags | None = None
+ version: float | None = Field(default=None, description="version of the node, used for schema migrations")
+
+
class MarketingAnalyticsRetentionQuery(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -30504,7 +30753,7 @@ class QueryResponseAlternative17(BaseModel):
)
-class QueryResponseAlternative42(BaseModel):
+class QueryResponseAlternative43(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -30561,7 +30810,7 @@ class QueryResponseAlternative42(BaseModel):
)
-class QueryResponseAlternative54(BaseModel):
+class QueryResponseAlternative55(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -32889,7 +33138,7 @@ class PathsV2ActorsQuery(BaseModel):
version: float | None = Field(default=None, description="version of the node, used for schema migrations")
-class QueryResponseAlternative67(BaseModel):
+class QueryResponseAlternative68(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -32947,8 +33196,8 @@ class QueryResponseAlternative(
| QueryResponseAlternative36
| QueryResponseAlternative37
| QueryResponseAlternative38
- | Any
| QueryResponseAlternative39
+ | Any
| QueryResponseAlternative40
| QueryResponseAlternative41
| QueryResponseAlternative42
@@ -32965,7 +33214,7 @@ class QueryResponseAlternative(
| QueryResponseAlternative53
| QueryResponseAlternative54
| QueryResponseAlternative55
- | QueryResponseAlternative57
+ | QueryResponseAlternative56
| QueryResponseAlternative58
| QueryResponseAlternative59
| QueryResponseAlternative60
@@ -32974,7 +33223,7 @@ class QueryResponseAlternative(
| QueryResponseAlternative63
| QueryResponseAlternative64
| QueryResponseAlternative65
- | QueryResponseAlternative67
+ | QueryResponseAlternative66
| QueryResponseAlternative68
| QueryResponseAlternative69
| QueryResponseAlternative70
@@ -32990,7 +33239,7 @@ class QueryResponseAlternative(
| QueryResponseAlternative80
| QueryResponseAlternative81
| QueryResponseAlternative82
- | QueryResponseAlternative85
+ | QueryResponseAlternative83
| QueryResponseAlternative86
| QueryResponseAlternative87
| QueryResponseAlternative88
@@ -33018,6 +33267,7 @@ class QueryResponseAlternative(
| QueryResponseAlternative110
| QueryResponseAlternative111
| QueryResponseAlternative112
+ | QueryResponseAlternative113
]
):
root: (
@@ -33059,8 +33309,8 @@ class QueryResponseAlternative(
| QueryResponseAlternative36
| QueryResponseAlternative37
| QueryResponseAlternative38
- | Any
| QueryResponseAlternative39
+ | Any
| QueryResponseAlternative40
| QueryResponseAlternative41
| QueryResponseAlternative42
@@ -33077,7 +33327,7 @@ class QueryResponseAlternative(
| QueryResponseAlternative53
| QueryResponseAlternative54
| QueryResponseAlternative55
- | QueryResponseAlternative57
+ | QueryResponseAlternative56
| QueryResponseAlternative58
| QueryResponseAlternative59
| QueryResponseAlternative60
@@ -33086,7 +33336,7 @@ class QueryResponseAlternative(
| QueryResponseAlternative63
| QueryResponseAlternative64
| QueryResponseAlternative65
- | QueryResponseAlternative67
+ | QueryResponseAlternative66
| QueryResponseAlternative68
| QueryResponseAlternative69
| QueryResponseAlternative70
@@ -33102,7 +33352,7 @@ class QueryResponseAlternative(
| QueryResponseAlternative80
| QueryResponseAlternative81
| QueryResponseAlternative82
- | QueryResponseAlternative85
+ | QueryResponseAlternative83
| QueryResponseAlternative86
| QueryResponseAlternative87
| QueryResponseAlternative88
@@ -33130,6 +33380,7 @@ class QueryResponseAlternative(
| QueryResponseAlternative110
| QueryResponseAlternative111
| QueryResponseAlternative112
+ | QueryResponseAlternative113
)
@@ -34226,6 +34477,7 @@ class HogQLAutocomplete(BaseModel):
| MarketingAnalyticsAttributionPathsQuery
| MarketingAnalyticsRetentionQuery
| MarketingAnalyticsSearchQuery
+ | MarketingAnalyticsRecommendationsQuery
| WebOverviewQuery
| WebStatsTableQuery
| WebExternalClicksTableQuery
@@ -34362,6 +34614,7 @@ class HogQLMetadata(BaseModel):
| MarketingAnalyticsAttributionPathsQuery
| MarketingAnalyticsRetentionQuery
| MarketingAnalyticsSearchQuery
+ | MarketingAnalyticsRecommendationsQuery
| WebOverviewQuery
| WebStatsTableQuery
| WebExternalClicksTableQuery
@@ -34515,6 +34768,7 @@ class MaxInsightContext(BaseModel):
| MarketingAnalyticsAttributionPathsQuery
| MarketingAnalyticsRetentionQuery
| MarketingAnalyticsSearchQuery
+ | MarketingAnalyticsRecommendationsQuery
| DataVisualizationNode
| BIVisualizationNode
| DataTableNode
@@ -34659,6 +34913,7 @@ class QueryRequest(BaseModel):
| MarketingAnalyticsAttributionPathsQuery
| MarketingAnalyticsRetentionQuery
| MarketingAnalyticsSearchQuery
+ | MarketingAnalyticsRecommendationsQuery
| DataVisualizationNode
| BIVisualizationNode
| DataTableNode
@@ -34796,6 +35051,7 @@ class QuerySchemaRoot(
| MarketingAnalyticsAttributionPathsQuery
| MarketingAnalyticsRetentionQuery
| MarketingAnalyticsSearchQuery
+ | MarketingAnalyticsRecommendationsQuery
| DataVisualizationNode
| BIVisualizationNode
| DataTableNode
@@ -34903,6 +35159,7 @@ class QuerySchemaRoot(
| MarketingAnalyticsAttributionPathsQuery
| MarketingAnalyticsRetentionQuery
| MarketingAnalyticsSearchQuery
+ | MarketingAnalyticsRecommendationsQuery
| DataVisualizationNode
| BIVisualizationNode
| DataTableNode
@@ -35015,6 +35272,7 @@ class QueryUpgradeRequest(BaseModel):
| MarketingAnalyticsAttributionPathsQuery
| MarketingAnalyticsRetentionQuery
| MarketingAnalyticsSearchQuery
+ | MarketingAnalyticsRecommendationsQuery
| DataVisualizationNode
| BIVisualizationNode
| DataTableNode
@@ -35127,6 +35385,7 @@ class QueryUpgradeResponse(BaseModel):
| MarketingAnalyticsAttributionPathsQuery
| MarketingAnalyticsRetentionQuery
| MarketingAnalyticsSearchQuery
+ | MarketingAnalyticsRecommendationsQuery
| DataVisualizationNode
| BIVisualizationNode
| DataTableNode
@@ -35284,6 +35543,7 @@ class VisualizationArtifactContent(BaseModel):
| MarketingAnalyticsAttributionPathsQuery
| MarketingAnalyticsRetentionQuery
| MarketingAnalyticsSearchQuery
+ | MarketingAnalyticsRecommendationsQuery
| DataVisualizationNode
| BIVisualizationNode
| DataTableNode
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index 6bc0e306bac7..28ec158898fe 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -2147,6 +2147,41 @@ class MarketingAnalyticsOrderByEnum(StrEnum):
DESC = "DESC"
+class MarketingAnalyticsRecommendationImpactDirection(StrEnum):
+ SAVE = "save"
+ GAIN = "gain"
+ INVEST = "invest"
+ KEEP = "keep"
+
+
+class MarketingAnalyticsRecommendationImpactType(StrEnum):
+ MEASURED = "measured"
+ ESTIMATED = "estimated"
+
+
+class MarketingAnalyticsRecommendationLevel(StrEnum):
+ CAMPAIGN = "campaign"
+ SEARCH_TERM = "search_term"
+
+
+class MarketingAnalyticsRecommendationRule(StrEnum):
+ BUDGET_CONSTRAINED = "budget_constrained"
+ BRAND_LEAK = "brand_leak"
+ SCALE_CAMPAIGN = "scale_campaign"
+ REVIEW_CAMPAIGN = "review_campaign"
+ POLICY_LIMITED = "policy_limited"
+ BRAND_OVERLAP = "brand_overlap"
+ CONTENT_GAP = "content_gap"
+ KEYWORD_GAP = "keyword_gap"
+ SPEND_WITHOUT_CONVERSIONS = "spend_without_conversions"
+ STRIKING_DISTANCE = "striking_distance"
+
+
+class MarketingAnalyticsRecommendationsSourceType(StrEnum):
+ GOOGLE_ADS = "GoogleAds"
+ GOOGLE_SEARCH_CONSOLE = "GoogleSearchConsole"
+
+
class MarketingAnalyticsRetentionInterval(StrEnum):
DAY = "day"
WEEK = "week"
@@ -2448,6 +2483,7 @@ class NodeKind(StrEnum):
MARKETING_ANALYTICS_ATTRIBUTION_PATHS_QUERY = "MarketingAnalyticsAttributionPathsQuery"
MARKETING_ANALYTICS_RETENTION_QUERY = "MarketingAnalyticsRetentionQuery"
MARKETING_ANALYTICS_SEARCH_QUERY = "MarketingAnalyticsSearchQuery"
+ MARKETING_ANALYTICS_RECOMMENDATIONS_QUERY = "MarketingAnalyticsRecommendationsQuery"
EXPERIMENT_METRIC = "ExperimentMetric"
EXPERIMENT_QUERY = "ExperimentQuery"
EXPERIMENT_EXPOSURE_QUERY = "ExperimentExposureQuery"
diff --git a/products/marketing_analytics/backend/hogql_queries/marketing_recommendations.py b/products/marketing_analytics/backend/hogql_queries/marketing_recommendations.py
new file mode 100644
index 000000000000..2a382a5a829d
--- /dev/null
+++ b/products/marketing_analytics/backend/hogql_queries/marketing_recommendations.py
@@ -0,0 +1,759 @@
+import re
+from collections import defaultdict
+from collections.abc import Iterable
+from typing import Literal
+
+import tldextract
+
+from posthog.schema import MarketingAnalyticsRecommendation, MarketingAnalyticsRecommendationRule
+
+from posthog.dataclasses import frozen
+
+PER_RULE_LIMIT = 10
+# Share of impressions that become clicks once a page reaches the top 3 organic results. A rough industry figure.
+TOP3_CTR = 0.15
+# Below this, someone else's ad often takes the first spot on your own brand searches.
+BRAND_DEFENSE_ABSOLUTE_TOP = 0.9
+INACTIVE_STATUSES = frozenset({"PAUSED", "ENDED", "REMOVED"})
+POLICY_REASONS = frozenset(
+ {
+ "HAS_ADS_LIMITED_BY_POLICY",
+ "HAS_ADS_DISAPPROVED",
+ # Performance Max reports policy limits on its asset groups instead of its ads.
+ "HAS_ASSET_GROUPS_LIMITED_BY_POLICY",
+ "HAS_ASSET_GROUPS_DISAPPROVED",
+ }
+)
+# Modifiers that match almost any search, so they say nothing about whether a query fits the account.
+GENERIC_WORDS = frozenset(
+ {
+ "app",
+ "apps",
+ "best",
+ "free",
+ "online",
+ "open",
+ "platform",
+ "site",
+ "software",
+ "source",
+ "tool",
+ "tools",
+ "top",
+ "web",
+ "website",
+ }
+)
+# Share of the searches mentioning a name that must be comparisons for it to count as a competitor.
+COMPETITOR_COMPARISON_SHARE = 0.07
+COMPARISON = re.compile(r"(alternatives?|competitors?|(^| )vs\.?( |$))")
+COMPETITOR_PATTERNS = (
+ re.compile(r"^([a-z0-9.-]+) (?:alternatives?|competitors?|vs\.?)( |$)"),
+ re.compile(r"(?:alternatives? to|vs\.?) ([a-z0-9.-]+)"),
+)
+DOMAIN_SUFFIX = re.compile(r"\.(com|io|co|ai|app|net|org)$")
+SITE_HOST = re.compile(r"^(?:sc-domain:|https?://)([a-z0-9.-]+)")
+MIN_BRAND_LENGTH = 3
+# The bundled public suffix snapshot, so parsing a site never fetches the list over the network.
+DOMAIN_PARTS = tldextract.TLDExtract(suffix_list_urls=(), include_psl_private_domains=True)
+
+Direction = Literal["save", "gain", "invest", "keep"]
+# Google Ads KeywordMatchType values, for tables that stored the enum number.
+MATCH_TYPES = {"2": "EXACT", "3": "PHRASE", "4": "BROAD"}
+
+
+@frozen
+class CampaignStats:
+ id: str
+ name: str
+ channel_type: str | None
+ primary_status: str | None
+ status_reasons: tuple[str, ...]
+ daily_budget: float | None
+ recommended_daily_budget: float | None
+ cost: float
+ conversions: float
+ impression_share: float | None
+ lost_to_budget: float | None
+ lost_to_rank: float | None
+ budget_id: str | None = None
+
+
+@frozen
+class SearchTermStats:
+ term: str
+ campaign_id: str
+ clicks: float
+ impressions: float
+ cost: float
+ conversions: float
+ status: str
+ absolute_top_percentage: float | None = None
+
+
+@frozen
+class OrganicQueryStats:
+ query: str
+ clicks: float
+ impressions: float
+ position: float
+
+
+@frozen
+class TermKeywordStats:
+ term: str
+ keyword: str
+ match_type: str
+ cost: float
+
+
+@frozen
+class RecommendationInputs:
+ campaigns: tuple[CampaignStats, ...]
+ search_terms: tuple[SearchTermStats, ...]
+ organic_queries: tuple[OrganicQueryStats, ...]
+ site_urls: tuple[str, ...]
+ currency: str | None
+ days: int
+ term_keywords: tuple[TermKeywordStats, ...] = ()
+
+
+@frozen
+class _Term:
+ term: str
+ clicks: float
+ cost: float
+ conversions: float
+ status: str
+ top_campaign_id: str
+ organic: OrganicQueryStats | None
+ absolute_top: float | None
+
+
+@frozen
+class _Spend:
+ cost: float
+ conversions: float
+
+
+@frozen
+class _BrandSpend:
+ cost: float
+ conversions: float
+ top_term: str
+
+
+def _site_brand(site_url: str) -> str | None:
+ match = SITE_HOST.match(site_url.lower())
+ if not match:
+ return None
+ # A URL-prefix property can be app.example.com or blog.example.com, so the brand is the registrable label.
+ brand = DOMAIN_PARTS(match.group(1).strip(".")).domain
+ return brand if len(brand) >= MIN_BRAND_LENGTH else None
+
+
+def brands_from_site_urls(site_urls: Iterable[str]) -> frozenset[str]:
+ return frozenset(brand for url in site_urls if (brand := _site_brand(url)))
+
+
+def _merge_organic(queries: Iterable[OrganicQueryStats]) -> dict[str, OrganicQueryStats]:
+ merged: dict[str, OrganicQueryStats] = {}
+ for query in queries:
+ current = merged.get(query.query)
+ if current is None:
+ merged[query.query] = query
+ continue
+ impressions = current.impressions + query.impressions
+ merged[query.query] = OrganicQueryStats(
+ query=query.query,
+ clicks=current.clicks + query.clicks,
+ impressions=impressions,
+ position=(current.position * current.impressions + query.position * query.impressions) / impressions
+ if impressions
+ else current.position,
+ )
+ return merged
+
+
+def recommend(inputs: RecommendationInputs) -> list[MarketingAnalyticsRecommendation]:
+ return _Recommender(inputs).run()
+
+
+class _Recommender:
+ def __init__(self, inputs: RecommendationInputs) -> None:
+ self.inputs = inputs
+ self.per_month = 30 / max(inputs.days, 1)
+ self.brands = brands_from_site_urls(inputs.site_urls)
+ self.campaigns = {campaign.id: campaign for campaign in inputs.campaigns}
+ self.organic = _merge_organic(inputs.organic_queries)
+ self.term_cost_by_campaign: dict[str, float] = defaultdict(float)
+ for row in inputs.search_terms:
+ self.term_cost_by_campaign[row.campaign_id] += row.cost
+ self.terms = self._aggregate_terms()
+ self.brand_terms = {term.term for term in self.terms.values() if self._is_brand(term)}
+ self.top_keyword: dict[str, TermKeywordStats] = {}
+ for keyword_row in inputs.term_keywords:
+ current = self.top_keyword.get(keyword_row.term)
+ if current is None or keyword_row.cost > current.cost:
+ self.top_keyword[keyword_row.term] = keyword_row
+
+ def run(self) -> list[MarketingAnalyticsRecommendation]:
+ campaign_rules = sorted(self._campaign_rules(), key=lambda rec: -(rec.impact or 0))
+ return campaign_rules + self._search_term_rules()
+
+ # Campaign rules
+
+ def _campaign_rules(self) -> list[MarketingAnalyticsRecommendation]:
+ recommendations: list[MarketingAnalyticsRecommendation] = []
+ brand_spend = self._brand_spend_by_campaign()
+ nonbrand = {
+ campaign.id: self._nonbrand_totals(campaign, brand_spend.get(campaign.id))
+ for campaign in self.campaigns.values()
+ }
+ search_campaigns = [
+ campaign
+ for campaign in self.campaigns.values()
+ if campaign.channel_type == "SEARCH" and not self._is_brand_campaign(campaign, brand_spend)
+ ]
+ nonbrand_cost = sum(nonbrand[campaign.id].cost for campaign in search_campaigns)
+ nonbrand_conversions = sum(nonbrand[campaign.id].conversions for campaign in search_campaigns)
+ nonbrand_cpa = nonbrand_cost / nonbrand_conversions if nonbrand_conversions else None
+ search_cost = sum(campaign.cost for campaign in self.campaigns.values() if campaign.channel_type == "SEARCH")
+
+ constrained_budgets: set[str] = set()
+ for campaign in self.campaigns.values():
+ if campaign.primary_status in INACTIVE_STATUSES:
+ continue
+ budget = self._budget_constrained(campaign)
+ # Campaigns that share a budget each report it as constrained, so one row covers the shared budget.
+ if budget and not (campaign.budget_id and campaign.budget_id in constrained_budgets):
+ recommendations.append(budget)
+ if campaign.budget_id:
+ constrained_budgets.add(campaign.budget_id)
+ if POLICY_REASONS.intersection(campaign.status_reasons):
+ recommendations.append(
+ self._recommendation(
+ MarketingAnalyticsRecommendationRule.POLICY_LIMITED,
+ "campaign",
+ campaign.name,
+ "Check the affected ads in Policy manager",
+ "Some ads or asset groups are limited or disapproved by Google policy, which cuts the campaign's reach.",
+ None,
+ "gain",
+ "measured",
+ )
+ )
+
+ has_brand_campaign = any(self._is_brand_campaign(c, brand_spend) for c in self.campaigns.values())
+ for campaign in self.campaigns.values():
+ if campaign.channel_type != "PERFORMANCE_MAX" or campaign.primary_status in INACTIVE_STATUSES:
+ continue
+ leak = brand_spend.get(campaign.id)
+ if leak and leak.cost >= 0.05 * max(self._term_cost(campaign.id), 1):
+ recommendations.append(self._brand_leak(campaign, leak, has_brand_campaign))
+ if campaign.conversions > 0 and (campaign.lost_to_rank or 0) >= 0.4:
+ recommendations.append(self._performance_max_rank(campaign))
+
+ for campaign in search_campaigns:
+ if campaign.primary_status in INACTIVE_STATUSES:
+ continue
+ leak = brand_spend.get(campaign.id)
+ if leak and leak.cost >= 0.05 * max(self._term_cost(campaign.id), 1):
+ recommendations.append(self._brand_leak(campaign, leak, has_brand_campaign))
+ totals = nonbrand[campaign.id]
+ cost, conversions = totals.cost, totals.conversions
+ cpa = cost / conversions if conversions else None
+ lost = (campaign.lost_to_budget or 0) + (campaign.lost_to_rank or 0)
+ if nonbrand_cpa and cpa and conversions >= 5 and cpa <= nonbrand_cpa and lost >= 0.4:
+ recommendations.append(self._scale(campaign, cpa, nonbrand_cpa, lost))
+ elif (
+ nonbrand_cpa
+ and search_cost
+ and campaign.cost >= 0.05 * search_cost
+ and (cpa is None or cpa >= 3 * nonbrand_cpa)
+ ):
+ recommendations.append(self._review(campaign, cpa, nonbrand_cpa))
+ return recommendations
+
+ def _budget_constrained(self, campaign: CampaignStats) -> MarketingAnalyticsRecommendation | None:
+ budget, recommended = campaign.daily_budget, campaign.recommended_daily_budget
+ if (
+ "BUDGET_CONSTRAINED" not in campaign.status_reasons
+ or not budget
+ or not recommended
+ or recommended <= budget
+ ):
+ return None
+ lost = (
+ f"{campaign.lost_to_budget:.0%} of eligible impressions are lost because the budget runs out. "
+ if campaign.lost_to_budget
+ else ""
+ )
+ return self._recommendation(
+ MarketingAnalyticsRecommendationRule.BUDGET_CONSTRAINED,
+ "campaign",
+ campaign.name,
+ f"Raise the daily budget from {self._money(budget)} to {self._money(recommended)}",
+ f"Limited by budget. {lost}{self._money(recommended)} a day is Google's recommended budget.",
+ (recommended - budget) * 30,
+ "invest",
+ "estimated",
+ )
+
+ def _brand_leak(
+ self, campaign: CampaignStats, leak: _BrandSpend, has_brand_campaign: bool
+ ) -> MarketingAnalyticsRecommendation:
+ cost, conversions, top_term = leak.cost, leak.conversions, leak.top_term
+ share = cost / max(self._term_cost(campaign.id), 1)
+ brand = next((brand for brand in self.brands if brand in top_term.replace(" ", "")), top_term)
+ # Performance Max takes no negative keywords; brand exclusions are its equivalent.
+ action = (
+ f'Add a brand exclusion for "{brand}"'
+ if campaign.channel_type == "PERFORMANCE_MAX"
+ else f'Add "{brand}" as a negative keyword'
+ )
+ follow_up = (
+ "Your brand campaign can serve them at a lower cost."
+ if has_brand_campaign
+ else "People who search your brand often find you without an ad."
+ )
+ return self._recommendation(
+ MarketingAnalyticsRecommendationRule.BRAND_LEAK,
+ "campaign",
+ campaign.name,
+ action,
+ f'{share:.0%} of its search term spend goes to brand searches such as "{top_term}", '
+ f"with {conversions:.0f} conversions. {follow_up}",
+ cost * self.per_month,
+ "save",
+ "measured",
+ )
+
+ def _scale(
+ self, campaign: CampaignStats, cpa: float, nonbrand_cpa: float, lost: float
+ ) -> MarketingAnalyticsRecommendation:
+ budget_bound = (campaign.lost_to_budget or 0) >= (campaign.lost_to_rank or 0)
+ extra = campaign.cost * min(lost / max(campaign.impression_share or 0.1, 0.1), 1)
+ return self._recommendation(
+ MarketingAnalyticsRecommendationRule.SCALE_CAMPAIGN,
+ "campaign",
+ campaign.name,
+ "Raise the budget" if budget_bound else "Raise bids or improve ad quality",
+ f"Non-brand CPA of {self._money(cpa)}, against {self._money(nonbrand_cpa)} across non-brand campaigns. "
+ f"It loses {campaign.lost_to_budget or 0:.0%} of impressions to budget "
+ f"and {campaign.lost_to_rank or 0:.0%} to ad rank.",
+ extra * self.per_month,
+ "invest",
+ "estimated",
+ )
+
+ def _performance_max_rank(self, campaign: CampaignStats) -> MarketingAnalyticsRecommendation:
+ lost = (campaign.lost_to_budget or 0) + (campaign.lost_to_rank or 0)
+ extra = campaign.cost * min(lost / max(campaign.impression_share or 0.1, 0.1), 1)
+ return self._recommendation(
+ MarketingAnalyticsRecommendationRule.SCALE_CAMPAIGN,
+ "campaign",
+ campaign.name,
+ "Raise the target CPA or improve its asset groups",
+ f"Converts at a CPA of {self._money(campaign.cost / campaign.conversions)}. "
+ f"It loses {campaign.lost_to_rank or 0:.0%} of eligible search impressions to ad rank "
+ f"and {campaign.lost_to_budget or 0:.0%} to budget, so most missed searches go to better-ranked ads.",
+ extra * self.per_month,
+ "invest",
+ "estimated",
+ )
+
+ def _review(
+ self, campaign: CampaignStats, cpa: float | None, nonbrand_cpa: float
+ ) -> MarketingAnalyticsRecommendation:
+ reason = (
+ f"Spent {self._money(campaign.cost)} with no non-brand conversions."
+ if cpa is None
+ else f"Non-brand CPA of {self._money(cpa)}, {cpa / nonbrand_cpa:.1f}x the non-brand average "
+ f"of {self._money(nonbrand_cpa)}."
+ )
+ return self._recommendation(
+ MarketingAnalyticsRecommendationRule.REVIEW_CAMPAIGN,
+ "campaign",
+ campaign.name,
+ "Review bids, ads and landing page, or pause",
+ reason,
+ campaign.cost * self.per_month,
+ "save",
+ "measured",
+ )
+
+ # Search term rules
+
+ def _search_term_rules(self) -> list[MarketingAnalyticsRecommendation]:
+ if not self.terms:
+ return []
+ terms = list(self.terms.values())
+ paid_cost = sum(term.cost for term in terms)
+ paid_conversions = sum(term.conversions for term in terms)
+ cpa = paid_cost / paid_conversions if paid_conversions else None
+ unranked = [term for term in terms if not term.organic or term.organic.position > 3]
+ unranked_clicks = sum(term.clicks for term in unranked)
+ average_cpc = sum(term.cost for term in unranked) / unranked_clicks if unranked_clicks else None
+ vocabulary = self._vocabulary(terms, cpa)
+ competitors = self._competitor_names()
+
+ rules: dict[MarketingAnalyticsRecommendationRule, list[MarketingAnalyticsRecommendation]] = defaultdict(list)
+ if cpa:
+ rules[MarketingAnalyticsRecommendationRule.BRAND_OVERLAP] = self._brand_overlap(terms, cpa)
+ rules[MarketingAnalyticsRecommendationRule.CONTENT_GAP] = [
+ self._term_recommendation(
+ MarketingAnalyticsRecommendationRule.CONTENT_GAP,
+ term,
+ "Create or improve a page for this search",
+ f"Converts in Ads at a CPA of {self._money(term.cost / term.conversions)} "
+ f"(account {self._money(cpa)}), but "
+ + (
+ f"ranks #{term.organic.position:.1f} organically"
+ if term.organic
+ else "does not rank organically"
+ ),
+ term.conversions * cpa,
+ "gain",
+ "measured",
+ )
+ for term in terms
+ if term.term not in self.brand_terms
+ and term.conversions >= 2
+ and term.cost / term.conversions <= cpa
+ and (not term.organic or term.organic.position > 10)
+ ]
+ rules[MarketingAnalyticsRecommendationRule.SPEND_WITHOUT_CONVERSIONS] = [
+ self._term_recommendation(
+ MarketingAnalyticsRecommendationRule.SPEND_WITHOUT_CONVERSIONS,
+ term,
+ self._no_conversion_action(term, competitors),
+ f"Spent {self._money(term.cost)} ({term.cost / cpa:.1f}x the account CPA) "
+ f"on {term.clicks:.0f} clicks with no conversions",
+ term.cost,
+ "save",
+ "measured",
+ )
+ for term in terms
+ if term.term not in self.brand_terms
+ and term.conversions == 0
+ and term.cost >= 2 * cpa
+ and term.status in ("NONE", "")
+ and self._serving(term)
+ ]
+ if self.organic:
+ if average_cpc:
+ rules[MarketingAnalyticsRecommendationRule.KEYWORD_GAP] = self._keyword_gap(
+ average_cpc, vocabulary, competitors
+ )
+ rules[MarketingAnalyticsRecommendationRule.STRIKING_DISTANCE] = [
+ self._term_recommendation(
+ MarketingAnalyticsRecommendationRule.STRIKING_DISTANCE,
+ term,
+ "Improve the ranking page to reach the top 3",
+ f"Position {term.organic.position:.1f} with {term.organic.impressions:.0f} impressions "
+ f"and {term.organic.clicks:.0f} clicks. Paid CPC {self._money(term.cost / term.clicks)}",
+ max(term.organic.impressions * TOP3_CTR - term.organic.clicks, 0) * term.cost / term.clicks,
+ "gain",
+ "estimated",
+ )
+ for term in terms
+ if term.organic
+ and term.term not in self.brand_terms
+ and 5 <= term.organic.position <= 20
+ and term.clicks >= 5
+ and term.term not in competitors
+ ]
+
+ ordered: list[MarketingAnalyticsRecommendation] = []
+ for rule in (
+ MarketingAnalyticsRecommendationRule.BRAND_OVERLAP,
+ MarketingAnalyticsRecommendationRule.CONTENT_GAP,
+ MarketingAnalyticsRecommendationRule.KEYWORD_GAP,
+ MarketingAnalyticsRecommendationRule.SPEND_WITHOUT_CONVERSIONS,
+ MarketingAnalyticsRecommendationRule.STRIKING_DISTANCE,
+ ):
+ ordered.extend(sorted(rules.get(rule, []), key=lambda rec: -(rec.impact or 0))[:PER_RULE_LIMIT])
+ return ordered
+
+ def _no_conversion_action(self, term: _Term, competitors: set[str]) -> str:
+ keyword = self.top_keyword.get(term.term)
+ match_type = MATCH_TYPES.get(keyword.match_type, keyword.match_type).lower() if keyword else ""
+ if self._mentions(term.term, competitors):
+ matched_by = f' It matched the keyword "{keyword.keyword}" ({match_type} match).' if keyword else ""
+ return f"Competitor term: decide whether conquesting is worth it.{matched_by}"
+ if not keyword:
+ return "Review the bid and landing page, or add it as a negative"
+ if match_type in ("broad", "phrase") and keyword.keyword.lower() != term.term:
+ return f'Add it as a negative, or change the keyword "{keyword.keyword}" from {match_type} to exact match'
+ return f'Review the keyword "{keyword.keyword}" ({match_type} match) and its landing page, or pause it'
+
+ def _brand_overlap(self, terms: list[_Term], cpa: float) -> list[MarketingAnalyticsRecommendation]:
+ recommendations = []
+ for term in terms:
+ organic = term.organic
+ if (
+ term.term not in self.brand_terms
+ or not organic
+ or organic.position > 3
+ or term.cost < cpa
+ or not self._serving(term)
+ ):
+ continue
+ reason = (
+ f"Ranks #{organic.position:.1f} organically with {organic.clicks:.0f} clicks. "
+ f"Ads cost {self._money(term.cost)} for {term.clicks:.0f} clicks."
+ )
+ # Another ad above yours on your own brand search means someone bids on it, so pausing hands them the top spot.
+ if term.absolute_top is not None and term.absolute_top < BRAND_DEFENSE_ABSOLUTE_TOP:
+ recommendations.append(
+ self._term_recommendation(
+ MarketingAnalyticsRecommendationRule.BRAND_OVERLAP,
+ term,
+ "Keep the ad: another ad often shows above yours",
+ f"{reason} When your ad shows, another ad is above it {1 - term.absolute_top:.0%} of the time.",
+ term.cost,
+ "keep",
+ "measured",
+ )
+ )
+ elif term.absolute_top is None:
+ # Without the top position, a competitor bidding on the brand is invisible, so pausing is not safe to suggest.
+ recommendations.append(
+ self._term_recommendation(
+ MarketingAnalyticsRecommendationRule.BRAND_OVERLAP,
+ term,
+ "Check whether other ads show above yours before you test pausing",
+ f"{reason} Top position data for this term is not synced yet.",
+ term.cost,
+ "save",
+ "estimated",
+ )
+ )
+ else:
+ recommendations.append(
+ self._term_recommendation(
+ MarketingAnalyticsRecommendationRule.BRAND_OVERLAP,
+ term,
+ "Test pausing the ad in alternating weeks and compare total clicks",
+ f"{reason} Your ad is at the very top {term.absolute_top:.0%} of the time it shows.",
+ term.cost,
+ "save",
+ "measured",
+ )
+ )
+ return recommendations
+
+ def _keyword_gap(
+ self, average_cpc: float, vocabulary: set[str], competitors: set[str]
+ ) -> list[MarketingAnalyticsRecommendation]:
+ has_search = any(
+ campaign.channel_type == "SEARCH" and campaign.primary_status not in INACTIVE_STATUSES
+ for campaign in self.campaigns.values()
+ )
+ impressions = sorted(query.impressions for query in self.organic.values())
+ threshold = impressions[int(len(impressions) * 0.95)] if impressions else 0
+ recommendations = []
+ for query in self.organic.values():
+ if query.query in self.terms or query.position <= 10 or query.impressions < threshold:
+ continue
+ if self._is_brand_query(query.query, query, 0) or self._mentions(query.query, competitors):
+ continue
+ words = [word for word in query.query.split() if len(word) >= 3 and word not in GENERIC_WORDS]
+ matched = [word for word in words if word in vocabulary]
+ if not words or len(matched) < len(words):
+ continue
+ recommendations.append(
+ self._recommendation(
+ MarketingAnalyticsRecommendationRule.KEYWORD_GAP,
+ "search_term",
+ query.query,
+ "Add as a keyword in Google Ads" if has_search else "Add as a search theme in Performance Max",
+ f"{query.impressions:.0f} organic impressions at position {query.position:.1f}, not bought. "
+ "Its words all appear in paid searches that convert at or below the account CPA",
+ query.impressions * TOP3_CTR * average_cpc * self.per_month,
+ "invest",
+ "estimated",
+ )
+ )
+ return recommendations
+
+ # Helpers
+
+ def _aggregate_terms(self) -> dict[str, _Term]:
+ totals: dict[str, list[float]] = defaultdict(lambda: [0.0, 0.0, 0.0])
+ statuses: dict[str, str] = {}
+ cost_by_campaign: dict[str, dict[str, float]] = defaultdict(lambda: defaultdict(float))
+ top_impressions: dict[str, list[float]] = defaultdict(lambda: [0.0, 0.0])
+ for row in self.inputs.search_terms:
+ total = totals[row.term]
+ total[0] += row.clicks
+ total[1] += row.cost
+ total[2] += row.conversions
+ statuses.setdefault(row.term, row.status)
+ cost_by_campaign[row.term][row.campaign_id] += row.cost
+ if row.absolute_top_percentage is not None and row.impressions:
+ top_impressions[row.term][0] += row.absolute_top_percentage * row.impressions
+ top_impressions[row.term][1] += row.impressions
+ return {
+ term: _Term(
+ term=term,
+ clicks=clicks,
+ cost=cost,
+ conversions=conversions,
+ status=statuses[term],
+ top_campaign_id=max(cost_by_campaign[term], key=lambda campaign: cost_by_campaign[term][campaign]),
+ organic=self.organic.get(term),
+ absolute_top=top[0] / top[1] if (top := top_impressions.get(term)) and top[1] else None,
+ )
+ for term, (clicks, cost, conversions) in totals.items()
+ }
+
+ def _names_brand(self, query: str) -> bool:
+ compact = query.replace(" ", "")
+ return any(brand in compact for brand in self.brands)
+
+ def _is_brand(self, term: _Term) -> bool:
+ return self._is_brand_query(term.term, term.organic, term.clicks)
+
+ def _is_brand_query(self, query: str, organic: OrganicQueryStats | None, paid_clicks: float) -> bool:
+ if self._names_brand(query):
+ return True
+ # Navigational behavior also catches misspellings of the brand. Paid clicks count too, since
+ # bidding on the brand pulls clicks away from the organic result.
+ return bool(
+ organic
+ and organic.position < 2.5
+ and organic.impressions >= 50
+ and (organic.clicks + paid_clicks) / organic.impressions > 0.3
+ )
+
+ def _brand_spend_by_campaign(self) -> dict[str, _BrandSpend]:
+ spend: dict[str, list[float]] = defaultdict(lambda: [0.0, 0.0])
+ top: dict[str, tuple[float, str]] = {}
+ for row in self.inputs.search_terms:
+ if row.term not in self.brand_terms:
+ continue
+ spend[row.campaign_id][0] += row.cost
+ spend[row.campaign_id][1] += row.conversions
+ if row.cost > top.get(row.campaign_id, (-1.0, ""))[0]:
+ top[row.campaign_id] = (row.cost, row.term)
+ return {
+ campaign: _BrandSpend(cost=cost, conversions=conversions, top_term=top[campaign][1])
+ for campaign, (cost, conversions) in spend.items()
+ }
+
+ def _is_brand_campaign(self, campaign: CampaignStats, brand_spend: dict[str, _BrandSpend]) -> bool:
+ spend = brand_spend.get(campaign.id)
+ return spend is not None and spend.cost >= 0.5 * max(self._term_cost(campaign.id), 1)
+
+ def _term_cost(self, campaign_id: str) -> float:
+ return self.term_cost_by_campaign.get(campaign_id, 0.0)
+
+ def _nonbrand_totals(self, campaign: CampaignStats, leak: _BrandSpend | None) -> _Spend:
+ if not leak:
+ return _Spend(cost=campaign.cost, conversions=campaign.conversions)
+ return _Spend(
+ cost=max(campaign.cost - leak.cost, 0), conversions=max(campaign.conversions - leak.conversions, 0)
+ )
+
+ def _vocabulary(self, terms: list[_Term], cpa: float | None) -> set[str]:
+ # Words from non-brand terms that convert at or below the account CPA: the account's own
+ # definition of a relevant search. Terms that convert only at a high cost do not count.
+ return {
+ word
+ for term in terms
+ if term.conversions > 0
+ and term.term not in self.brand_terms
+ and (cpa is None or term.cost / term.conversions <= cpa)
+ for word in term.term.split()
+ if len(word) >= 3 and word not in GENERIC_WORDS
+ }
+
+ def _competitor_names(self) -> set[str]:
+ queries = set(self.organic) | set(self.terms)
+ comparisons: dict[str, int] = defaultdict(int)
+ appearances: dict[str, int] = defaultdict(int)
+ for query in queries:
+ for word in set(query.split()):
+ appearances[DOMAIN_SUFFIX.sub("", word)] += 1
+ if self._names_brand(query):
+ continue
+ for pattern in COMPETITOR_PATTERNS:
+ match = pattern.search(query)
+ if match:
+ comparisons[DOMAIN_SUFFIX.sub("", match.group(1))] += 1
+ # A competitor shows up in two comparison searches, is searched on its own, and a fair share of the
+ # searches that mention it are comparisons. Category words like "analytics" appear in thousands of
+ # searches and almost never as the subject of a comparison.
+ return {
+ name
+ for name, count in comparisons.items()
+ if count >= 2
+ and len(name) >= 3
+ and name in queries
+ and name not in self.brands
+ and name not in GENERIC_WORDS
+ and count / appearances[name] >= COMPETITOR_COMPARISON_SHARE
+ }
+
+ @staticmethod
+ def _mentions(query: str, competitors: set[str]) -> bool:
+ return any(DOMAIN_SUFFIX.sub("", word) in competitors for word in query.split())
+
+ def _serving(self, term: _Term) -> bool:
+ # Advice to cut or pause a term is moot when its campaign no longer serves.
+ campaign = self.campaigns.get(term.top_campaign_id)
+ return campaign is None or campaign.primary_status not in INACTIVE_STATUSES
+
+ def _term_recommendation(
+ self,
+ rule: MarketingAnalyticsRecommendationRule,
+ term: _Term,
+ action: str,
+ reason: str,
+ impact: float,
+ direction: Direction,
+ impact_type: Literal["measured", "estimated"],
+ ) -> MarketingAnalyticsRecommendation:
+ campaign = self.campaigns.get(term.top_campaign_id)
+ return self._recommendation(
+ rule,
+ "search_term",
+ term.term,
+ action,
+ reason,
+ impact * self.per_month,
+ direction,
+ impact_type,
+ campaign.name if campaign else None,
+ )
+
+ def _recommendation(
+ self,
+ rule: MarketingAnalyticsRecommendationRule,
+ level: Literal["campaign", "search_term"],
+ subject: str,
+ action: str,
+ reason: str,
+ impact: float | None,
+ direction: Direction,
+ impact_type: Literal["measured", "estimated"],
+ campaign: str | None = None,
+ ) -> MarketingAnalyticsRecommendation:
+ return MarketingAnalyticsRecommendation(
+ rule=rule,
+ level=level,
+ subject=subject,
+ campaign=campaign,
+ action=action,
+ reason=reason,
+ impact=round(impact) if impact is not None else None,
+ impactDirection=direction,
+ impactType=impact_type,
+ currency=self.inputs.currency,
+ )
+
+ def _money(self, amount: float) -> str:
+ currency = self.inputs.currency or ""
+ return f"${amount:,.0f}" if currency in ("USD", "") else f"{amount:,.0f} {currency}"
diff --git a/products/marketing_analytics/backend/hogql_queries/marketing_recommendations_query_runner.py b/products/marketing_analytics/backend/hogql_queries/marketing_recommendations_query_runner.py
new file mode 100644
index 000000000000..2b57687bff3c
--- /dev/null
+++ b/products/marketing_analytics/backend/hogql_queries/marketing_recommendations_query_runner.py
@@ -0,0 +1,420 @@
+import json
+from datetime import datetime
+from functools import cached_property
+from typing import Any
+
+from posthog.schema import (
+ CachedMarketingAnalyticsRecommendationsQueryResponse,
+ MarketingAnalyticsRecommendation,
+ MarketingAnalyticsRecommendationRule,
+ MarketingAnalyticsRecommendationsQuery,
+ MarketingAnalyticsRecommendationsQueryResponse,
+ MarketingAnalyticsRecommendationsSource,
+ MarketingAnalyticsRecommendationsSourceType,
+)
+
+from posthog.hogql import ast
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.database.database import Database
+from posthog.hogql.parser import parse_select
+from posthog.hogql.query import create_default_modifiers_for_team, execute_hogql_query
+
+from posthog.hogql_queries.query_runner import AnalyticsQueryRunner
+from posthog.hogql_queries.utils.query_date_range import QueryDateRange
+
+from products.marketing_analytics.backend.hogql_queries.marketing_recommendations import (
+ CampaignStats,
+ OrganicQueryStats,
+ RecommendationInputs,
+ SearchTermStats,
+ TermKeywordStats,
+ recommend,
+)
+from products.warehouse_sources.backend.facade.api import (
+ all_queryable_table_keys,
+ list_schemas_for_source,
+ list_sources,
+)
+
+ROW_LIMIT = 50000
+RECOMMENDATION_SOURCE_TYPES = ("GoogleAds", "GoogleSearchConsole")
+DISCLAIMER = (
+ "These are suggestions generated by fixed rules applied to your synced Google Ads and Search Console data. "
+ "Impact figures are estimates based on past performance, not predictions or guarantees. "
+ "You decide what to change, so review each suggestion before editing a campaign."
+)
+
+
+class MarketingAnalyticsRecommendationsQueryRunner(
+ AnalyticsQueryRunner[MarketingAnalyticsRecommendationsQueryResponse]
+):
+ query: MarketingAnalyticsRecommendationsQuery
+ response: MarketingAnalyticsRecommendationsQueryResponse
+ cached_response: CachedMarketingAnalyticsRecommendationsQueryResponse
+
+ @cached_property
+ def query_date_range(self) -> QueryDateRange:
+ return QueryDateRange(date_range=self.query.dateRange, team=self.team, interval=None, now=datetime.now())
+
+ @cached_property
+ def hogql_database(self) -> Database:
+ return Database.create_for(
+ team=self.team,
+ user=self.user,
+ modifiers=create_default_modifiers_for_team(self.team, self.modifiers),
+ timings=self.timings,
+ )
+
+ @cached_property
+ def hogql_context(self) -> HogQLContext:
+ return HogQLContext(
+ team_id=self.team.pk,
+ modifiers=create_default_modifiers_for_team(self.team, self.modifiers),
+ database=self.hogql_database,
+ )
+
+ def to_query(self) -> ast.SelectQuery:
+ return ast.SelectQuery(select=[ast.Constant(value=1)])
+
+ def _calculate(self) -> MarketingAnalyticsRecommendationsQueryResponse:
+ sources = self.query.sources if self.query.sources is not None else self._project_sources()
+ if not sources:
+ return MarketingAnalyticsRecommendationsQueryResponse(results=[], disclaimer=DISCLAIMER)
+ ads = [source for source in sources if source.sourceType == "GoogleAds"]
+ organic = [source for source in sources if source.sourceType == "GoogleSearchConsole"]
+ date_from, date_to = self.query_date_range.date_from(), self.query_date_range.date_to()
+ organic_queries = tuple(query for source in organic for query in self._organic_queries(source))
+ site_urls = tuple(url for source in organic for url in self._site_urls(source))
+ days = max((date_to - date_from).days + 1, 1)
+ # Each ad account has its own campaigns, costs and currency, so rules compare a campaign only with
+ # campaigns from the same account. Search Console data is shared because it has no account link.
+ results = [
+ recommendation
+ for source in ads
+ for recommendation in recommend(
+ RecommendationInputs(
+ campaigns=tuple(self._campaigns(source)),
+ search_terms=tuple(self._search_terms(source)),
+ organic_queries=organic_queries,
+ site_urls=site_urls,
+ currency=self._currency(source),
+ days=self._days_with_data(source) or days,
+ term_keywords=tuple(self._term_keywords(source)),
+ )
+ )
+ ]
+ return MarketingAnalyticsRecommendationsQueryResponse(
+ results=_dedupe_organic_only(results), disclaimer=DISCLAIMER
+ )
+
+ def _project_sources(self) -> list[MarketingAnalyticsRecommendationsSource]:
+ table_keys = all_queryable_table_keys(self.team.pk)
+ sources = []
+ for source in list_sources(self.team.pk):
+ if source.source_type not in RECOMMENDATION_SOURCE_TYPES:
+ continue
+ tables = {
+ schema.name: table_keys[schema.table_id].queryable_key
+ for schema in list_schemas_for_source(source.id, self.team.pk)
+ if schema.should_sync
+ and schema.last_synced_at is not None
+ and schema.table_id is not None
+ and schema.table_id in table_keys
+ }
+ recommendation_source = _recommendation_source(source.source_type, tables)
+ if recommendation_source is not None:
+ sources.append(recommendation_source)
+ return sources
+
+ def _readable(self, table: str | None) -> bool:
+ if not table:
+ return False
+ return self.hogql_database.has_table(table) and not self.hogql_database.is_table_access_denied(table)
+
+ def _has_field(self, table: str, field: str) -> bool:
+ return self.hogql_database.get_table(table.split(".")).has_field(field)
+
+ def _field(self, table: str, field: str) -> ast.Expr:
+ if self._has_field(table, field):
+ return ast.Field(chain=[field])
+ return ast.Constant(value=None)
+
+ def _select(self, sql: str, table: str, **placeholders: ast.Expr) -> list[list[Any]]:
+ date_range = self.query_date_range
+ result = execute_hogql_query(
+ query_type="marketing_analytics_recommendations_query",
+ query=parse_select(
+ # HogQL caps a query without a LIMIT at 100 rows, and accounts often have more campaigns.
+ sql if "LIMIT" in sql else f"{sql}\nLIMIT {ROW_LIMIT}",
+ placeholders={
+ "table": ast.Field(chain=list[str | int](table.split("."))),
+ "date_from": ast.Constant(value=date_range.date_from()),
+ "date_to": ast.Constant(value=date_range.date_to()),
+ **placeholders,
+ },
+ ),
+ context=self.hogql_context,
+ team=self.team,
+ user=self.user,
+ timings=self.timings,
+ modifiers=self.modifiers,
+ limit_context=self.limit_context,
+ )
+ return result.results or []
+
+ def _campaigns(self, source: MarketingAnalyticsRecommendationsSource) -> list[CampaignStats]:
+ if not self._readable(source.campaignTable) or not self._readable(source.campaignStatsTable):
+ return []
+ assert source.campaignTable and source.campaignStatsTable
+ definitions = {
+ row[0]: row
+ for row in self._select(
+ """
+ SELECT toString(campaign_id), any(campaign_name), any(campaign_advertising_channel_type),
+ any({primary_status}), any(toString({status_reasons})),
+ any(campaign_budget_amount_micros) / 1000000, any({recommended_budget}) / 1000000,
+ any(toString({budget_id})), any(toString({serving_status}))
+ FROM {table} GROUP BY campaign_id
+ """,
+ source.campaignTable,
+ primary_status=self._field(source.campaignTable, "campaign_primary_status"),
+ status_reasons=self._field(source.campaignTable, "campaign_primary_status_reasons"),
+ recommended_budget=self._field(
+ source.campaignTable, "campaign_budget_recommended_budget_amount_micros"
+ ),
+ budget_id=self._field(source.campaignTable, "campaign_campaign_budget"),
+ serving_status=self._field(source.campaignTable, "campaign_status"),
+ )
+ }
+ spend = {
+ row[0]: row
+ for row in self._select(
+ """
+ SELECT toString(campaign_id), sum(toFloat(metrics_cost_micros)) / 1000000, sum(toFloat(metrics_conversions))
+ FROM {table}
+ WHERE toDate(segments_date) >= toDate({date_from}) AND toDate(segments_date) <= toDate({date_to})
+ GROUP BY campaign_id
+ """,
+ source.campaignStatsTable,
+ )
+ }
+ shares = self._impression_shares(source.campaignImpressionShareTable)
+ campaigns = []
+ for campaign_id, (_, cost, conversions) in spend.items():
+ definition = definitions.get(campaign_id)
+ if not definition or not cost:
+ continue
+ share = shares.get(campaign_id, (None, None, None))
+ campaigns.append(
+ CampaignStats(
+ id=campaign_id,
+ name=definition[1] or campaign_id,
+ channel_type=definition[2],
+ # Older syncs lack primary_status, and campaign_status still tells paused and removed apart.
+ primary_status=definition[3] or definition[8] or None,
+ status_reasons=_parse_reasons(definition[4]),
+ daily_budget=definition[5],
+ recommended_daily_budget=definition[6] or None,
+ cost=float(cost),
+ conversions=float(conversions or 0),
+ impression_share=share[0],
+ lost_to_budget=share[1],
+ lost_to_rank=share[2],
+ budget_id=definition[7] or None,
+ )
+ )
+ return campaigns
+
+ def _impression_shares(self, table: str | None) -> dict[str, tuple[float | None, ...]]:
+ if not table or not self._readable(table):
+ return {}
+ fields = {
+ name: self._field(table, f"metrics_search_{name}")
+ for name in (
+ "impression_share",
+ "budget_lost_impression_share",
+ "rank_lost_impression_share",
+ )
+ }
+ rows = self._select(
+ """
+ SELECT toString(campaign_id),
+ sumIf(toFloat({impression_share}) * metrics_impressions, {impression_share} IS NOT NULL)
+ / nullIf(sumIf(metrics_impressions, {impression_share} IS NOT NULL), 0),
+ sumIf(toFloat({budget_lost_impression_share}) * metrics_impressions, {budget_lost_impression_share} IS NOT NULL)
+ / nullIf(sumIf(metrics_impressions, {budget_lost_impression_share} IS NOT NULL), 0),
+ sumIf(toFloat({rank_lost_impression_share}) * metrics_impressions, {rank_lost_impression_share} IS NOT NULL)
+ / nullIf(sumIf(metrics_impressions, {rank_lost_impression_share} IS NOT NULL), 0)
+ FROM {table}
+ WHERE toDate(segments_date) >= toDate({date_from}) AND toDate(segments_date) <= toDate({date_to})
+ GROUP BY campaign_id
+ """,
+ table,
+ **fields,
+ )
+ return {row[0]: tuple(row[1:]) for row in rows}
+
+ def _search_terms(self, source: MarketingAnalyticsRecommendationsSource) -> list[SearchTermStats]:
+ terms: list[SearchTermStats] = []
+ for table, term_field, status_field in (
+ (source.searchTermTable, "search_term_view_search_term", "search_term_view_status"),
+ (source.performanceMaxSearchTermTable, "campaign_search_term_view_search_term", None),
+ ):
+ if not table or not self._readable(table):
+ continue
+ rows = self._select(
+ f"""
+ SELECT lower(trim({{term}})) AS term, toString(campaign_id), sum(metrics_clicks), sum(metrics_impressions),
+ sum(toFloat(metrics_cost_micros)) / 1000000, sum(toFloat(metrics_conversions)), any(toString({{status}})),
+ sumIf(toFloat({{absolute_top}}) * metrics_impressions, {{absolute_top}} IS NOT NULL)
+ / nullIf(sumIf(metrics_impressions, {{absolute_top}} IS NOT NULL), 0)
+ FROM {{table}}
+ WHERE toDate(segments_date) >= toDate({{date_from}}) AND toDate(segments_date) <= toDate({{date_to}})
+ AND notEmpty(term)
+ GROUP BY term, campaign_id
+ ORDER BY sum(metrics_cost_micros) DESC
+ LIMIT {ROW_LIMIT}
+ """,
+ table,
+ term=ast.Field(chain=[term_field]),
+ status=ast.Field(chain=[status_field]) if status_field else ast.Constant(value="NONE"),
+ absolute_top=self._field(table, "metrics_absolute_top_impression_percentage"),
+ )
+ terms.extend(
+ SearchTermStats(
+ term=row[0],
+ campaign_id=row[1],
+ clicks=float(row[2] or 0),
+ impressions=float(row[3] or 0),
+ cost=float(row[4] or 0),
+ conversions=float(row[5] or 0),
+ status=row[6] or "NONE",
+ absolute_top_percentage=row[7],
+ )
+ for row in rows
+ )
+ return terms
+
+ def _term_keywords(self, source: MarketingAnalyticsRecommendationsSource) -> list[TermKeywordStats]:
+ if not source.searchTermKeywordTable or not self._readable(source.searchTermKeywordTable):
+ return []
+ rows = self._select(
+ f"""
+ SELECT lower(trim(search_term_view_search_term)) AS term, segments_keyword_info_text,
+ toString(segments_keyword_info_match_type), sum(toFloat(metrics_cost_micros)) / 1000000 AS cost
+ FROM {{table}}
+ WHERE toDate(segments_date) >= toDate({{date_from}}) AND toDate(segments_date) <= toDate({{date_to}})
+ AND notEmpty(term)
+ GROUP BY term, segments_keyword_info_text, segments_keyword_info_match_type
+ ORDER BY cost DESC
+ LIMIT {ROW_LIMIT}
+ """,
+ source.searchTermKeywordTable,
+ )
+ return [
+ TermKeywordStats(term=row[0], keyword=row[1] or "", match_type=row[2] or "", cost=float(row[3] or 0))
+ for row in rows
+ if row[1]
+ ]
+
+ def _organic_queries(self, source: MarketingAnalyticsRecommendationsSource) -> list[OrganicQueryStats]:
+ if not source.queryTable or not self._readable(source.queryTable):
+ return []
+ rows = self._select(
+ f"""
+ SELECT lower(trim(query)) AS q, sum(clicks), sum(impressions),
+ sum(position * impressions) / nullIf(sum(impressions), 0)
+ FROM {{table}}
+ WHERE toDate(date) >= toDate({{date_from}}) AND toDate(date) <= toDate({{date_to}}) AND notEmpty(q)
+ GROUP BY q
+ ORDER BY sum(impressions) DESC
+ LIMIT {ROW_LIMIT}
+ """,
+ source.queryTable,
+ )
+ return [
+ OrganicQueryStats(
+ query=row[0], clicks=float(row[1] or 0), impressions=float(row[2] or 0), position=float(row[3] or 0)
+ )
+ for row in rows
+ if row[2]
+ ]
+
+ def _site_urls(self, source: MarketingAnalyticsRecommendationsSource) -> list[str]:
+ if not source.sitesTable or not self._readable(source.sitesTable):
+ return []
+ return [row[0] for row in self._select("SELECT site_url FROM {table} LIMIT 10", source.sitesTable) if row[0]]
+
+ def _days_with_data(self, source: MarketingAnalyticsRecommendationsSource) -> int | None:
+ # A source that started syncing inside the range has fewer days of spend, and monthly figures must use them.
+ if not source.campaignStatsTable or not self._readable(source.campaignStatsTable):
+ return None
+ rows = self._select(
+ """
+ SELECT count(DISTINCT toDate(segments_date)) FROM {table}
+ WHERE toDate(segments_date) >= toDate({date_from}) AND toDate(segments_date) <= toDate({date_to})
+ """,
+ source.campaignStatsTable,
+ )
+ return int(rows[0][0]) if rows and rows[0][0] else None
+
+ def _currency(self, source: MarketingAnalyticsRecommendationsSource) -> str | None:
+ # campaign_stats carries the account currency like the other marketing queries read it; the customer
+ # table is only a fallback for stats synced before that column existed.
+ for table in (source.campaignStatsTable, source.customerTable):
+ if not table or not self._readable(table) or not self._has_field(table, "customer_currency_code"):
+ continue
+ rows = self._select(
+ "SELECT anyIf(upper(customer_currency_code), length(coalesce(customer_currency_code, '')) > 0) FROM {table}",
+ table,
+ )
+ if rows and rows[0][0]:
+ return rows[0][0]
+ return None
+
+
+def _recommendation_source(source_type: str, tables: dict[str, str]) -> MarketingAnalyticsRecommendationsSource | None:
+ if source_type == "GoogleAds":
+ if "campaign" not in tables or "campaign_stats" not in tables:
+ return None
+ return MarketingAnalyticsRecommendationsSource(
+ sourceType=MarketingAnalyticsRecommendationsSourceType.GOOGLE_ADS,
+ campaignTable=tables["campaign"],
+ campaignStatsTable=tables["campaign_stats"],
+ campaignImpressionShareTable=tables.get("campaign_impression_share_stats"),
+ customerTable=tables.get("customer"),
+ searchTermTable=tables.get("search_term_stats"),
+ searchTermKeywordTable=tables.get("search_term_keyword_stats"),
+ performanceMaxSearchTermTable=tables.get("performance_max_search_term_stats"),
+ )
+ query_table = tables.get("search_analytics_by_query") or tables.get("search_analytics_by_query_page")
+ if query_table is None:
+ return None
+ return MarketingAnalyticsRecommendationsSource(
+ sourceType=MarketingAnalyticsRecommendationsSourceType.GOOGLE_SEARCH_CONSOLE,
+ queryTable=query_table,
+ sitesTable=tables.get("sites"),
+ )
+
+
+def _parse_reasons(value: str | None) -> tuple[str, ...]:
+ if not value:
+ return ()
+ try:
+ parsed = json.loads(value)
+ except ValueError:
+ return tuple(part.strip(" '\"") for part in value.strip("[]").split(",") if part.strip(" '\""))
+ return tuple(str(reason) for reason in parsed) if isinstance(parsed, list) else ()
+
+
+def _dedupe_organic_only(results: list[MarketingAnalyticsRecommendation]) -> list[MarketingAnalyticsRecommendation]:
+ # Keyword gap reads only the shared Search Console data, so each ad account would repeat the same query.
+ seen: set[str] = set()
+ deduped = []
+ for recommendation in results:
+ if recommendation.rule == MarketingAnalyticsRecommendationRule.KEYWORD_GAP:
+ if recommendation.subject in seen:
+ continue
+ seen.add(recommendation.subject)
+ deduped.append(recommendation)
+ return deduped
diff --git a/products/marketing_analytics/backend/hogql_queries/test_marketing_recommendations.py b/products/marketing_analytics/backend/hogql_queries/test_marketing_recommendations.py
new file mode 100644
index 000000000000..8fea00e6fa84
--- /dev/null
+++ b/products/marketing_analytics/backend/hogql_queries/test_marketing_recommendations.py
@@ -0,0 +1,266 @@
+from dataclasses import replace
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.marketing_analytics.backend.hogql_queries.marketing_recommendations import (
+ CampaignStats,
+ OrganicQueryStats,
+ RecommendationInputs,
+ SearchTermStats,
+ TermKeywordStats,
+ brands_from_site_urls,
+ recommend,
+)
+
+
+def _campaign(**overrides: object) -> CampaignStats:
+ values: dict = {
+ "id": "c1",
+ "name": "Search",
+ "channel_type": "SEARCH",
+ "primary_status": "ELIGIBLE",
+ "status_reasons": (),
+ "daily_budget": 100.0,
+ "recommended_daily_budget": None,
+ "cost": 1000.0,
+ "conversions": 10.0,
+ "impression_share": 0.5,
+ "lost_to_budget": 0.1,
+ "lost_to_rank": 0.1,
+ **overrides,
+ }
+ return CampaignStats(**values)
+
+
+def _term(term: str, campaign_id: str, cost: float, conversions: float, clicks: float = 10) -> SearchTermStats:
+ return SearchTermStats(
+ term=term,
+ campaign_id=campaign_id,
+ clicks=clicks,
+ impressions=100,
+ cost=cost,
+ conversions=conversions,
+ status="NONE",
+ )
+
+
+def _inputs(
+ campaigns: tuple[CampaignStats, ...] = (),
+ terms: tuple[SearchTermStats, ...] = (),
+ organic: tuple[OrganicQueryStats, ...] = (),
+ term_keywords: tuple[TermKeywordStats, ...] = (),
+) -> RecommendationInputs:
+ return RecommendationInputs(
+ term_keywords=term_keywords,
+ campaigns=campaigns,
+ search_terms=terms,
+ organic_queries=organic,
+ site_urls=("sc-domain:example.com",),
+ currency="USD",
+ days=30,
+ )
+
+
+class TestMarketingRecommendations(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("google_recommends_more", ("BUDGET_CONSTRAINED",), "ELIGIBLE", 300.0, True),
+ ("no_google_recommendation", ("BUDGET_CONSTRAINED",), "ELIGIBLE", None, False),
+ ("not_budget_constrained", ("UNKNOWN",), "ELIGIBLE", 300.0, False),
+ ("paused_campaign", ("BUDGET_CONSTRAINED",), "PAUSED", 300.0, False),
+ ]
+ )
+ def test_budget_rule_needs_a_budget_limit_and_google_recommendation(
+ self, _name: str, reasons: tuple[str, ...], status: str, recommended: float | None, expected: bool
+ ) -> None:
+ campaign = _campaign(status_reasons=reasons, primary_status=status, recommended_daily_budget=recommended)
+ rules = [rec for rec in recommend(_inputs((campaign,))) if rec.rule == "budget_constrained"]
+ assert bool(rules) == expected
+ if expected:
+ assert rules[0].action == "Raise the daily budget from $100 to $300"
+ assert rules[0].impact == 6000
+
+ def test_campaigns_sharing_a_budget_get_one_budget_recommendation(self) -> None:
+ shared = {"status_reasons": ("BUDGET_CONSTRAINED",), "recommended_daily_budget": 300.0, "budget_id": "b1"}
+ campaigns = (
+ _campaign(id="c1", **shared),
+ _campaign(id="c2", name="Search 2", **shared),
+ _campaign(id="c3", name="Search 3", status_reasons=("BUDGET_CONSTRAINED",), recommended_daily_budget=200.0),
+ )
+
+ budget_rows = [rec for rec in recommend(_inputs(campaigns)) if rec.rule == "budget_constrained"]
+
+ assert len(budget_rows) == 2
+
+ @parameterized.expand(
+ [
+ ("domain_property", "sc-domain:example.com", {"example"}),
+ ("url_prefix_subdomain", "https://app.example.com/", {"example"}),
+ ("country_code_domain", "https://www.example.co.uk/", {"example"}),
+ ("private_suffix", "https://example.github.io/", {"example"}),
+ ("multi_label_suffix", "sc-domain:example.com.br", {"example"}),
+ ("label_too_short_to_match_safely", "sc-domain:ab.io", set()),
+ ]
+ )
+ def test_brand_comes_from_the_registrable_domain(self, _name: str, site_url: str, expected: set[str]) -> None:
+ assert brands_from_site_urls([site_url]) == expected
+
+ def test_brand_conversions_do_not_make_a_non_brand_campaign_look_cheap(self) -> None:
+ brand_campaign = _campaign(id="brand", name="Brand", cost=500, conversions=100)
+ cheap_looking = _campaign(
+ id="generic", name="Generic", cost=2000, conversions=20, lost_to_budget=0.3, lost_to_rank=0.3
+ )
+ other = _campaign(id="other", name="Other", cost=3000, conversions=30)
+ terms = (
+ _term("example", "brand", cost=500, conversions=100),
+ _term("example pricing", "generic", cost=800, conversions=18),
+ _term("product analytics", "generic", cost=1200, conversions=2),
+ _term("session replay", "other", cost=3000, conversions=30),
+ )
+
+ recs = recommend(_inputs((brand_campaign, cheap_looking, other), terms))
+
+ leak = next(rec for rec in recs if rec.rule == "brand_leak")
+ assert (leak.subject, leak.action) == ("Generic", 'Add "example" as a negative keyword')
+ assert not any(rec.rule == "scale_campaign" and rec.subject == "Generic" for rec in recs)
+
+ @parameterized.expand(
+ [
+ ("another_ad_often_shows_above", 0.6, "keep", "Keep the ad"),
+ ("ad_owns_the_top_spot", 0.95, "save", "Test pausing"),
+ ("top_spot_not_measured", None, "save", "Check whether other ads show above yours"),
+ ]
+ )
+ def test_brand_overlap_keeps_the_ad_when_another_ad_shows_above(
+ self, _name: str, absolute_top: float | None, direction: str, action_start: str
+ ) -> None:
+ brand = _campaign(id="brand", name="Brand")
+ terms = (
+ replace(_term("example", "brand", cost=1000, conversions=5), absolute_top_percentage=absolute_top),
+ _term("analytics", "brand", cost=100, conversions=5),
+ )
+ organic = (OrganicQueryStats(query="example", clicks=500, impressions=1000, position=1.0),)
+
+ overlap = [rec for rec in recommend(_inputs((brand,), terms, organic)) if rec.rule == "brand_overlap"]
+
+ assert [(rec.subject, rec.impactDirection) for rec in overlap] == [("example", direction)]
+ assert overlap[0].action.startswith(action_start)
+
+ @parameterized.expand(
+ [
+ ("every_word_converts_cheaply", "funnel analysis", True),
+ ("one_word_never_converted", "funnel spy", False),
+ ("only_generic_words", "free online tool", False),
+ ]
+ )
+ def test_keyword_gap_needs_every_meaningful_word_to_convert(self, _name: str, query: str, expected: bool) -> None:
+ campaign = _campaign()
+ terms = (
+ _term("funnel tracking", "c1", cost=100, conversions=10),
+ _term("analysis software", "c1", cost=100, conversions=10),
+ _term("spy", "c1", cost=1000, conversions=1),
+ )
+ organic = tuple(OrganicQueryStats(query=f"filler {i}", clicks=1, impressions=1, position=50) for i in range(30))
+ organic += (OrganicQueryStats(query=query, clicks=1, impressions=5000, position=25),)
+
+ gaps = [rec.subject for rec in recommend(_inputs((campaign,), terms, organic)) if rec.rule == "keyword_gap"]
+
+ assert (query in gaps) == expected
+
+ def test_performance_max_gets_brand_exclusion_and_rank_advice(self) -> None:
+ pmax = _campaign(
+ id="pmax",
+ name="PMax",
+ channel_type="PERFORMANCE_MAX",
+ status_reasons=("HAS_ASSET_GROUPS_LIMITED_BY_POLICY",),
+ lost_to_rank=0.6,
+ )
+ terms = (
+ _term("example", "pmax", cost=300, conversions=2),
+ _term("project planning software", "pmax", cost=700, conversions=8),
+ )
+
+ actions = {
+ (rec.rule.value, rec.action) for rec in recommend(_inputs((pmax,), terms)) if rec.level == "campaign"
+ }
+
+ assert actions == {
+ ("brand_leak", 'Add a brand exclusion for "example"'),
+ ("scale_campaign", "Raise the target CPA or improve its asset groups"),
+ ("policy_limited", "Check the affected ads in Policy manager"),
+ }
+
+ @parameterized.expand(
+ [
+ (
+ "broad",
+ "BROAD",
+ 'Add it as a negative, or change the keyword "website traffic" from broad to exact match',
+ ),
+ (
+ "phrase_enum_number",
+ "3",
+ 'Add it as a negative, or change the keyword "website traffic" from phrase to exact match',
+ ),
+ ("exact", "EXACT", 'Review the keyword "website traffic" (exact match) and its landing page, or pause it'),
+ ]
+ )
+ def test_spend_without_conversions_names_the_keyword_that_matched(
+ self, _name: str, match_type: str, expected: str
+ ) -> None:
+ terms = (
+ _term("spy website traffic", "c1", cost=500, conversions=0),
+ _term("product analytics", "c1", cost=500, conversions=10),
+ )
+ keywords = (
+ TermKeywordStats(term="spy website traffic", keyword="website traffic", match_type=match_type, cost=400),
+ TermKeywordStats(term="spy website traffic", keyword="traffic", match_type="BROAD", cost=100),
+ )
+
+ actions = [
+ rec.action
+ for rec in recommend(_inputs((_campaign(),), terms, term_keywords=keywords))
+ if rec.rule == "spend_without_conversions"
+ ]
+
+ assert actions == [expected]
+
+ @parameterized.expand([("serving", "ELIGIBLE", 1), ("paused", "PAUSED", 0), ("removed", "REMOVED", 0)])
+ def test_spend_without_conversions_skips_campaigns_that_do_not_serve(
+ self, _name: str, status: str, expected: int
+ ) -> None:
+ campaigns = (_campaign(primary_status=status), _campaign(id="c2", name="Other"))
+ terms = (
+ _term("free analytics template", "c1", cost=500, conversions=0),
+ _term("product analytics", "c2", cost=500, conversions=10),
+ )
+
+ rows = [rec for rec in recommend(_inputs(campaigns, terms)) if rec.rule == "spend_without_conversions"]
+
+ assert len(rows) == expected
+
+ def test_category_words_are_not_treated_as_competitors(self) -> None:
+ terms = (
+ _term("trackly logs", "c1", cost=500, conversions=0),
+ _term("app analytics", "c1", cost=500, conversions=0),
+ _term("product analytics", "c1", cost=500, conversions=10),
+ )
+ comparisons = ("trackly alternatives", "trackly vs zentrix", "analytics alternatives", "analytics vs bi")
+ everyday = tuple(f"analytics report {i}" for i in range(60))
+ organic = tuple(
+ OrganicQueryStats(query=query, clicks=1, impressions=10, position=30)
+ for query in (*comparisons, *everyday, "trackly", "analytics")
+ )
+
+ actions = {
+ rec.subject: rec.action
+ for rec in recommend(_inputs((_campaign(),), terms, organic))
+ if rec.rule == "spend_without_conversions"
+ }
+
+ assert actions == {
+ "trackly logs": "Competitor term: decide whether conquesting is worth it.",
+ "app analytics": "Review the bid and landing page, or add it as a negative",
+ }
diff --git a/products/marketing_analytics/backend/hogql_queries/test_marketing_recommendations_query_runner.py b/products/marketing_analytics/backend/hogql_queries/test_marketing_recommendations_query_runner.py
new file mode 100644
index 000000000000..fa5f7e3778d7
--- /dev/null
+++ b/products/marketing_analytics/backend/hogql_queries/test_marketing_recommendations_query_runner.py
@@ -0,0 +1,138 @@
+from pathlib import Path
+from tempfile import TemporaryDirectory
+
+from posthog.test.base import BaseTest, ClickhouseTestMixin
+
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from posthog.schema import DateRange, MarketingAnalyticsRecommendationsQuery, MarketingAnalyticsRecommendationsSource
+
+from products.marketing_analytics.backend.hogql_queries.marketing_recommendations_query_runner import (
+ MarketingAnalyticsRecommendationsQueryRunner,
+)
+from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSchema, ExternalDataSource
+from products.warehouse_sources.backend.facade.testing import create_data_warehouse_table_from_csv
+
+
+class TestMarketingAnalyticsRecommendationsQueryRunner(ClickhouseTestMixin, BaseTest):
+ def _table(self, name: str, columns: dict[str, str], csv: str) -> str:
+ with TemporaryDirectory() as directory:
+ path = Path(directory) / f"{name}.csv"
+ path.write_text(csv)
+ table, _, _, _, cleanup = create_data_warehouse_table_from_csv(
+ path, name, columns, f"test_storage_bucket-posthog.marketing_analytics.{name}", self.team
+ )
+ self.addCleanup(cleanup)
+ return table.name
+
+ @parameterized.expand([("with_status_columns", True), ("before_status_columns_were_synced", False)])
+ def test_reads_every_campaign_and_tolerates_missing_status_columns(self, _name: str, has_status: bool) -> None:
+ count = 101
+ campaign_columns = {
+ "campaign_id": "Int64",
+ "campaign_name": "String",
+ "campaign_advertising_channel_type": "String",
+ "campaign_budget_amount_micros": "Int64",
+ }
+ if has_status:
+ campaign_columns |= {
+ "campaign_primary_status": "String",
+ "campaign_primary_status_reasons": "String",
+ "campaign_budget_recommended_budget_amount_micros": "Int64",
+ }
+ rows = []
+ for i in range(1, count + 1):
+ row = [str(i), f"Campaign {i}", "SEARCH", "100000000"]
+ if has_status:
+ constrained = i == count
+ row += [
+ "LIMITED" if constrained else "ELIGIBLE",
+ '"[""BUDGET_CONSTRAINED""]"' if constrained else '"[]"',
+ "300000000" if constrained else "0",
+ ]
+ rows.append(",".join(row))
+ campaigns = self._table(
+ "campaign", campaign_columns, ",".join(campaign_columns) + "\n" + "\n".join(rows) + "\n"
+ )
+ stats = self._table(
+ "campaign_stats",
+ {
+ "campaign_id": "Int64",
+ "segments_date": "Date",
+ "metrics_cost_micros": "Int64",
+ "metrics_conversions": "Float64",
+ },
+ "campaign_id,segments_date,metrics_cost_micros,metrics_conversions\n"
+ + "".join(f"{i},2026-01-15,1000000000,10\n" for i in range(1, count + 1)),
+ )
+
+ response = MarketingAnalyticsRecommendationsQueryRunner(
+ query=MarketingAnalyticsRecommendationsQuery(
+ dateRange=DateRange(date_from="2026-01-01", date_to="2026-01-30"),
+ sources=[
+ MarketingAnalyticsRecommendationsSource(
+ sourceType="GoogleAds", campaignTable=campaigns, campaignStatsTable=stats
+ )
+ ],
+ ),
+ team=self.team,
+ user=self.user,
+ ).calculate()
+
+ budget = [(rec.subject, rec.action) for rec in response.results if rec.rule == "budget_constrained"]
+ assert budget == ([("Campaign 101", "Raise the daily budget from $100 to $300")] if has_status else [])
+
+
+class TestMarketingAnalyticsRecommendationsSourceDiscovery(BaseTest):
+ def _source(self, source_type: str, prefix: str, schemas: dict[str, bool]) -> None:
+ source = ExternalDataSource.objects.create(
+ team=self.team,
+ source_id=prefix,
+ connection_id=prefix,
+ status=ExternalDataSource.Status.COMPLETED,
+ source_type=source_type,
+ prefix=prefix,
+ )
+ for name, synced in schemas.items():
+ table = DataWarehouseTable.objects.create(
+ team=self.team, name=f"{prefix}{source_type.lower()}_{name}", columns={}, external_data_source=source
+ )
+ ExternalDataSchema.objects.create(
+ team=self.team,
+ source=source,
+ name=name,
+ table=table,
+ should_sync=synced,
+ last_synced_at=timezone.now() if synced else None,
+ )
+
+ def test_reads_synced_tables_of_every_google_source_when_the_query_names_none(self) -> None:
+ self._source(
+ "GoogleAds",
+ "acme",
+ {"campaign": True, "campaign_stats": True, "search_term_stats": True, "customer": False},
+ )
+ self._source("GoogleAds", "unsynced", {"campaign": True, "campaign_stats": False})
+ self._source("GoogleSearchConsole", "organic", {"search_analytics_by_query_page": True, "sites": True})
+ self._source("BingAds", "bing", {"campaign_performance_report": True})
+
+ runner = MarketingAnalyticsRecommendationsQueryRunner(
+ query=MarketingAnalyticsRecommendationsQuery(), team=self.team, user=self.user
+ )
+
+ sources = sorted(runner._project_sources(), key=lambda source: source.sourceType)
+ assert [source.model_dump(exclude_none=True) for source in sources] == [
+ {
+ "sourceType": "GoogleAds",
+ "campaignTable": "googleads.acme.campaign",
+ "campaignStatsTable": "googleads.acme.campaign_stats",
+ "searchTermTable": "googleads.acme.search_term_stats",
+ },
+ {
+ "sourceType": "GoogleSearchConsole",
+ "queryTable": "googlesearchconsole.organic.search_analytics_by_query_page",
+ "sitesTable": "googlesearchconsole.organic.sites",
+ },
+ ]
diff --git a/products/marketing_analytics/mcp/prompts/query-marketing-recommendations.md b/products/marketing_analytics/mcp/prompts/query-marketing-recommendations.md
new file mode 100644
index 000000000000..a77d0e80e303
--- /dev/null
+++ b/products/marketing_analytics/mcp/prompts/query-marketing-recommendations.md
@@ -0,0 +1,37 @@
+Get paid and organic search recommendations for the project's Google Ads accounts, built from synced Google Ads and Google Search Console warehouse tables. Mirrors the recommendations in the in-product **Marketing analytics** scene.
+
+# When to use
+
+Use this tool when the user asks where to cut ad spend, which campaigns to scale or review, which search terms waste money, or how paid and organic search overlap.
+
+Do not use it for attribution, conversion goals, or channel performance. Use `marketing-analytics-diagnose` when the data looks missing or wrong.
+
+# Inputs
+
+- `dateRange` — pass `{ "date_from": "-30d" }` unless the user asks for another period. Short ranges give few recommendations, because the rules need enough clicks and spend to compare.
+- Leave everything else out. The tool reads every synced Google Ads and Google Search Console source in the project.
+
+# Output
+
+Each result has:
+
+- `rule` — the check that produced it, for example `spend_without_conversions`, `brand_leak`, `budget_constrained`, `scale_campaign`, `review_campaign`, `brand_overlap`, `content_gap`, `keyword_gap`, `striking_distance` or `policy_limited`.
+- `level` — `campaign` or `search_term`. `subject` is the campaign name or the search term, and `campaign` is the campaign a search term belongs to.
+- `action` and `reason` — what to do and the numbers behind it. Quote them instead of inventing your own advice.
+- `impact` — the monthly money impact in `currency`, or null. `impactDirection` says how to read it: `save` is spend to cut, `invest` is extra budget to add, `gain` is value to win, and `keep` is spend to protect.
+- `impactType` — `measured` comes straight from the data. `estimated` is a projection, so present it as an estimate.
+
+Totals in different currencies come from different ad accounts. Never add them together.
+
+Present the results as suggestions for the user to evaluate, not as instructions. Always show the response's `disclaimer` text with them. Do not change campaigns, budgets, bids or keywords on the user's behalf.
+
+An empty result means no rule fired, or the project has no synced Google Ads `campaign` and `campaign_stats` tables. Call `marketing-analytics-data-sources` to tell the two apart.
+
+# Example
+
+```json
+{
+ "kind": "MarketingAnalyticsRecommendationsQuery",
+ "dateRange": { "date_from": "-30d" }
+}
+```
diff --git a/products/marketing_analytics/mcp/tools.yaml b/products/marketing_analytics/mcp/tools.yaml
index a40853e07137..527a3c4b0539 100644
--- a/products/marketing_analytics/mcp/tools.yaml
+++ b/products/marketing_analytics/mcp/tools.yaml
@@ -239,3 +239,24 @@ tools:
integrations, unmatched custom sources, and total spend at risk. Use when the user asks why their events
appear in 'non-integrated', or why UTMs are not matching the ad platform data.
feature_flag: marketing-analytics-mcp
+wrappers:
+ query-marketing-recommendations:
+ schema_ref: MarketingAnalyticsRecommendationsQuery
+ enabled: true
+ scopes:
+ - query:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Get paid and organic search recommendations
+ description_file: ./prompts/query-marketing-recommendations.md
+ system_prompt_hint: Google Ads and Search Console recommendations - wasted spend, budgets, brand and organic overlap
+ exclude_properties:
+ - response
+ - modifiers
+ - sources
+ use_optimized_output: false
+ url_prefix: /marketing
+ feature_flag: marketing-analytics-recommendations
+ reads_ingested_data: events_or_warehouse
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 5d9c106119de..8ef5f73d1ea5 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -11879,6 +11879,24 @@
"reads_ingested_data": "events",
"system_prompt_hint": "Log filtering by severity/service/attribute"
},
+ "query-marketing-recommendations": {
+ "description": "Get paid and organic search recommendations for the project's Google Ads accounts, built from synced Google Ads and Google Search Console warehouse tables. Mirrors the recommendations in the in-product **Marketing analytics** scene.\n\n# When to use\n\nUse this tool when the user asks where to cut ad spend, which campaigns to scale or review, which search terms waste money, or how paid and organic search overlap.\n\nDo not use it for attribution, conversion goals, or channel performance. Use `marketing-analytics-diagnose` when the data looks missing or wrong.\n\n# Inputs\n\n- `dateRange` — pass `{ \"date_from\": \"-30d\" }` unless the user asks for another period. Short ranges give few recommendations, because the rules need enough clicks and spend to compare.\n- Leave everything else out. The tool reads every synced Google Ads and Google Search Console source in the project.\n\n# Output\n\nEach result has:\n\n- `rule` — the check that produced it, for example `spend_without_conversions`, `brand_leak`, `budget_constrained`, `scale_campaign`, `review_campaign`, `brand_overlap`, `content_gap`, `keyword_gap`, `striking_distance` or `policy_limited`.\n- `level` — `campaign` or `search_term`. `subject` is the campaign name or the search term, and `campaign` is the campaign a search term belongs to.\n- `action` and `reason` — what to do and the numbers behind it. Quote them instead of inventing your own advice.\n- `impact` — the monthly money impact in `currency`, or null. `impactDirection` says how to read it: `save` is spend to cut, `invest` is extra budget to add, `gain` is value to win, and `keep` is spend to protect.\n- `impactType` — `measured` comes straight from the data. `estimated` is a projection, so present it as an estimate.\n\nTotals in different currencies come from different ad accounts. Never add them together.\n\nPresent the results as suggestions for the user to evaluate, not as instructions. Always show the response's `disclaimer` text with them. Do not change campaigns, budgets, bids or keywords on the user's behalf.\n\nAn empty result means no rule fired, or the project has no synced Google Ads `campaign` and `campaign_stats` tables. Call `marketing-analytics-data-sources` to tell the two apart.\n\n# Example\n\n```json\n{\n \"kind\": \"MarketingAnalyticsRecommendationsQuery\",\n \"dateRange\": { \"date_from\": \"-30d\" }\n}\n```",
+ "category": "Marketing analytics",
+ "feature": "marketing_analytics",
+ "summary": "Get paid and organic search recommendations",
+ "title": "Get paid and organic search recommendations",
+ "required_scopes": ["query:read"],
+ "api_operations": ["POST /api/projects/{project_id}/query/"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "marketing-analytics-recommendations",
+ "reads_ingested_data": "events_or_warehouse",
+ "system_prompt_hint": "Google Ads and Search Console recommendations - wasted spend, budgets, brand and organic overlap"
+ },
"query-mcp-harness-breakdown": {
"description": "Group this project's MCP tool-call activity by the resolved client harness — the friendly product label for the MCP client (Claude Agent SDK, Claude Code, OpenAI Codex, Cursor, Claude.ai, …). Returns calls, error count, error rate, and session count per harness. Accepts the same dateRange / properties / filterTestAccounts filters as the dashboard and resolves the harness server-side over the same query runner, so results match the UI exactly. Use to answer \"which harnesses use our MCP, and how reliably?\".",
"category": "MCP analytics",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index de6f2e0a0dd1..3168bf513816 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -12566,6 +12566,24 @@
"reads_ingested_data": "events",
"system_prompt_hint": "Log filtering by severity/service/attribute"
},
+ "query-marketing-recommendations": {
+ "description": "Get paid and organic search recommendations for the project's Google Ads accounts, built from synced Google Ads and Google Search Console warehouse tables. Mirrors the recommendations in the in-product **Marketing analytics** scene.\n\n# When to use\n\nUse this tool when the user asks where to cut ad spend, which campaigns to scale or review, which search terms waste money, or how paid and organic search overlap.\n\nDo not use it for attribution, conversion goals, or channel performance. Use `marketing-analytics-diagnose` when the data looks missing or wrong.\n\n# Inputs\n\n- `dateRange` — pass `{ \"date_from\": \"-30d\" }` unless the user asks for another period. Short ranges give few recommendations, because the rules need enough clicks and spend to compare.\n- Leave everything else out. The tool reads every synced Google Ads and Google Search Console source in the project.\n\n# Output\n\nEach result has:\n\n- `rule` — the check that produced it, for example `spend_without_conversions`, `brand_leak`, `budget_constrained`, `scale_campaign`, `review_campaign`, `brand_overlap`, `content_gap`, `keyword_gap`, `striking_distance` or `policy_limited`.\n- `level` — `campaign` or `search_term`. `subject` is the campaign name or the search term, and `campaign` is the campaign a search term belongs to.\n- `action` and `reason` — what to do and the numbers behind it. Quote them instead of inventing your own advice.\n- `impact` — the monthly money impact in `currency`, or null. `impactDirection` says how to read it: `save` is spend to cut, `invest` is extra budget to add, `gain` is value to win, and `keep` is spend to protect.\n- `impactType` — `measured` comes straight from the data. `estimated` is a projection, so present it as an estimate.\n\nTotals in different currencies come from different ad accounts. Never add them together.\n\nPresent the results as suggestions for the user to evaluate, not as instructions. Always show the response's `disclaimer` text with them. Do not change campaigns, budgets, bids or keywords on the user's behalf.\n\nAn empty result means no rule fired, or the project has no synced Google Ads `campaign` and `campaign_stats` tables. Call `marketing-analytics-data-sources` to tell the two apart.\n\n# Example\n\n```json\n{\n \"kind\": \"MarketingAnalyticsRecommendationsQuery\",\n \"dateRange\": { \"date_from\": \"-30d\" }\n}\n```",
+ "category": "Marketing analytics",
+ "feature": "marketing_analytics",
+ "summary": "Get paid and organic search recommendations",
+ "title": "Get paid and organic search recommendations",
+ "required_scopes": ["query:read"],
+ "api_operations": ["POST /api/projects/{project_id}/query/"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "marketing-analytics-recommendations",
+ "reads_ingested_data": "events_or_warehouse",
+ "system_prompt_hint": "Google Ads and Search Console recommendations - wasted spend, budgets, brand and organic overlap"
+ },
"query-mcp-harness-breakdown": {
"description": "Group this project's MCP tool-call activity by the resolved client harness — the friendly product label for the MCP client (Claude Agent SDK, Claude Code, OpenAI Codex, Cursor, Claude.ai, …). Returns calls, error count, error rate, and session count per harness. Accepts the same dateRange / properties / filterTestAccounts filters as the dashboard and resolves the harness server-side over the same query runner, so results match the UI exactly. Use to answer \"which harnesses use our MCP, and how reliably?\".",
"category": "MCP analytics",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index f7ac3b383d02..e2eba467a049 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -61541,6 +61541,131 @@ export namespace Schemas {
version?: number | null;
}
+ export type MarketingAnalyticsRecommendationImpactDirection = typeof MarketingAnalyticsRecommendationImpactDirection[keyof typeof MarketingAnalyticsRecommendationImpactDirection];
+
+
+ export const MarketingAnalyticsRecommendationImpactDirection = {
+ Save: 'save',
+ Gain: 'gain',
+ Invest: 'invest',
+ Keep: 'keep',
+ } as const;
+
+ export type MarketingAnalyticsRecommendationImpactType = typeof MarketingAnalyticsRecommendationImpactType[keyof typeof MarketingAnalyticsRecommendationImpactType];
+
+
+ export const MarketingAnalyticsRecommendationImpactType = {
+ Measured: 'measured',
+ Estimated: 'estimated',
+ } as const;
+
+ export type MarketingAnalyticsRecommendationLevel = typeof MarketingAnalyticsRecommendationLevel[keyof typeof MarketingAnalyticsRecommendationLevel];
+
+
+ export const MarketingAnalyticsRecommendationLevel = {
+ Campaign: 'campaign',
+ SearchTerm: 'search_term',
+ } as const;
+
+ export type MarketingAnalyticsRecommendationRule = typeof MarketingAnalyticsRecommendationRule[keyof typeof MarketingAnalyticsRecommendationRule];
+
+
+ export const MarketingAnalyticsRecommendationRule = {
+ BudgetConstrained: 'budget_constrained',
+ BrandLeak: 'brand_leak',
+ ScaleCampaign: 'scale_campaign',
+ ReviewCampaign: 'review_campaign',
+ PolicyLimited: 'policy_limited',
+ BrandOverlap: 'brand_overlap',
+ ContentGap: 'content_gap',
+ KeywordGap: 'keyword_gap',
+ SpendWithoutConversions: 'spend_without_conversions',
+ StrikingDistance: 'striking_distance',
+ } as const;
+
+ export interface MarketingAnalyticsRecommendation {
+ action: string;
+ /** The campaign a search term recommendation applies to, when it applies to one. */
+ campaign?: string | null;
+ currency?: string | null;
+ /** Monthly money impact in the account currency. Null when the rule has no money impact. */
+ impact?: number | null;
+ impactDirection: MarketingAnalyticsRecommendationImpactDirection;
+ impactType: MarketingAnalyticsRecommendationImpactType;
+ level: MarketingAnalyticsRecommendationLevel;
+ reason: string;
+ rule: MarketingAnalyticsRecommendationRule;
+ /** The campaign name or the search term the recommendation is about. */
+ subject: string;
+ }
+
+ export interface MarketingAnalyticsRecommendationsQueryResponse {
+ /** Caveat to show with the results. The results are suggestions, and impact figures are estimates. */
+ disclaimer: string;
+ /** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
+ error?: string | null;
+ /** Generated HogQL query. */
+ hogql?: string | null;
+ /** Modifiers used when performing the query */
+ modifiers?: HogQLQueryModifiers | null;
+ /** Query status indicates whether next to the provided data, a query is still running. */
+ query_status?: QueryStatus | null;
+ /** The resolved previous/comparison period date range, when comparing against another period */
+ resolved_compare_date_range?: ResolvedDateRangeResponse | null;
+ /** The date range used for the query */
+ resolved_date_range?: ResolvedDateRangeResponse | null;
+ results: MarketingAnalyticsRecommendation[];
+ /** Measured timings for different parts of the query generation process */
+ timings?: QueryTiming[] | null;
+ /** 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 type MarketingAnalyticsRecommendationsSourceType = typeof MarketingAnalyticsRecommendationsSourceType[keyof typeof MarketingAnalyticsRecommendationsSourceType];
+
+
+ export const MarketingAnalyticsRecommendationsSourceType = {
+ GoogleAds: 'GoogleAds',
+ GoogleSearchConsole: 'GoogleSearchConsole',
+ } as const;
+
+ export interface MarketingAnalyticsRecommendationsSource {
+ /** Google Ads daily campaign impression share table. */
+ campaignImpressionShareTable?: string | null;
+ /** Google Ads daily campaign stats table. */
+ campaignStatsTable?: string | null;
+ /** Google Ads campaign table. */
+ campaignTable?: string | null;
+ /** Google Ads customer table, used for the account currency. */
+ customerTable?: string | null;
+ /** Google Ads search term table for Performance Max campaigns. */
+ performanceMaxSearchTermTable?: string | null;
+ /** Google Search Console table with one row per query, or per query and page. */
+ queryTable?: string | null;
+ /** Google Ads search term table split by the keyword that matched each term. */
+ searchTermKeywordTable?: string | null;
+ /** Google Ads search term table for Search campaigns. */
+ searchTermTable?: string | null;
+ /** Google Search Console sites table, used to infer the brand name. */
+ sitesTable?: string | null;
+ sourceType: MarketingAnalyticsRecommendationsSourceType;
+ }
+
+ export interface MarketingAnalyticsRecommendationsQuery {
+ dateRange?: DateRange | null;
+ kind?: 'MarketingAnalyticsRecommendationsQuery';
+ /** Modifiers used when performing the query */
+ modifiers?: HogQLQueryModifiers | null;
+ response?: MarketingAnalyticsRecommendationsQueryResponse | null;
+ /** Tables to read. Omit to read every synced Google Ads and Google Search Console source in the project. */
+ sources?: MarketingAnalyticsRecommendationsSource[] | null;
+ tags?: QueryLogTags | null;
+ /** version of the node, used for schema migrations */
+ version?: number | null;
+ }
+
export type WebAgentContentGrouping = typeof WebAgentContentGrouping[keyof typeof WebAgentContentGrouping];
@@ -63973,7 +64098,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 | MarketingAnalyticsRetentionQuery | MarketingAnalyticsSearchQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebAgentAnalyticsQuery | WebPageDirectoryQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingFingerprintProjectionQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingReleasesQuery | ErrorTrackingIssueCorrelationQuery | ErrorTrackingIssueEventsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | MetricsHistogramQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | CalendarHeatmapQuery | RecordingsQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPModelBreakdownQuery | MCPProtocolVersionBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolCategoryMapQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | MCPMissingCapabilitiesQuery | null;
+ sourceQuery?: EventsNode | ActionsNode | PersonsNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | MarketingAnalyticsRetentionQuery | MarketingAnalyticsSearchQuery | MarketingAnalyticsRecommendationsQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebAgentAnalyticsQuery | WebPageDirectoryQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingFingerprintProjectionQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingReleasesQuery | ErrorTrackingIssueCorrelationQuery | ErrorTrackingIssueEventsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | MetricsHistogramQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | CalendarHeatmapQuery | RecordingsQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPModelBreakdownQuery | MCPProtocolVersionBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolCategoryMapQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | MCPMissingCapabilitiesQuery | null;
tags?: QueryLogTags | null;
/** Variables to be subsituted into the query */
variables?: HogQLMetadataVariables;
@@ -63999,7 +64124,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 | MarketingAnalyticsRetentionQuery | MarketingAnalyticsSearchQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebAgentAnalyticsQuery | WebPageDirectoryQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingFingerprintProjectionQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingReleasesQuery | ErrorTrackingIssueCorrelationQuery | ErrorTrackingIssueEventsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | MetricsHistogramQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | CalendarHeatmapQuery | RecordingsQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPModelBreakdownQuery | MCPProtocolVersionBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolCategoryMapQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | MCPMissingCapabilitiesQuery | null;
+ sourceQuery?: EventsNode | ActionsNode | PersonsNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | MarketingAnalyticsRetentionQuery | MarketingAnalyticsSearchQuery | MarketingAnalyticsRecommendationsQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebAgentAnalyticsQuery | WebPageDirectoryQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingFingerprintProjectionQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingReleasesQuery | ErrorTrackingIssueCorrelationQuery | ErrorTrackingIssueEventsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | MetricsHistogramQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | CalendarHeatmapQuery | RecordingsQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPModelBreakdownQuery | MCPProtocolVersionBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolCategoryMapQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | MCPMissingCapabilitiesQuery | null;
/** Start position of the editor word */
startPosition: number;
tags?: QueryLogTags | null;
@@ -100551,7 +100676,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 | ErrorTrackingIssueEventsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebAgentAnalyticsQuery | WebPageDirectoryQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | MarketingAnalyticsRetentionQuery | MarketingAnalyticsSearchQuery | DataVisualizationNode | BIVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | PathsV2Query | StickinessQuery | LifecycleQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | MetricsHistogramQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPModelBreakdownQuery | MCPProtocolVersionBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolCategoryMapQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | MCPMissingCapabilitiesQuery | 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 | ErrorTrackingIssueEventsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebAgentAnalyticsQuery | WebPageDirectoryQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | MarketingAnalyticsRetentionQuery | MarketingAnalyticsSearchQuery | MarketingAnalyticsRecommendationsQuery | DataVisualizationNode | BIVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | PathsV2Query | StickinessQuery | LifecycleQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | MetricsHistogramQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPModelBreakdownQuery | MCPProtocolVersionBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolCategoryMapQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | MCPMissingCapabilitiesQuery | 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
@@ -101519,6 +101644,30 @@ export namespace Schemas {
}
export interface QueryResponseAlternative39 {
+ /** Caveat to show with the results. The results are suggestions, and impact figures are estimates. */
+ disclaimer: string;
+ /** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
+ error?: string | null;
+ /** Generated HogQL query. */
+ hogql?: string | null;
+ /** Modifiers used when performing the query */
+ modifiers?: HogQLQueryModifiers | null;
+ /** Query status indicates whether next to the provided data, a query is still running. */
+ query_status?: QueryStatus | null;
+ /** The resolved previous/comparison period date range, when comparing against another period */
+ resolved_compare_date_range?: ResolvedDateRangeResponse | null;
+ /** The date range used for the query */
+ resolved_date_range?: ResolvedDateRangeResponse | null;
+ results: MarketingAnalyticsRecommendation[];
+ /** Measured timings for different parts of the query generation process */
+ timings?: QueryTiming[] | null;
+ /** 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 QueryResponseAlternative40 {
columns: unknown[];
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -101547,7 +101696,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;
@@ -101575,7 +101724,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative41 {
+ export interface QueryResponseAlternative42 {
columns: unknown[];
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -101603,7 +101752,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative42 {
+ export interface QueryResponseAlternative43 {
/** Executed ClickHouse query */
clickhouse?: string | null;
/** Display formats for directly selected virtual properties, aligned with columns. */
@@ -101642,7 +101791,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative43 {
+ export interface QueryResponseAlternative44 {
dateFrom?: string | null;
dateTo?: string | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
@@ -101674,7 +101823,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;
@@ -101709,7 +101858,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;
@@ -101737,7 +101886,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;
@@ -101764,7 +101913,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative47 {
+ export interface QueryResponseAlternative48 {
columns?: unknown[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -101799,7 +101948,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative48 {
+ export interface QueryResponseAlternative49 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -101832,7 +101981,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative49 {
+ export interface QueryResponseAlternative50 {
columns?: unknown[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -101859,7 +102008,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative50 {
+ export interface QueryResponseAlternative51 {
columns: unknown[];
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -101886,7 +102035,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative51 {
+ export interface QueryResponseAlternative52 {
columns?: unknown[] | null;
/** ISO timestamp of the oldest precompute window backing this result — surfaced as "data as of X". */
dataComputedAt?: string | null;
@@ -101918,9 +102067,9 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export type QueryResponseAlternative52Results = {[key: string]: MarketingAnalyticsItem};
+ export type QueryResponseAlternative53Results = {[key: string]: MarketingAnalyticsItem};
- export interface QueryResponseAlternative52 {
+ export interface QueryResponseAlternative53 {
/** ISO timestamp of the oldest precompute window backing this result — surfaced as "data as of X". */
dataComputedAt?: string | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
@@ -101937,7 +102086,7 @@ export namespace Schemas {
resolved_compare_date_range?: ResolvedDateRangeResponse | null;
/** The date range used for the query */
resolved_date_range?: ResolvedDateRangeResponse | null;
- results: QueryResponseAlternative52Results;
+ results: QueryResponseAlternative53Results;
samplingRate?: SamplingRate | null;
/** Measured timings for different parts of the query generation process */
timings?: QueryTiming[] | null;
@@ -101947,7 +102096,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;
@@ -101973,7 +102122,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative54 {
+ export interface QueryResponseAlternative55 {
columns?: string[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -101999,7 +102148,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative55 {
+ export interface QueryResponseAlternative56 {
columns?: string[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -102025,7 +102174,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative57 {
+ export interface QueryResponseAlternative58 {
columns?: unknown[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -102052,7 +102201,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative58 {
+ export interface QueryResponseAlternative59 {
columns: unknown[];
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -102082,7 +102231,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative59 {
+ export interface QueryResponseAlternative60 {
columns?: (AccountsTableAccountFieldColumn | AccountsTableTagsColumn | AccountsTableNoteCountColumn | AccountsTableRelationshipColumn | AccountsTableCustomPropertyColumn | AccountsTableCustomPropertyHistoryColumn)[] | null;
customPropertyDefinitions?: AccountsTableCustomPropertyDefinition[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
@@ -102116,13 +102265,13 @@ export namespace Schemas {
/**
* The name of each action the query's series reference, keyed by action id. A series saved without a `name` displays this name, because the query holds only the action's id.
*/
- export type QueryResponseAlternative60ActionNames = {[key: string]: string} | null;
+ export type QueryResponseAlternative61ActionNames = {[key: string]: string} | null;
- export type QueryResponseAlternative60ResultsItem = { [key: string]: unknown };
+ export type QueryResponseAlternative61ResultsItem = { [key: string]: unknown };
- export interface QueryResponseAlternative60 {
+ export interface QueryResponseAlternative61 {
/** The name of each action the query's series reference, keyed by action id. A series saved without a `name` displays this name, because the query holds only the action's id. */
- action_names?: QueryResponseAlternative60ActionNames;
+ action_names?: QueryResponseAlternative61ActionNames;
boxplot_data?: BoxPlotDatum[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -102138,7 +102287,7 @@ export namespace Schemas {
resolved_compare_date_range?: ResolvedDateRangeResponse | null;
/** The date range used for the query */
resolved_date_range?: ResolvedDateRangeResponse | null;
- results: QueryResponseAlternative60ResultsItem[];
+ results: QueryResponseAlternative61ResultsItem[];
/** Measured timings for different parts of the query generation process */
timings?: QueryTiming[] | null;
/** Connector-synced data warehouse sources referenced by this query, if any. */
@@ -102147,7 +102296,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;
/** Generated HogQL query. */
@@ -102171,7 +102320,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative62 {
+ export interface QueryResponseAlternative63 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -102193,7 +102342,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. */
@@ -102215,7 +102364,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. */
@@ -102240,13 +102389,13 @@ export namespace Schemas {
/**
* The name of each action the query's series reference, keyed by action id. A series saved without a `name` displays this name, because the query holds only the action's id.
*/
- export type QueryResponseAlternative65ActionNames = {[key: string]: string} | null;
+ export type QueryResponseAlternative66ActionNames = {[key: string]: string} | null;
- export type QueryResponseAlternative65ResultsItem = { [key: string]: unknown };
+ export type QueryResponseAlternative66ResultsItem = { [key: string]: unknown };
- export interface QueryResponseAlternative65 {
+ export interface QueryResponseAlternative66 {
/** The name of each action the query's series reference, keyed by action id. A series saved without a `name` displays this name, because the query holds only the action's id. */
- action_names?: QueryResponseAlternative65ActionNames;
+ action_names?: QueryResponseAlternative66ActionNames;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -102259,7 +102408,7 @@ export namespace Schemas {
resolved_compare_date_range?: ResolvedDateRangeResponse | null;
/** The date range used for the query */
resolved_date_range?: ResolvedDateRangeResponse | null;
- results: QueryResponseAlternative65ResultsItem[];
+ results: QueryResponseAlternative66ResultsItem[];
/** Measured timings for different parts of the query generation process */
timings?: QueryTiming[] | null;
/** Connector-synced data warehouse sources referenced by this query, if any. */
@@ -102268,14 +102417,14 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export type QueryResponseAlternative67Tables = {[key: string]: DatabaseSchemaPostHogTable | DatabaseSchemaSystemTable | DatabaseSchemaDataWarehouseTable | DatabaseSchemaViewTable | DatabaseSchemaManagedViewTable | DatabaseSchemaBatchExportTable | DatabaseSchemaMaterializedViewTable | DatabaseSchemaEndpointTable};
+ export type QueryResponseAlternative68Tables = {[key: string]: DatabaseSchemaPostHogTable | DatabaseSchemaSystemTable | DatabaseSchemaDataWarehouseTable | DatabaseSchemaViewTable | DatabaseSchemaManagedViewTable | DatabaseSchemaBatchExportTable | DatabaseSchemaMaterializedViewTable | DatabaseSchemaEndpointTable};
- export interface QueryResponseAlternative67 {
+ export interface QueryResponseAlternative68 {
joins: DataWarehouseViewLink[];
- tables: QueryResponseAlternative67Tables;
+ tables: QueryResponseAlternative68Tables;
}
- export interface QueryResponseAlternative68 {
+ export interface QueryResponseAlternative69 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
has_next: boolean;
@@ -102300,7 +102449,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative69 {
+ export interface QueryResponseAlternative70 {
columns?: string[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -102328,7 +102477,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative70 {
+ export interface QueryResponseAlternative71 {
count: number;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -102351,7 +102500,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative71 {
+ export interface QueryResponseAlternative72 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -102373,7 +102522,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative72 {
+ export interface QueryResponseAlternative73 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -102395,7 +102544,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative73 {
+ export interface QueryResponseAlternative74 {
/** Upper bound per row (y axis), ascending. */
bounds: number[];
/** Observation count per cell: counts[row][column], row = bound, column = time. */
@@ -102423,7 +102572,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;
hasMore?: boolean | null;
@@ -102450,7 +102599,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative75 {
+ export interface QueryResponseAlternative76 {
/** 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. */
@@ -102474,7 +102623,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative76 {
+ export interface QueryResponseAlternative77 {
/** 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. */
@@ -102498,7 +102647,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?: AttributeBreakdownRow[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
@@ -102522,13 +102671,13 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative78 {
+ export interface QueryResponseAlternative79 {
questions: string[];
/** Data warehouse sync warnings — see AnalyticsQueryResponseBase.warnings for semantics. */
warnings?: DataWarehouseSyncWarning[] | null;
}
- export interface QueryResponseAlternative79 {
+ export interface QueryResponseAlternative80 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
hasMore?: boolean | null;
@@ -102553,7 +102702,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative80 {
+ export interface QueryResponseAlternative81 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
hasMore?: boolean | null;
@@ -102578,7 +102727,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative81 {
+ export interface QueryResponseAlternative82 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -102600,7 +102749,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative82 {
+ export interface QueryResponseAlternative83 {
columns?: string[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -102626,7 +102775,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative85 {
+ export interface QueryResponseAlternative86 {
/** Timestamp of the newer trace */
newerTimestamp?: string | null;
/** ID of the newer trace (chronologically after current) */
@@ -102641,7 +102790,7 @@ export namespace Schemas {
warnings?: DataWarehouseSyncWarning[] | null;
}
- export interface QueryResponseAlternative86 {
+ export interface QueryResponseAlternative87 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -102663,7 +102812,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative87 {
+ export interface QueryResponseAlternative88 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -102685,7 +102834,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative88 {
+ export interface QueryResponseAlternative89 {
columns: unknown[];
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -102715,7 +102864,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative89 {
+ export interface QueryResponseAlternative90 {
columns?: (AccountsTableAccountFieldColumn | AccountsTableTagsColumn | AccountsTableNoteCountColumn | AccountsTableRelationshipColumn | AccountsTableCustomPropertyColumn | AccountsTableCustomPropertyHistoryColumn)[] | null;
customPropertyDefinitions?: AccountsTableCustomPropertyDefinition[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
@@ -102746,7 +102895,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative90 {
+ export interface QueryResponseAlternative91 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -102768,7 +102917,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative91 {
+ export interface QueryResponseAlternative92 {
columns?: unknown[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -102795,9 +102944,9 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export type QueryResponseAlternative92ResultsItem = { [key: string]: unknown };
+ export type QueryResponseAlternative93ResultsItem = { [key: string]: unknown };
- 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. */
@@ -102810,7 +102959,7 @@ export namespace Schemas {
resolved_compare_date_range?: ResolvedDateRangeResponse | null;
/** The date range used for the query */
resolved_date_range?: ResolvedDateRangeResponse | null;
- results: QueryResponseAlternative92ResultsItem[];
+ results: QueryResponseAlternative93ResultsItem[];
/** Measured timings for different parts of the query generation process */
timings?: QueryTiming[] | null;
/** Connector-synced data warehouse sources referenced by this query, if any. */
@@ -102819,7 +102968,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative93 {
+ export interface QueryResponseAlternative94 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -102841,7 +102990,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative94 {
+ export interface QueryResponseAlternative95 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -102863,7 +103012,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. */
@@ -102885,7 +103034,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;
/** Whether another page of individual model identifiers is available. */
@@ -102909,7 +103058,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. */
@@ -102931,7 +103080,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. */
@@ -102953,7 +103102,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. */
@@ -102975,7 +103124,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. */
@@ -102997,7 +103146,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. */
@@ -103020,7 +103169,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. */
@@ -103042,7 +103191,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. */
@@ -103070,7 +103219,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. */
@@ -103092,7 +103241,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. */
@@ -103114,7 +103263,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. */
@@ -103136,7 +103285,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. */
@@ -103158,7 +103307,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. */
@@ -103180,7 +103329,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. */
@@ -103202,7 +103351,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. */
@@ -103224,7 +103373,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;
/** Whether more reports exist past this page. */
@@ -103248,7 +103397,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative112 {
+ export interface QueryResponseAlternative113 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -103270,7 +103419,7 @@ 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 | QueryResponseAlternative27 | 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 | QueryResponseAlternative55 | QueryResponseAlternative57 | QueryResponseAlternative58 | QueryResponseAlternative59 | QueryResponseAlternative60 | QueryResponseAlternative61 | QueryResponseAlternative62 | QueryResponseAlternative63 | QueryResponseAlternative64 | QueryResponseAlternative65 | QueryResponseAlternative67 | QueryResponseAlternative68 | QueryResponseAlternative69 | QueryResponseAlternative70 | QueryResponseAlternative71 | QueryResponseAlternative72 | QueryResponseAlternative73 | QueryResponseAlternative74 | QueryResponseAlternative75 | QueryResponseAlternative76 | QueryResponseAlternative77 | QueryResponseAlternative78 | QueryResponseAlternative79 | QueryResponseAlternative80 | QueryResponseAlternative81 | QueryResponseAlternative82 | QueryResponseAlternative85 | QueryResponseAlternative86 | 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 | QueryResponseAlternative112;
+ 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 | QueryResponseAlternative27 | QueryResponseAlternative28 | QueryResponseAlternative29 | QueryResponseAlternative30 | QueryResponseAlternative31 | QueryResponseAlternative32 | QueryResponseAlternative33 | QueryResponseAlternative34 | QueryResponseAlternative35 | QueryResponseAlternative36 | QueryResponseAlternative37 | QueryResponseAlternative38 | QueryResponseAlternative39 | unknown | QueryResponseAlternative40 | QueryResponseAlternative41 | QueryResponseAlternative42 | QueryResponseAlternative43 | QueryResponseAlternative44 | QueryResponseAlternative45 | QueryResponseAlternative46 | QueryResponseAlternative47 | QueryResponseAlternative48 | QueryResponseAlternative49 | QueryResponseAlternative50 | QueryResponseAlternative51 | QueryResponseAlternative52 | QueryResponseAlternative53 | QueryResponseAlternative54 | QueryResponseAlternative55 | QueryResponseAlternative56 | QueryResponseAlternative58 | QueryResponseAlternative59 | QueryResponseAlternative60 | QueryResponseAlternative61 | QueryResponseAlternative62 | QueryResponseAlternative63 | QueryResponseAlternative64 | QueryResponseAlternative65 | QueryResponseAlternative66 | QueryResponseAlternative68 | QueryResponseAlternative69 | QueryResponseAlternative70 | QueryResponseAlternative71 | QueryResponseAlternative72 | QueryResponseAlternative73 | QueryResponseAlternative74 | QueryResponseAlternative75 | QueryResponseAlternative76 | QueryResponseAlternative77 | QueryResponseAlternative78 | QueryResponseAlternative79 | QueryResponseAlternative80 | QueryResponseAlternative81 | QueryResponseAlternative82 | QueryResponseAlternative83 | QueryResponseAlternative86 | 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 | QueryResponseAlternative112 | QueryResponseAlternative113;
export interface QueryScanResponse {
analysis?: QueryScanAnalysis | null;
@@ -103281,11 +103430,11 @@ export namespace Schemas {
}
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 | ErrorTrackingIssueEventsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebAgentAnalyticsQuery | WebPageDirectoryQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | MarketingAnalyticsRetentionQuery | MarketingAnalyticsSearchQuery | DataVisualizationNode | BIVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | PathsV2Query | StickinessQuery | LifecycleQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | MetricsHistogramQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPModelBreakdownQuery | MCPProtocolVersionBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolCategoryMapQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | MCPMissingCapabilitiesQuery | 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 | ErrorTrackingIssueEventsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebAgentAnalyticsQuery | WebPageDirectoryQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | MarketingAnalyticsRetentionQuery | MarketingAnalyticsSearchQuery | MarketingAnalyticsRecommendationsQuery | DataVisualizationNode | BIVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | PathsV2Query | StickinessQuery | LifecycleQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | MetricsHistogramQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPModelBreakdownQuery | MCPProtocolVersionBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolCategoryMapQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | MCPMissingCapabilitiesQuery | 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 | ErrorTrackingIssueEventsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebAgentAnalyticsQuery | WebPageDirectoryQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | MarketingAnalyticsRetentionQuery | MarketingAnalyticsSearchQuery | DataVisualizationNode | BIVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | PathsV2Query | StickinessQuery | LifecycleQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | MetricsHistogramQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPModelBreakdownQuery | MCPProtocolVersionBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolCategoryMapQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | MCPMissingCapabilitiesQuery | 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 | ErrorTrackingIssueEventsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebAgentAnalyticsQuery | WebPageDirectoryQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | MarketingAnalyticsRetentionQuery | MarketingAnalyticsSearchQuery | MarketingAnalyticsRecommendationsQuery | DataVisualizationNode | BIVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | PathsV2Query | StickinessQuery | LifecycleQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | MetricsHistogramQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPModelBreakdownQuery | MCPProtocolVersionBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolCategoryMapQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | MCPMissingCapabilitiesQuery | PropertyValuesQuery;
}
export interface QuotaResourceLimit {
diff --git a/services/mcp/src/tools/generated/marketing_analytics.ts b/services/mcp/src/tools/generated/marketing_analytics.ts
index c789c48f7126..9ac058677879 100644
--- a/services/mcp/src/tools/generated/marketing_analytics.ts
+++ b/services/mcp/src/tools/generated/marketing_analytics.ts
@@ -3,6 +3,7 @@ import { z } from 'zod'
import type { Schemas } from '@/api/generated'
import * as orvalSchemas from '@/generated/marketing_analytics/api'
+import { createQueryWrapper } from '@/tools/query-wrapper-factory'
import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
const MarketingAnalyticsConversionGoalsSchema = () => z.object({})
@@ -352,6 +353,87 @@ const marketingAnalyticsUtmAudit = (): ToolBase<
},
})
+// --- Query wrapper schemas from schema.json ---
+
+const DateRange = z.object({
+ date_from: z
+ .string()
+ .nullable()
+ .describe(
+ 'Start of the date range. Accepts ISO 8601 timestamps (e.g., 2024-01-15T00:00:00Z) or relative formats: -7d (7 days ago), -2w (2 weeks ago), -1m (1 month ago),\n-1h (1 hour ago), -1mStart (start of last month), -1yStart (start of last year).'
+ )
+ .optional(),
+ date_to: z
+ .string()
+ .nullable()
+ .describe(
+ 'End of the date range. Same format as date_from. Omit or null for "now". A calendar day without a time (2024-01-15) is inclusive: it rounds to the last moment of that day in the project timezone, unless explicitDate is set.'
+ )
+ .optional(),
+ daysOfWeek: z
+ .union([
+ z.array(
+ z.union([
+ z.literal(1),
+ z.literal(2),
+ z.literal(3),
+ z.literal(4),
+ z.literal(5),
+ z.literal(6),
+ z.literal(7),
+ ])
+ ),
+ z.null(),
+ ])
+ .describe(
+ 'Restrict the query to events occurring on these ISO days of week (1=Monday to 7=Sunday), evaluated in the project timezone. Omit or empty for all days. Only applied by insight queries.'
+ )
+ .optional(),
+ excludeIncompletePeriods: z.coerce
+ .boolean()
+ .nullable()
+ .describe(
+ 'Exclude the current, still-collecting period by clipping date_to to the end of the last complete interval (evaluated in the project timezone). No-op when the range contains no complete interval. Only applied by insight queries.'
+ )
+ .default(false)
+ .optional(),
+ explicitDate: z.coerce
+ .boolean()
+ .nullable()
+ .describe(
+ 'Whether the date_from and date_to should be used verbatim. Disables rounding to the start and end of period.'
+ )
+ .default(false)
+ .optional(),
+})
+
+const QueryLogTags = z.object({
+ name: z.string().describe('Name of the query, preferably unique. For example web_analytics_vitals').optional(),
+ presetId: z
+ .string()
+ .describe('Short id of the saved Web analytics filter preset this query was run under, if any.')
+ .optional(),
+ productKey: z
+ .string()
+ .describe(
+ "Product responsible for this query. Use string, there's no need to churn the Schema when we add a new product *"
+ )
+ .optional(),
+ scene: z
+ .string()
+ .describe(
+ "Scene where this query is shown in the UI. Use string, there's no need to churn the Schema when we add a new Scene *"
+ )
+ .optional(),
+})
+
+const MarketingAnalyticsRecommendationsQuery = z.object({
+ dateRange: DateRange.optional(),
+ kind: z.literal('MarketingAnalyticsRecommendationsQuery').default('MarketingAnalyticsRecommendationsQuery'),
+ tags: QueryLogTags.optional(),
+ version: z.coerce.number().describe('version of the node, used for schema migrations').optional(),
+})
+
export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'marketing-analytics-conversion-goals': marketingAnalyticsConversionGoals,
'marketing-analytics-conversion-recommendations': marketingAnalyticsConversionRecommendations,
@@ -366,4 +448,11 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'marketing-analytics-suggest-utm-mappings': marketingAnalyticsSuggestUtmMappings,
'marketing-analytics-update-conversion-goal': marketingAnalyticsUpdateConversionGoal,
'marketing-analytics-utm-audit': marketingAnalyticsUtmAudit,
+ 'query-marketing-recommendations': createQueryWrapper({
+ name: 'query-marketing-recommendations',
+ schema: MarketingAnalyticsRecommendationsQuery,
+ kind: 'MarketingAnalyticsRecommendationsQuery',
+ outputFormat: 'json',
+ urlPrefix: '/marketing',
+ }),
}
diff --git a/services/mcp/src/tools/query-wrapper-factory.ts b/services/mcp/src/tools/query-wrapper-factory.ts
index cd7baaa7a5fa..6da0a60182a8 100644
--- a/services/mcp/src/tools/query-wrapper-factory.ts
+++ b/services/mcp/src/tools/query-wrapper-factory.ts
@@ -250,6 +250,7 @@ export function createQueryWrapper<T extends ZodObjectAny>(config: QueryWrapperC
// column names are the only way to read each cell.
...(Array.isArray(data.columns) && Array.isArray(data.results) ? { columns: data.columns } : {}),
...(data.warnings ? { warnings: data.warnings } : {}),
+ ...(typeof data.disclaimer === 'string' ? { disclaimer: data.disclaimer } : {}),
// Cursor-paginated queries (e.g. RecordingsQuery) need these for the caller to request the next page.
...(typeof data.has_next === 'boolean'
? { has_next: data.has_next, next_cursor: data.next_cursor ?? null }
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-marketing-recommendations.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-marketing-recommendations.json
new file mode 100644
index 000000000000..28d1ddf935de
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-marketing-recommendations.json
@@ -0,0 +1,130 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "dateRange": {
+ "properties": {
+ "date_from": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Start of the date range. Accepts ISO 8601 timestamps (e.g., 2024-01-15T00:00:00Z) or relative formats: -7d (7 days ago), -2w (2 weeks ago), -1m (1 month ago),\n-1h (1 hour ago), -1mStart (start of last month), -1yStart (start of last year)."
+ },
+ "date_to": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "End of the date range. Same format as date_from. Omit or null for \"now\". A calendar day without a time (2024-01-15) is inclusive: it rounds to the last moment of that day in the project timezone, unless explicitDate is set."
+ },
+ "daysOfWeek": {
+ "anyOf": [
+ {
+ "items": {
+ "anyOf": [
+ {
+ "const": 1,
+ "type": "number"
+ },
+ {
+ "const": 2,
+ "type": "number"
+ },
+ {
+ "const": 3,
+ "type": "number"
+ },
+ {
+ "const": 4,
+ "type": "number"
+ },
+ {
+ "const": 5,
+ "type": "number"
+ },
+ {
+ "const": 6,
+ "type": "number"
+ },
+ {
+ "const": 7,
+ "type": "number"
+ }
+ ]
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Restrict the query to events occurring on these ISO days of week (1=Monday to 7=Sunday), evaluated in the project timezone. Omit or empty for all days. Only applied by insight queries."
+ },
+ "excludeIncompletePeriods": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": false,
+ "description": "Exclude the current, still-collecting period by clipping date_to to the end of the last complete interval (evaluated in the project timezone). No-op when the range contains no complete interval. Only applied by insight queries."
+ },
+ "explicitDate": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": false,
+ "description": "Whether the date_from and date_to should be used verbatim. Disables rounding to the start and end of period."
+ }
+ },
+ "type": "object"
+ },
+ "kind": {
+ "const": "MarketingAnalyticsRecommendationsQuery",
+ "default": "MarketingAnalyticsRecommendationsQuery",
+ "type": "string"
+ },
+ "tags": {
+ "properties": {
+ "name": {
+ "description": "Name of the query, preferably unique. For example web_analytics_vitals",
+ "type": "string"
+ },
+ "presetId": {
+ "description": "Short id of the saved Web analytics filter preset this query was run under, if any.",
+ "type": "string"
+ },
+ "productKey": {
+ "description": "Product responsible for this query. Use string, there's no need to churn the Schema when we add a new product *",
+ "type": "string"
+ },
+ "scene": {
+ "description": "Scene where this query is shown in the UI. Use string, there's no need to churn the Schema when we add a new Scene *",
+ "type": "string"
+ }
+ },
+ "type": "object"
+ },
+ "version": {
+ "description": "version of the node, used for schema migrations",
+ "type": "number"
+ }
+ },
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/query-wrapper-factory.test.ts b/services/mcp/tests/unit/query-wrapper-factory.test.ts
index 4b99a86b9329..750e707de67f 100644
--- a/services/mcp/tests/unit/query-wrapper-factory.test.ts
+++ b/services/mcp/tests/unit/query-wrapper-factory.test.ts
@@ -637,6 +637,18 @@ describe('createQueryWrapper warnings', () => {
const result = (await tool.handler(contextWithRunQuery({ results: [] }), { kind: 'HogQLQuery' })) as any
expect(result).not.toHaveProperty('warnings')
+ expect(result).not.toHaveProperty('disclaimer')
+ })
+
+ it('forwards the disclaimer the backend attaches to the results', async () => {
+ const disclaimer = 'These are suggestions. Review each one before you act on it.'
+ const tool = createQueryWrapper({ name: 'test', schema, kind: 'MarketingAnalyticsRecommendationsQuery' })()
+
+ const result = (await tool.handler(contextWithRunQuery({ results: [], disclaimer }), {
+ kind: 'MarketingAnalyticsRecommendationsQuery',
+ })) as any
+
+ expect(result.disclaimer).toBe(disclaimer)
})
})
diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.ts
index 28371244e4a7..492e6e41dc75 100644
--- a/services/mcp/tests/unit/tool-filtering.test.ts
+++ b/services/mcp/tests/unit/tool-filtering.test.ts
@@ -1121,6 +1121,7 @@ describe('Tool Filtering - Feature Flags', () => {
'llm-analytics-tags',
'workflows-destination-suggestion',
'marketing-analytics-conversion-setup-ai',
+ 'marketing-analytics-recommendations',
'insight-data-checks',
'logs-agent-tools',
'workflows-transactional-email-api',
diff --git a/services/mcp/tests/unit/tool-schema-snapshots.test.ts b/services/mcp/tests/unit/tool-schema-snapshots.test.ts
index cb242a85c9bf..1b48dbc61dfe 100644
--- a/services/mcp/tests/unit/tool-schema-snapshots.test.ts
+++ b/services/mcp/tests/unit/tool-schema-snapshots.test.ts
@@ -108,6 +108,7 @@ async function loadSnapshotTools(): Promise<Tool<ZodObjectAny>[]> {
'scouts-tool-access': true,
'subscription-source-summaries': true,
'marketing-analytics-conversion-setup-ai': true,
+ 'marketing-analytics-recommendations': true,
'workflows-mcp-onboarding': true,
'workflows-sending-tier-requests': true,
'insight-data-checks': true,