Skip to content

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

feat(marketing-analytics): add Max AI tools for diagnostics and audits (#58688)

Javier Bahamondesc44886ac25c2
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 4d5670eff358..7c58ac609298 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -356,6 +356,7 @@ export const FEATURE_FLAGS = {
LOGS_SQL_VIEW: 'logs-sql-view', // owner: #team-logs
LOGS_TABBED_VIEW: 'logs-tabbed-view', // owner: #team-logs
MANAGED_VIEWSETS: 'managed-viewsets', // owner: @rafaeelaudibert #team-revenue-analytics
+ MARKETING_ANALYTICS_AI: 'marketing-analytics-ai', // owner: @jabahamondes #team-web-analytics
MARKETING_ANALYTICS_DRILL_DOWN: 'marketing-analytics-drill-down', // owner: @jabahamondes #team-web-analytics
MARKETING_ANALYTICS_EXTENDED_DRILL_DOWN: 'marketing-analytics-extended-drill-down', // owner: @jabahamondes #team-web-analytics
MARKETING_ANALYTICS_MULTI_TOUCH_ATTRIBUTION: 'marketing-analytics-multi-touch-attribution', // owner: @jabahamondes #team-web-analytics
diff --git a/frontend/src/lib/scopes.tsx b/frontend/src/lib/scopes.tsx
index ea99c3623441..57ec4c33b6ff 100644
--- a/frontend/src/lib/scopes.tsx
+++ b/frontend/src/lib/scopes.tsx
@@ -69,6 +69,7 @@ export const API_SCOPES: APIScope[] = [
{ key: 'llm_provider_key', objectName: 'LLM provider key', objectPlural: 'LLM provider keys' },
{ key: 'llm_skill', objectName: 'LLM skill', objectPlural: 'LLM skills' },
{ key: 'logs', objectName: 'Logs', objectPlural: 'logs' },
+ { key: 'marketing_analytics', objectName: 'Marketing analytics', objectPlural: 'marketing analytics' },
{ key: 'notebook', objectName: 'Notebook', objectPlural: 'notebooks' },
{ key: 'organization', objectName: 'Organization', objectPlural: 'organizations', disabledWhenProjectScoped: true },
{
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 1a686fa04e54..606c03e6e803 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -3559,7 +3559,14 @@
"search_llm_traces",
"run_hog_eval_test",
"diagnose_proxy",
- "web_analytics_doctor"
+ "web_analytics_doctor",
+ "marketing_diagnose_setup",
+ "marketing_explain_conversion_goal",
+ "marketing_list_conversion_goals",
+ "marketing_list_data_sources",
+ "marketing_audit_utm",
+ "marketing_suggest_conversion_goals",
+ "marketing_suggest_utm_mappings"
],
"type": "string"
},
diff --git a/frontend/src/queries/schema/schema-assistant-messages.ts b/frontend/src/queries/schema/schema-assistant-messages.ts
index b3feadd000a2..7406cf78ea5d 100644
--- a/frontend/src/queries/schema/schema-assistant-messages.ts
+++ b/frontend/src/queries/schema/schema-assistant-messages.ts
@@ -499,6 +499,13 @@ export type AssistantTool =
| 'run_hog_eval_test'
| 'diagnose_proxy'
| 'web_analytics_doctor'
+ | 'marketing_diagnose_setup'
+ | 'marketing_explain_conversion_goal'
+ | 'marketing_list_conversion_goals'
+ | 'marketing_list_data_sources'
+ | 'marketing_audit_utm'
+ | 'marketing_suggest_conversion_goals'
+ | 'marketing_suggest_utm_mappings'
export enum AgentMode {
ProductAnalytics = 'product_analytics',
diff --git a/frontend/src/scenes/marketing-analytics/MarketingAnalyticsScene.tsx b/frontend/src/scenes/marketing-analytics/MarketingAnalyticsScene.tsx
index da58182686ea..efba71cefed1 100644
--- a/frontend/src/scenes/marketing-analytics/MarketingAnalyticsScene.tsx
+++ b/frontend/src/scenes/marketing-analytics/MarketingAnalyticsScene.tsx
@@ -2,11 +2,13 @@ import clsx from 'clsx'
import { BindLogic, useActions, useValues } from 'kea'
import { useEffect } from 'react'
-import { IconGear } from '@posthog/icons'
+import { IconGear, IconSparkles } from '@posthog/icons'
import { LemonBanner, LemonButton, LemonSkeleton, LemonTabs, Link } from '@posthog/lemon-ui'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { MaxTool } from 'scenes/max/MaxTool'
+import { useMaxTool } from 'scenes/max/useMaxTool'
import { sceneConfigurations } from 'scenes/scenes'
import { Scene, SceneExport } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
@@ -215,6 +217,55 @@ const TAB_DESCRIPTIONS: Record<string, string> = {
'Check that your ad platform campaigns are properly linked to UTM tracking in PostHog.',
}
+const MarketingAnalyticsAIToolWrapper = ({ children }: { children: React.ReactNode }): JSX.Element => {
+ const { dateFilter, integrationFilter, compareFilter } = useValues(marketingAnalyticsLogic)
+ const { conversion_goals, marketingAnalyticsConfig } = useValues(marketingAnalyticsSettingsLogic)
+ const { featureFlags } = useValues(featureFlagLogic)
+ const aiEnabled = !!featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_AI]
+
+ // Shared context for every Marketing analytics Max tool — consumed by
+ // MARKETING_CONTEXT_PROMPT in products/marketing_analytics/backend/max_tools.py.
+ const maxContext = {
+ current_filters: { integrationFilter, compareFilter },
+ current_date_range: { date_from: dateFilter.dateFrom, date_to: dateFilter.dateTo },
+ custom_source_mappings_count: Object.keys(marketingAnalyticsConfig?.custom_source_mappings || {}).length,
+ campaign_name_mappings_count: Object.keys(marketingAnalyticsConfig?.campaign_name_mappings || {}).length,
+ existing_goal_count: (conversion_goals || []).length,
+ }
+
+ // Register the follow-up tools so Max can actually call them when the
+ // diagnostic recommends them. Only `marketing_diagnose_setup` gets the
+ // visible MaxTool button below — the rest are data tools with no UI anchor.
+ useMaxTool({ identifier: 'marketing_explain_conversion_goal', context: maxContext, active: aiEnabled })
+ useMaxTool({ identifier: 'marketing_list_conversion_goals', context: maxContext, active: aiEnabled })
+ useMaxTool({ identifier: 'marketing_list_data_sources', context: maxContext, active: aiEnabled })
+ useMaxTool({ identifier: 'marketing_audit_utm', context: maxContext, active: aiEnabled })
+ useMaxTool({ identifier: 'marketing_suggest_conversion_goals', context: maxContext, active: aiEnabled })
+ useMaxTool({ identifier: 'marketing_suggest_utm_mappings', context: maxContext, active: aiEnabled })
+
+ return (
+ <MaxTool
+ identifier="marketing_diagnose_setup"
+ active={aiEnabled}
+ context={maxContext}
+ contextDescription={{
+ text: 'Marketing analytics setup',
+ icon: <IconSparkles />,
+ }}
+ initialMaxPrompt="Diagnose my marketing analytics setup"
+ suggestions={[
+ 'Diagnose my marketing analytics setup',
+ 'Why are events showing as non-integrated?',
+ 'Suggest custom_source_mappings for unmatched UTM values',
+ 'Which custom events would make good conversion goals?',
+ 'List my conversion goals and their last-30d performance',
+ ]}
+ >
+ <>{children}</>
+ </MaxTool>
+ )
+}
+
export function MarketingAnalyticsScene(): JSX.Element {
const { activeTab } = useValues(marketingAnalyticsLogic)
@@ -253,7 +304,9 @@ export function MarketingAnalyticsScene(): JSX.Element {
</>
}
/>
- <MarketingAnalyticsContent />
+ <MarketingAnalyticsAIToolWrapper>
+ <MarketingAnalyticsContent />
+ </MarketingAnalyticsAIToolWrapper>
</SceneContent>
</BindLogic>
</BindLogic>
diff --git a/frontend/src/scenes/max/max-constants.tsx b/frontend/src/scenes/max/max-constants.tsx
index b9e003d1bfc8..484948d90921 100644
--- a/frontend/src/scenes/max/max-constants.tsx
+++ b/frontend/src/scenes/max/max-constants.tsx
@@ -752,6 +752,65 @@ export const TOOL_DEFINITIONS: Record<AssistantTool, ToolDefinition> = {
return toolCall.status === 'completed' ? 'Diagnosed web analytics' : 'Diagnosing web analytics...'
},
},
+ marketing_diagnose_setup: {
+ name: 'Diagnose marketing analytics',
+ description:
+ 'Diagnose marketing analytics setup with a health check across data sources, attribution, and conversion goals',
+ product: Scene.MarketingAnalytics,
+ icon: iconForType('marketing_analytics'),
+ displayFormatter: (toolCall) =>
+ toolCall.status === 'completed' ? 'Diagnosed marketing analytics' : 'Diagnosing marketing analytics...',
+ },
+ marketing_explain_conversion_goal: {
+ name: 'Explain a conversion goal',
+ description:
+ 'Explain a conversion goal by showing which events drove its count, broken down by source and integration',
+ product: Scene.MarketingAnalytics,
+ icon: iconForType('marketing_analytics'),
+ displayFormatter: (toolCall) =>
+ toolCall.status === 'completed' ? 'Explained conversion goal' : 'Explaining conversion goal...',
+ },
+ marketing_list_conversion_goals: {
+ name: 'List conversion goals',
+ description: 'List conversion goals with their last-30d performance',
+ product: Scene.MarketingAnalytics,
+ icon: iconForType('marketing_analytics'),
+ displayFormatter: (toolCall) =>
+ toolCall.status === 'completed' ? 'Listed conversion goals' : 'Listing conversion goals...',
+ },
+ marketing_list_data_sources: {
+ name: 'List marketing data sources',
+ description: 'List marketing data sources with platform-side health for every connected ad integration',
+ product: Scene.MarketingAnalytics,
+ icon: iconForType('marketing_analytics'),
+ displayFormatter: (toolCall) =>
+ toolCall.status === 'completed' ? 'Listed marketing data sources' : 'Listing marketing data sources...',
+ },
+ marketing_audit_utm: {
+ name: 'Audit UTM tagging',
+ description: 'Audit UTM tagging to find issues that prevent attribution to ad platforms',
+ product: Scene.MarketingAnalytics,
+ icon: iconForType('marketing_analytics'),
+ displayFormatter: (toolCall) =>
+ toolCall.status === 'completed' ? 'Audited UTM tagging' : 'Auditing UTM tagging...',
+ },
+ marketing_suggest_conversion_goals: {
+ name: 'Suggest conversion goals',
+ description: 'Suggest conversion goals by ranking custom events that are good candidates',
+ product: Scene.MarketingAnalytics,
+ icon: iconForType('marketing_analytics'),
+ displayFormatter: (toolCall) =>
+ toolCall.status === 'completed' ? 'Suggested conversion goals' : 'Suggesting conversion goals...',
+ },
+ marketing_suggest_utm_mappings: {
+ name: 'Suggest UTM mappings',
+ description:
+ 'Suggest UTM mappings by detecting unmatched utm_source values and proposing custom_source_mappings entries',
+ product: Scene.MarketingAnalytics,
+ icon: iconForType('marketing_analytics'),
+ displayFormatter: (toolCall) =>
+ toolCall.status === 'completed' ? 'Suggested UTM mappings' : 'Suggesting UTM mappings...',
+ },
upsert_dashboard: {
name: 'Create and edit dashboards',
description: 'Create and edit dashboards with insights based on your requirements',
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 30389151e04b..0097ec3db85c 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -5368,6 +5368,7 @@ export type APIScopeObject =
| 'llm_provider_key'
| 'llm_skill'
| 'logs'
+ | 'marketing_analytics'
| 'notebook'
| 'organization'
| 'organization_integration'
diff --git a/posthog/rbac/user_access_control.py b/posthog/rbac/user_access_control.py
index 78078d7789f7..db1ba14fc454 100644
--- a/posthog/rbac/user_access_control.py
+++ b/posthog/rbac/user_access_control.py
@@ -89,6 +89,11 @@ RESOURCE_INHERITANCE_MAP: dict[APIScopeObject, APIScopeObject] = {
"customer_journey": "customer_analytics",
"experiment_saved_metric": "experiment",
"dashboard_template": "dashboard",
+ # Marketing analytics doesn't have its own RBAC resource yet — inherit from
+ # web_analytics so the existing per-team controls actually gate it (matches
+ # the frontend mapping in sceneTypes.ts: Scene.MarketingAnalytics ->
+ # AccessControlResourceType.WebAnalytics).
+ "marketing_analytics": "web_analytics",
}
tracer = trace.get_tracer(__name__)
diff --git a/posthog/schema.py b/posthog/schema.py
index 88c584e08599..aeb87e81755d 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -737,6 +737,13 @@ class AssistantTool(StrEnum):
RUN_HOG_EVAL_TEST = "run_hog_eval_test"
DIAGNOSE_PROXY = "diagnose_proxy"
WEB_ANALYTICS_DOCTOR = "web_analytics_doctor"
+ MARKETING_DIAGNOSE_SETUP = "marketing_diagnose_setup"
+ MARKETING_EXPLAIN_CONVERSION_GOAL = "marketing_explain_conversion_goal"
+ MARKETING_LIST_CONVERSION_GOALS = "marketing_list_conversion_goals"
+ MARKETING_LIST_DATA_SOURCES = "marketing_list_data_sources"
+ MARKETING_AUDIT_UTM = "marketing_audit_utm"
+ MARKETING_SUGGEST_CONVERSION_GOALS = "marketing_suggest_conversion_goals"
+ MARKETING_SUGGEST_UTM_MAPPINGS = "marketing_suggest_utm_mappings"
class AssistantToolCall(BaseModel):
diff --git a/posthog/scopes.py b/posthog/scopes.py
index 49223e689f16..74a16bd5f4a8 100644
--- a/posthog/scopes.py
+++ b/posthog/scopes.py
@@ -68,6 +68,7 @@ APIScopeObject = Literal[
"llm_provider_key",
"llm_skill",
"logs",
+ "marketing_analytics",
"notebook",
"organization",
"organization_integration",
diff --git a/posthog/security/llm_prompt_sanitization.py b/posthog/security/llm_prompt_sanitization.py
new file mode 100644
index 000000000000..b6271e104cb6
--- /dev/null
+++ b/posthog/security/llm_prompt_sanitization.py
@@ -0,0 +1,90 @@
+"""Sanitize user-controlled text before embedding it in an LLM prompt.
+
+Shared across products (subscriptions, marketing analytics, Max tools).
+"""
+
+from __future__ import annotations
+
+import re
+import unicodedata
+
+INSIGHT_NAME_MAX_LEN = 120
+INSIGHT_DESCRIPTION_MAX_LEN = 500
+SERIES_LABEL_MAX_LEN = 200
+SUBSCRIPTION_TITLE_MAX_LEN = 200
+GENERIC_VALUE_MAX_LEN = 200
+PROMPT_GUIDE_MAX_LEN = 500
+# `CoreMemory.formatted_text` returns `text[:2500] + "…" + text[-2500:]` when the
+# raw text exceeds 5000 chars — that's 5001 chars total. Match what the upstream
+# helper can actually produce so we don't silently drop the last tail character.
+CORE_MEMORY_MAX_LEN = 5001
+
+_TAG_RE = re.compile(r"</?[a-zA-Z_][^>]*>")
+_LLM_MARKER_RE = re.compile(
+ r"</?\s*(?:system|user|assistant|human|insight_data|user_context|subscription_title|core_memory)\b[^>]*>?",
+ re.IGNORECASE,
+)
+_NEWLINE_RE = re.compile(r"[\r\n\u2028\u2029]+")
+_WHITESPACE_RUN_RE = re.compile(r"[ \t]+")
+
+_INVISIBLE_KEEP = {"\n", "\r", "\t"}
+_EXTRA_INVISIBLES = (
+ {"\u034f", "\u3164", "\uffa0"}
+ | {chr(c) for c in range(0x115F, 0x1161)}
+ | {chr(c) for c in range(0x17B4, 0x17B6)}
+ | {chr(c) for c in range(0x180B, 0x180E)}
+ | {chr(c) for c in range(0xFE00, 0xFE10)}
+ | {chr(c) for c in range(0xE0100, 0xE01F0)}
+)
+
+
+def _is_invisible(c: str) -> bool:
+ if c in _INVISIBLE_KEEP:
+ return False
+ if unicodedata.category(c) in ("Cc", "Cf"):
+ return True
+ return c in _EXTRA_INVISIBLES
+
+
+def _strip_invisible(value: str) -> str:
+ return "".join(c for c in value if not _is_invisible(c))
+
+
+def sanitize_user_text(
+ value: str | None,
+ max_len: int,
+ *,
+ none_placeholder: str = "",
+ truncate_marker: str = "",
+) -> str:
+ if not value:
+ return none_placeholder
+ cleaned = _strip_invisible(value)
+ previous = ""
+ while previous != cleaned:
+ previous = cleaned
+ cleaned = _LLM_MARKER_RE.sub("", cleaned)
+ cleaned = _TAG_RE.sub("", cleaned)
+ cleaned = _NEWLINE_RE.sub(" ", cleaned)
+ cleaned = _WHITESPACE_RUN_RE.sub(" ", cleaned).strip()
+ if not cleaned:
+ return none_placeholder
+ if len(cleaned) > max_len:
+ cleaned = cleaned[:max_len].rstrip() + truncate_marker
+ return cleaned
+
+
+def sanitize_core_memory_text(value: str | None, max_len: int = CORE_MEMORY_MAX_LEN) -> str:
+ """Sanitize core memory facts. Preserves newlines so each fact stays on its own line,
+ but strips structural LLM markers so the memory cannot escape its `<core_memory>` wrapper."""
+ if not value:
+ return ""
+ cleaned = _strip_invisible(value)
+ previous = ""
+ while previous != cleaned:
+ previous = cleaned
+ cleaned = _LLM_MARKER_RE.sub("", cleaned)
+ cleaned = cleaned.strip()
+ if len(cleaned) > max_len:
+ cleaned = cleaned[:max_len].rstrip()
+ return cleaned
diff --git a/posthog/temporal/subscriptions/prompt_sanitization.py b/posthog/temporal/subscriptions/prompt_sanitization.py
index 087641128b9d..2539fc6b7add 100644
--- a/posthog/temporal/subscriptions/prompt_sanitization.py
+++ b/posthog/temporal/subscriptions/prompt_sanitization.py
@@ -1,77 +1,31 @@
-from __future__ import annotations
-
-import re
-import unicodedata
-
-INSIGHT_NAME_MAX_LEN = 120
-INSIGHT_DESCRIPTION_MAX_LEN = 500
-SERIES_LABEL_MAX_LEN = 200
-SUBSCRIPTION_TITLE_MAX_LEN = 200
-GENERIC_VALUE_MAX_LEN = 200
-PROMPT_GUIDE_MAX_LEN = 500
-# `CoreMemory.formatted_text` returns `text[:2500] + "…" + text[-2500:]` when the
-# raw text exceeds 5000 chars — that's 5001 chars total. Match what the upstream
-# helper can actually produce so we don't silently drop the last tail character.
-CORE_MEMORY_MAX_LEN = 5001
-
-_TAG_RE = re.compile(r"</?[a-zA-Z_][^>]*>")
-_LLM_MARKER_RE = re.compile(
- r"</?\s*(?:system|user|assistant|human|insight_data|user_context|subscription_title|core_memory)\b[^>]*>?",
- re.IGNORECASE,
+"""Backwards-compat re-export. The real implementation now lives in
+`posthog.security.llm_prompt_sanitization` so it can be shared across products
+(marketing analytics, subscriptions, future Max tools).
+
+Keep these imports stable — `llm_change_summary.py` and any external pins
+import from here.
+"""
+
+from posthog.security.llm_prompt_sanitization import (
+ CORE_MEMORY_MAX_LEN,
+ GENERIC_VALUE_MAX_LEN,
+ INSIGHT_DESCRIPTION_MAX_LEN,
+ INSIGHT_NAME_MAX_LEN,
+ PROMPT_GUIDE_MAX_LEN,
+ SERIES_LABEL_MAX_LEN,
+ SUBSCRIPTION_TITLE_MAX_LEN,
+ sanitize_core_memory_text,
+ sanitize_user_text,
)
-_NEWLINE_RE = re.compile(r"[\r\n\u2028\u2029]+")
-_WHITESPACE_RUN_RE = re.compile(r"[ \t]+")
-
-_INVISIBLE_KEEP = {"\n", "\r", "\t"}
-_EXTRA_INVISIBLES = (
- {"\u034f", "\u3164", "\uffa0"}
- | {chr(c) for c in range(0x115F, 0x1161)}
- | {chr(c) for c in range(0x17B4, 0x17B6)}
- | {chr(c) for c in range(0x180B, 0x180E)}
- | {chr(c) for c in range(0xFE00, 0xFE10)}
- | {chr(c) for c in range(0xE0100, 0xE01F0)}
-)
-
-
-def _is_invisible(c: str) -> bool:
- if c in _INVISIBLE_KEEP:
- return False
- if unicodedata.category(c) in ("Cc", "Cf"):
- return True
- return c in _EXTRA_INVISIBLES
-
-
-def _strip_invisible(value: str) -> str:
- return "".join(c for c in value if not _is_invisible(c))
-
-
-def sanitize_user_text(value: str | None, max_len: int) -> str:
- if not value:
- return ""
- cleaned = _strip_invisible(value)
- previous = ""
- while previous != cleaned:
- previous = cleaned
- cleaned = _LLM_MARKER_RE.sub("", cleaned)
- cleaned = _TAG_RE.sub("", cleaned)
- cleaned = _NEWLINE_RE.sub(" ", cleaned)
- cleaned = _WHITESPACE_RUN_RE.sub(" ", cleaned).strip()
- if len(cleaned) > max_len:
- cleaned = cleaned[:max_len].rstrip()
- return cleaned
-
-def sanitize_core_memory_text(value: str | None, max_len: int = CORE_MEMORY_MAX_LEN) -> str:
- """Sanitize core memory facts. Preserves newlines so each fact stays on its own line,
- but strips structural LLM markers so the memory cannot escape its `<core_memory>` wrapper."""
- if not value:
- return ""
- cleaned = _strip_invisible(value)
- previous = ""
- while previous != cleaned:
- previous = cleaned
- cleaned = _LLM_MARKER_RE.sub("", cleaned)
- cleaned = cleaned.strip()
- if len(cleaned) > max_len:
- cleaned = cleaned[:max_len].rstrip()
- return cleaned
+__all__ = [
+ "CORE_MEMORY_MAX_LEN",
+ "GENERIC_VALUE_MAX_LEN",
+ "INSIGHT_DESCRIPTION_MAX_LEN",
+ "INSIGHT_NAME_MAX_LEN",
+ "PROMPT_GUIDE_MAX_LEN",
+ "SERIES_LABEL_MAX_LEN",
+ "SUBSCRIPTION_TITLE_MAX_LEN",
+ "sanitize_core_memory_text",
+ "sanitize_user_text",
+]
diff --git a/products/marketing_analytics/backend/max_tools.py b/products/marketing_analytics/backend/max_tools.py
new file mode 100644
index 000000000000..deaf4da0e157
--- /dev/null
+++ b/products/marketing_analytics/backend/max_tools.py
@@ -0,0 +1,799 @@
+"""MaxTool wrappers around Marketing analytics services.
+
+The LangChain surface (args schema, descriptions, context, access checks) lives
+here; the business logic lives in `services/`.
+"""
+
+from dataclasses import asdict
+from datetime import datetime
+from textwrap import dedent
+from typing import Any
+from zoneinfo import ZoneInfo
+
+from django.utils import timezone
+
+import structlog
+from pydantic import BaseModel, Field
+
+from posthog.schema import DateRange
+
+from posthog.models.team.team import Team
+from posthog.rbac.user_access_control import AccessControlLevel
+from posthog.scopes import APIScopeObject
+from posthog.security.llm_prompt_sanitization import GENERIC_VALUE_MAX_LEN, sanitize_user_text
+from posthog.sync import database_sync_to_async
+from posthog.utils import relative_date_parse
+
+from products.marketing_analytics.backend.services.conversion_goals_inspector import (
+ explain_conversion_goal,
+ list_conversion_goals,
+)
+from products.marketing_analytics.backend.services.data_source_health import get_data_source_health
+from products.marketing_analytics.backend.services.event_suggestions import suggest_conversion_goals
+from products.marketing_analytics.backend.services.mapping_suggester import suggest_utm_mappings
+from products.marketing_analytics.backend.services.marketing_diagnostic import get_marketing_diagnostic
+from products.marketing_analytics.backend.services.utm_audit import run_utm_audit
+
+from ee.hogai.tool import MaxTool
+
+logger = structlog.get_logger(__name__)
+
+# Cap attribution scans server-side: an unbounded utm_source scan over multi-year
+# windows can pin a ClickHouse node on a high-volume team, and this surface isn't interactive.
+MAX_LOOKBACK_DAYS = 365
+
+# Shared context for tools mounted on /marketing — keeps the root node from
+# conflating Marketing with Web analytics or misstating the attribution model.
+MARKETING_CONTEXT_PROMPT = dedent("""
+ User is on /marketing — the Marketing analytics product, NOT Web analytics.
+
+ Distinctions to keep in mind:
+ - Marketing analytics 'Reported conversions' = numbers PULLED from connected ad platforms via their APIs (Google Ads metrics_conversions, Meta CAPI, etc.). PostHog does not compute these.
+ - Marketing analytics 'Conversion goals' = PostHog events/actions configured by the team to be matched with UTM-tagged sessions for attribution.
+ - Web analytics 'Goals' are a SEPARATE concept from Marketing analytics conversion goals; do not conflate them.
+ - Marketing analytics is a built-in feature page at /marketing, not a configurable dashboard. Its tabular view cannot be added as a component to other dashboards.
+ - Marketing analytics supports first-touch, last-touch, and multi-touch attribution (linear, time-decay, position-based). The team's active model is reported as `attribution_mode` by the conversion-goal tools — read it rather than assuming. Multi-touch distributes conversion credit across the UTM touchpoints seen within the team's attribution window before each conversion. ML-based "data-driven" attribution is not available.
+
+ Current filters: {current_filters}
+ Current date range: {current_date_range}
+ Configured custom_source_mappings count: {custom_source_mappings_count}
+ Configured campaign_name_mappings count: {campaign_name_mappings_count}
+ Existing conversion goal count: {existing_goal_count}
+""").strip()
+
+
+def _marketing_resource() -> list[tuple[APIScopeObject, AccessControlLevel]]:
+ return [("marketing_analytics", "viewer")]
+
+
+def _lookback_days_from_date_range(team: Team, date_range: dict | None) -> int | None:
+ """Convert the frontend `current_date_range` to a lookback in days, parsed in the
+ team's timezone (relative or ISO). Returns None when unparseable."""
+ if not date_range or not isinstance(date_range, dict):
+ return None
+ raw_from = date_range.get("date_from")
+ if not raw_from:
+ return None
+ raw_to = date_range.get("date_to")
+
+ tz = ZoneInfo(team.timezone)
+ try:
+ start = relative_date_parse(str(raw_from), tz)
+ end = relative_date_parse(str(raw_to), tz) if raw_to else timezone.now().astimezone(tz)
+ except Exception:
+ logger.warning("marketing_lookback_date_parse_failed", team_id=team.pk, date_range=date_range)
+ return None
+
+ delta = (end - start).days
+ return delta if delta > 0 else None
+
+
+def _resolve_lookback_days(team: Team, self_context: dict, requested: int | None, fallback: int) -> int:
+ """Resolve `lookback_days`: explicit > inferred-from-context > fallback, all
+ clamped to MAX_LOOKBACK_DAYS."""
+ if requested is not None and requested > 0:
+ return min(requested, MAX_LOOKBACK_DAYS)
+ inferred = _lookback_days_from_date_range(team, self_context.get("current_date_range"))
+ if inferred is not None:
+ return min(inferred, MAX_LOOKBACK_DAYS)
+ return min(fallback, MAX_LOOKBACK_DAYS)
+
+
+# ---------- Tool 1: marketing_diagnose_setup ----------
+
+
+class MarketingDiagnoseSetupArgs(BaseModel):
+ include_conversion_goals: bool = Field(
+ default=True,
+ description="Whether to also load conversion goals as part of the diagnostic. Set to False for a faster sync+attribution-only check.",
+ )
+ source_type: str | None = Field(
+ default=None,
+ description="Optional. Filter the diagnostic to one integration (e.g. 'GoogleAds', 'MetaAds').",
+ )
+ attribution_lookback_days: int | None = Field(
+ default=None,
+ ge=1,
+ le=1095,
+ description=(
+ "Days of event history used for the attribution side. By default the tool reads the "
+ "user's currently visible date range from context (typically what they're looking at "
+ "in the dashboard) and uses that. Pass an explicit value (e.g. 7, 90, 365) only when "
+ "the user asks for a different window than what they're currently viewing."
+ ),
+ )
+
+
+class MarketingDiagnoseSetupTool(MaxTool):
+ name: str = "marketing_diagnose_setup"
+ description: str = dedent("""
+ READ-ONLY end-to-end diagnostic of Marketing analytics for the current project.
+
+ Returns:
+ - Per-integration overall_status (healthy / sync_broken / events_broken / events_unmatched / events_only / schema_misconfigured / not_connected)
+ - Sync state (last_sync_at, errors, row counts, schema mapping coverage)
+ - Attribution state (UTM-tagged events arriving, matched vs likely-yours-but-unmatched)
+ - Conversion goals with last-30d performance and misconfig flags
+ - Recommended next actions, each pointing to the right follow-up tool
+
+ USE THIS TOOL FIRST whenever the user asks why marketing analytics looks wrong, missing, or broken. Do NOT speculate about causes before calling this tool.
+ """).strip()
+ context_prompt_template: str = MARKETING_CONTEXT_PROMPT
+ args_schema: type[BaseModel] = MarketingDiagnoseSetupArgs
+
+ def get_required_resource_access(self) -> list[tuple[APIScopeObject, AccessControlLevel]]:
+ return _marketing_resource()
+
+ async def _arun_impl(
+ self,
+ include_conversion_goals: bool = True,
+ source_type: str | None = None,
+ attribution_lookback_days: int | None = None,
+ ) -> tuple[str, dict[str, Any]]:
+ resolved_lookback = _resolve_lookback_days(self._team, self.context, attribution_lookback_days, fallback=7)
+ response = await get_marketing_diagnostic(
+ self._team,
+ source_type=source_type,
+ include_conversion_goals=include_conversion_goals,
+ attribution_lookback_days=resolved_lookback,
+ )
+ return _format_diagnostic_for_llm(response), response.to_dict()
+
+
+# ---------- Tool 2: marketing_explain_conversion_goal ----------
+
+
+class MarketingExplainConversionGoalArgs(BaseModel):
+ goal_id: str = Field(
+ description="The id of the conversion goal to explain. Must match an id from `marketing_list_conversion_goals`.",
+ )
+ date_from: str | None = Field(
+ default=None,
+ description="ISO 8601 start of the period to explain. Defaults to 30 days ago.",
+ )
+ date_to: str | None = Field(
+ default=None,
+ description="ISO 8601 end of the period to explain. Defaults to now.",
+ )
+
+
+class MarketingExplainConversionGoalTool(MaxTool):
+ name: str = "marketing_explain_conversion_goal"
+ description: str = dedent("""
+ Break down the events that COUNT toward a conversion goal by their own utm_source, utm_campaign, and matched integration. Returns recent sample events for inspection.
+
+ This is a flat per-event breakdown of the conversion events themselves — NOT an analysis of the user's prior journey, and NOT the dashboard's attribution calculation (first-touch / last-touch / multi-touch weighting is applied by the dashboard, not here).
+
+ Use this when the user asks "what utm_sources are behind my N conversions?" or "where do these conversions come from?".
+
+ Only EventsNode and ActionsNode goals are explained at the event level. DataWarehouseNode goals are computed against external tables and short-circuit with a note.
+ """).strip()
+ context_prompt_template: str = MARKETING_CONTEXT_PROMPT
+ args_schema: type[BaseModel] = MarketingExplainConversionGoalArgs
+
+ def get_required_resource_access(self) -> list[tuple[APIScopeObject, AccessControlLevel]]:
+ return _marketing_resource()
+
+ async def _arun_impl(
+ self, goal_id: str, date_from: str | None = None, date_to: str | None = None
+ ) -> tuple[str, dict[str, Any]]:
+ period = None
+ if date_from or date_to:
+ period = DateRange(date_from=date_from, date_to=date_to)
+ try:
+ response = await explain_conversion_goal(self._team, goal_id, period=period)
+ except ValueError as exc:
+ return f"Could not explain goal: {exc}", {"error": "goal_not_found", "goal_id": goal_id}
+ return _format_explain_goal_for_llm(response), response.to_dict()
+
+
+# ---------- Tool 3: marketing_list_conversion_goals ----------
+
+
+class MarketingListConversionGoalsArgs(BaseModel):
+ pass
+
+
+class MarketingListConversionGoalsTool(MaxTool):
+ name: str = "marketing_list_conversion_goals"
+ description: str = dedent("""
+ Read the configured conversion goals for the current project. Each goal is returned with its kind (EventsNode / ActionsNode / DataWarehouseNode), target label, last-30d count, integrated vs non-integrated split, and a misconfiguration flag.
+
+ Use this BEFORE answering any question about which events are conversion goals or how many conversions there are.
+ """).strip()
+ context_prompt_template: str = MARKETING_CONTEXT_PROMPT
+ args_schema: type[BaseModel] = MarketingListConversionGoalsArgs
+
+ def get_required_resource_access(self) -> list[tuple[APIScopeObject, AccessControlLevel]]:
+ return _marketing_resource()
+
+ async def _arun_impl(self) -> tuple[str, dict[str, Any]]:
+ response = await list_conversion_goals(self._team)
+ return _format_conversion_goals_for_llm(response), response.to_dict()
+
+
+# ---------- Tool 4: marketing_list_data_sources ----------
+
+
+class MarketingListDataSourcesArgs(BaseModel):
+ source_type: str | None = Field(
+ default=None,
+ description="Optional. Restrict to one integration (e.g. 'GoogleAds').",
+ )
+
+
+class MarketingListDataSourcesTool(MaxTool):
+ name: str = "marketing_list_data_sources"
+ description: str = dedent("""
+ List the platform-side health of every native marketing integration: connected/not, last sync time and status, last error, rows synced, and schema-mapping coverage.
+
+ This is the platform → DW side only. For PostHog-events-side health (UTM matching), call `marketing_diagnose_setup`.
+ """).strip()
+ context_prompt_template: str = MARKETING_CONTEXT_PROMPT
+ args_schema: type[BaseModel] = MarketingListDataSourcesArgs
+
+ def get_required_resource_access(self) -> list[tuple[APIScopeObject, AccessControlLevel]]:
+ return _marketing_resource()
+
+ async def _arun_impl(self, source_type: str | None = None) -> tuple[str, dict[str, Any]]:
+ response = await get_data_source_health(self._team, source_type=source_type)
+ return _format_data_sources_for_llm(response), response.to_dict()
+
+
+# ---------- Tool 5: marketing_audit_utm ----------
+
+
+class MarketingAuditUtmArgs(BaseModel):
+ pass
+
+
+class MarketingAuditUtmTool(MaxTool):
+ name: str = "marketing_audit_utm"
+ description: str = dedent("""
+ Audit the UTM tagging quality of recent events: campaigns with issues, mismatched utm_source vs configured 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.
+ """).strip()
+ context_prompt_template: str = MARKETING_CONTEXT_PROMPT
+ args_schema: type[BaseModel] = MarketingAuditUtmArgs
+
+ def get_required_resource_access(self) -> list[tuple[APIScopeObject, AccessControlLevel]]:
+ return _marketing_resource()
+
+ async def _arun_impl(self) -> tuple[str, dict[str, Any]]:
+ # `run_utm_audit` is sync (legacy contract); wrap with the standard async helper.
+ response = await database_sync_to_async(run_utm_audit)(self._team)
+ return _format_audit_utm_for_llm(response), asdict(response)
+
+
+# ---------- Tool 6: marketing_suggest_conversion_goals ----------
+
+
+class MarketingSuggestConversionGoalsArgs(BaseModel):
+ top_n: int = Field(default=10, ge=1, le=50)
+ min_count: int = Field(
+ default=50, ge=0, description="Minimum 30d event count for an event to be considered a candidate."
+ )
+
+
+class MarketingSuggestConversionGoalsTool(MaxTool):
+ name: str = "marketing_suggest_conversion_goals"
+ description: str = dedent("""
+ Suggest custom events that are good candidates for becoming conversion goals. Ranks by volume, UTM tag coverage, and uniqueness of users. Excludes autocapture/system events and events that are already configured as goals.
+ """).strip()
+ context_prompt_template: str = MARKETING_CONTEXT_PROMPT
+ args_schema: type[BaseModel] = MarketingSuggestConversionGoalsArgs
+
+ def get_required_resource_access(self) -> list[tuple[APIScopeObject, AccessControlLevel]]:
+ return _marketing_resource()
+
+ async def _arun_impl(self, top_n: int = 10, min_count: int = 50) -> tuple[str, dict[str, Any]]:
+ response = await suggest_conversion_goals(self._team, top_n=top_n, min_count=min_count)
+ return _format_event_suggestions_for_llm(response), response.to_dict()
+
+
+# ---------- Tool 7: marketing_suggest_utm_mappings ----------
+
+
+class MarketingSuggestUtmMappingsArgs(BaseModel):
+ min_event_count: int = Field(
+ default=10,
+ ge=0,
+ description="Only suggest mappings for raw values with at least this many events in the lookback window.",
+ )
+ lookback_days: int | None = Field(
+ default=None,
+ ge=1,
+ le=1095,
+ description=(
+ "Days of event history to inspect. By default the tool reads the user's currently "
+ "visible date range from context (typically what they're looking at in the dashboard). "
+ "Pass an explicit value (e.g. 90, 365) only when the user asks for a different window "
+ "than what they're currently viewing. Falls back to 90 if context has no date range."
+ ),
+ )
+
+
+class MarketingSuggestUtmMappingsTool(MaxTool):
+ name: str = "marketing_suggest_utm_mappings"
+ description: str = dedent("""
+ USE THIS TOOL — DO NOT FALL BACK TO SQL — whenever the user asks about utm_source mappings, custom_source_mappings, unmatched / non-integrated UTM values, or the question "what utm_sources do I have and which ad platform do they belong to?".
+
+ Returns:
+ - `full_utm_source_catalogue`: every utm_source value seen on events in the window (matched + unmatched), with event count and which integration it resolves to (if any). Use this to answer "which UTMs are arriving" without running SQL.
+ - `source_suggestions`: mapping recommendations where a value's token matches a known alias (e.g. raw `facebook_paid` → MetaAds). For ambiguous values (typos like `fcebook`, novel sources) use `raw_unmatched_samples` and judge them yourself.
+ - `raw_unmatched_samples`: every unmatched value (including likely-not-an-ad values like `organic`, `newsletter`, `partner`).
+ - `current_mappings`: every alias already in effect (canonical + team_custom) so you don't suggest duplicates.
+
+ Defaults to last 90 days. Pass `lookback_days=365` (or more) when the user asks about a longer period or when 90 days returns no UTMs.
+
+ Read-only — applying mappings is a separate write tool (Phase 2).
+ """).strip()
+ context_prompt_template: str = MARKETING_CONTEXT_PROMPT
+ args_schema: type[BaseModel] = MarketingSuggestUtmMappingsArgs
+
+ def get_required_resource_access(self) -> list[tuple[APIScopeObject, AccessControlLevel]]:
+ return _marketing_resource()
+
+ async def _arun_impl(
+ self,
+ min_event_count: int = 10,
+ lookback_days: int | None = None,
+ ) -> tuple[str, dict[str, Any]]:
+ resolved_lookback = _resolve_lookback_days(self._team, self.context, lookback_days, fallback=90)
+ response = await suggest_utm_mappings(
+ self._team,
+ min_event_count=min_event_count,
+ lookback_days=resolved_lookback,
+ )
+ return _format_utm_mapping_suggestions_for_llm(response), response.to_dict()
+
+
+# --------------------------------------------------------------------------
+# LLM-facing content formatters
+# --------------------------------------------------------------------------
+# These turn a service response into the string the LLM uses to compose its reply,
+# so it must carry every datum the LLM needs. The `artifact` (dict) is for the frontend.
+
+
+def _sanitize_for_prompt(value: Any, max_len: int = GENERIC_VALUE_MAX_LEN) -> str:
+ """Sanitize a user-controlled event property for an LLM prompt: `<none>` for empty,
+ `…` on truncation. Coerces non-string values (event properties can be numbers)."""
+ text = str(value) if value is not None else None
+ return sanitize_user_text(text, max_len, none_placeholder="<none>", truncate_marker="…")
+
+
+def _format_timestamp_for_llm(dt: datetime | None) -> str:
+ """Render a timestamp with a pre-computed relative age — LLMs do date arithmetic
+ unreliably, so we compute "how long ago" here rather than letting the model."""
+ if dt is None:
+ return "never"
+ delta_days = (timezone.now() - dt).days
+ if delta_days < 0:
+ rel = "in the future — clock skew?"
+ elif delta_days == 0:
+ rel = "today"
+ elif delta_days == 1:
+ rel = "1 day ago"
+ else:
+ rel = f"{delta_days} days ago"
+ return f"{dt:%Y-%m-%d %H:%M} UTC ({rel})"
+
+
+def _format_diagnostic_for_llm(response) -> str:
+ lines: list[str] = [
+ "# Marketing analytics diagnostic",
+ f"Overall status: **{response.overall_status}** — {response.summary}",
+ "",
+ "REPORTING INSTRUCTIONS for the assistant:",
+ "- DO NOT agglomerate integrations into a single sentence (avoid phrasings like 'X integrations have schema issues').",
+ "- For every connected integration with an issue, name it explicitly and list its specific missing tables / columns / errors.",
+ "- Always include the `settings_url` and `fix_suggestion` so the user can click straight to the fix.",
+ "- `matched_pct` is matched events ÷ ALL team events carrying any utm_source — NOT a share of ad-platform clicks or impressions. Never describe it as 'X% of clicks'.",
+ "- Report sync timestamps exactly as given; the relative age is already computed — do not recompute it.",
+ "",
+ ]
+
+ integrations = response.integrations or []
+ if integrations:
+ lines.append("## Integrations (report each one individually)")
+ for entry in integrations:
+ lines.append(f"### {entry.display_name} (`{entry.source_type}`) — status: `{entry.overall_status}`")
+ lines.append(f"- diagnosis: {_sanitize_for_prompt(entry.diagnosis, max_len=500)}")
+ ds = entry.data_source
+ if ds is not None:
+ lines.append(f"- settings_url: {ds.settings_url}")
+ if ds.schemas_url:
+ lines.append(
+ f"- schemas_url: {ds.schemas_url} (per-source Schemas tab — for table enable/disable, retry failed syncs, reconnect)"
+ )
+ if ds.fix_suggestion:
+ lines.append(f"- fix_suggestion: {_sanitize_for_prompt(ds.fix_suggestion, max_len=500)}")
+ if ds is not None and ds.connected:
+ last_sync = _format_timestamp_for_llm(ds.last_sync_at)
+ lines.append(
+ f"- sync: `{ds.last_sync_status}`, last_sync_at={last_sync}, "
+ f"sync_activity_24h={ds.rows_last_24h} rows processed, "
+ f"sync_activity_7d={ds.rows_last_7d} rows processed "
+ f"(this is total sync throughput across all jobs in the window — "
+ f"not the row count of the source table)"
+ )
+ if ds.last_error:
+ # Third-party connector error body — highest-risk injection surface here.
+ lines.append(f"- last_error: {_sanitize_for_prompt(ds.last_error)}")
+ if ds.schema_columns_required_missing:
+ lines.append(f"- schema_columns_required_missing: {', '.join(ds.schema_columns_required_missing)}")
+ if ds.required_tables:
+ table_lines = []
+ for t in ds.required_tables:
+ if not t.present:
+ table_lines.append(f"`{t.table_name}` (missing)")
+ elif not t.should_sync:
+ table_lines.append(f"`{t.table_name}` (disabled, status={t.status})")
+ elif t.status == "Failed":
+ table_lines.append(f"`{t.table_name}` (FAILED)")
+ else:
+ table_lines.append(f"`{t.table_name}` ({t.status or 'unknown'})")
+ lines.append(f"- required_tables: {', '.join(table_lines)}")
+ attr = entry.attribution
+ if attr is not None:
+ lines.append(
+ f"- events: matched {attr.events_matched_last_7d} of "
+ f"{attr.events_with_utm_last_7d} team events-with-utm_source ({attr.matched_pct}%), "
+ f"likely-yours-but-unmatched={attr.events_unmatched_likely_yours_last_7d}"
+ )
+ if attr.sample_unmatched_utm_sources:
+ samples = ", ".join(
+ f"{_sanitize_for_prompt(s.raw_value)}({s.event_count})"
+ for s in attr.sample_unmatched_utm_sources[:5]
+ )
+ lines.append(f"- likely-yours unmatched samples: {samples}")
+ for action in entry.recommended_actions or []:
+ tool_hint = f" → call `{action.target_tool}`" if action.target_tool else ""
+ lines.append(f"- **action ({action.severity})**: {action.title}{tool_hint}")
+ if action.detail:
+ lines.append(f" {action.detail}")
+ lines.append("")
+
+ goals_resp = response.conversion_goals
+ if goals_resp is not None:
+ lines.append("## Conversion goals")
+ lines.append(
+ f"Attribution: `{goals_resp.attribution_mode}`, window: {goals_resp.attribution_window_days}d. "
+ f"{len(goals_resp.goals)} configured."
+ )
+ lines.append("")
+ lines.append(_NON_INTEGRATED_SPLIT_INSTRUCTIONS)
+ lines.append("")
+ for goal in goals_resp.goals or []:
+ lines.append(_format_goal_line(goal))
+ lines.append("")
+
+ if response.recommended_actions:
+ lines.append("## Top recommended actions")
+ for action in response.recommended_actions:
+ tool_hint = f" → call `{action.target_tool}`" if action.target_tool else ""
+ lines.append(f"- **({action.severity})** {action.title}{tool_hint}")
+ if action.detail:
+ lines.append(f" {action.detail}")
+
+ return "\n".join(lines)
+
+
+def _format_conversion_goals_for_llm(response) -> str:
+ if not response.goals:
+ return "No conversion goals are configured for this project."
+ lines: list[str] = [
+ f"Attribution: `{response.attribution_mode}`, window: {response.attribution_window_days}d. "
+ f"{len(response.goals)} configured. "
+ f"{'Some goals are misconfigured.' if response.has_misconfigured else 'All goals look valid.'}",
+ "",
+ _NON_INTEGRATED_SPLIT_INSTRUCTIONS,
+ "",
+ ]
+ for goal in response.goals:
+ lines.append(_format_goal_line(goal, include_id=True))
+ return "\n".join(lines)
+
+
+_NON_INTEGRATED_SPLIT_INSTRUCTIONS = dedent("""
+ REPORTING INSTRUCTIONS for `non_integrated_count` (CRITICAL — has two root causes with OPPOSITE fixes):
+
+ `non_integrated_count` = `events_without_utm_source` + `events_with_unmatched_utm_source`. These have DIFFERENT fixes:
+
+ - `events_without_utm_source`: the conversion event has NO `utm_source` property at all (the user landed without UTM tags, or the SDK is set up without UTM persistence).
+ Fix: tag the ad URLs with utm_source/utm_campaign, OR enable session-scoped UTM persistence so events fired later in the session inherit the entry-page UTMs.
+ DO NOT recommend `custom_source_mappings` for this bucket — there is nothing to map.
+ DO NOT recommend reconnecting an integration for this bucket — the events have no source attribution at all.
+
+ - `events_with_unmatched_utm_source`: the event has a `utm_source` value, but it doesn't match any known integration alias (canonical or team-custom).
+ Fix: add a `custom_source_mappings` entry, OR fix the upstream UTM tagging to use a recognized value.
+ Use `marketing_suggest_utm_mappings` to see the actual unmatched values and which ones look like ad platforms vs organic/direct/test.
+
+ When reporting on a goal's non-integrated count, ALWAYS break it down into these two buckets and propose the correct fix per bucket. Do NOT lump them together.
+""").strip()
+
+
+def _format_goal_line(goal, *, include_id: bool = False) -> str:
+ head = f"- id=`{goal.id}` " if include_id else "- "
+ line = f"{head}**{goal.name}** (`{goal.kind}`, target=`{goal.target_label}`) — last_30d={goal.last_30d_count}"
+ if goal.integrated_count is not None and goal.non_integrated_count is not None:
+ line += (
+ f", integrated={goal.integrated_count}, "
+ f"non_integrated={goal.non_integrated_count} "
+ f"(without_utm_source={goal.events_without_utm_source}, "
+ f"with_unmatched_utm_source={goal.events_with_unmatched_utm_source}), "
+ f"integrated_pct={goal.integrated_pct}%"
+ )
+ if goal.is_approximate:
+ line += f" (approximate — {goal.approximation_reason or 'approximate count'})"
+ if goal.is_misconfigured:
+ line += f" ⚠️ MISCONFIGURED: {goal.misconfig_reason}"
+ return line
+
+
+def _format_data_sources_for_llm(response) -> str:
+ connected = [e for e in response.integrations if e.connected]
+ lines: list[str] = [
+ f"Overall: **{response.overall_status}**. {len(connected)} of {len(response.integrations)} integrations connected.",
+ "",
+ "REPORTING INSTRUCTION: list each integration individually with its specific missing tables/columns/errors and the `settings_url`. Never agglomerate.",
+ "",
+ ]
+ for entry in response.integrations:
+ if not entry.connected:
+ lines.append(f"### {entry.display_name} — not connected (settings_url={entry.settings_url})")
+ continue
+ last_sync = _format_timestamp_for_llm(entry.last_sync_at)
+ lines.append(f"### {entry.display_name} — status=`{entry.last_sync_status}`")
+ if entry.schemas_url:
+ lines.append(f"- schemas_url: {entry.schemas_url}")
+ lines.append(f"- last_sync_at: {last_sync}")
+ lines.append(
+ f"- sync_activity_24h={entry.rows_last_24h} rows processed, "
+ f"sync_activity_7d={entry.rows_last_7d} rows processed "
+ f"(total throughput across sync jobs, not source-table row count)"
+ )
+ lines.append(f"- settings_url: {entry.settings_url}")
+ if entry.last_error:
+ lines.append(f"- last_error: {_sanitize_for_prompt(entry.last_error)}")
+ if entry.schema_columns_required_missing:
+ lines.append(f"- missing_required_columns: {', '.join(entry.schema_columns_required_missing)}")
+ if entry.required_tables:
+ table_lines = []
+ for t in entry.required_tables:
+ if not t.present:
+ table_lines.append(f"`{t.table_name}` (missing)")
+ elif not t.should_sync:
+ table_lines.append(f"`{t.table_name}` (disabled)")
+ elif t.status == "Failed":
+ table_lines.append(f"`{t.table_name}` (FAILED)")
+ else:
+ table_lines.append(f"`{t.table_name}` ({t.status or 'unknown'})")
+ lines.append(f"- required_tables: {', '.join(table_lines)}")
+ if entry.diagnosis:
+ lines.append(f"- diagnosis: {_sanitize_for_prompt(entry.diagnosis, max_len=500)}")
+ if entry.fix_suggestion:
+ lines.append(f"- fix: {_sanitize_for_prompt(entry.fix_suggestion, max_len=500)}")
+ lines.append("")
+ if response.issues_summary:
+ lines.append("## Issues summary")
+ for issue in response.issues_summary:
+ lines.append(f"- {issue}")
+ return "\n".join(lines)
+
+
+def _format_explain_goal_for_llm(response) -> str:
+ lines: list[str] = [
+ f"# Goal '{response.goal_name}' (`{response.kind}`)",
+ f"Period: {response.period.date_from} → {response.period.date_to}",
+ f"Total: {response.total_count}",
+ ]
+ if response.integrated_count is not None and response.non_integrated_count is not None:
+ lines.append(
+ f"Integrated: {response.integrated_count}, "
+ f"Non-integrated: {response.non_integrated_count} "
+ f"(without_utm_source={response.events_without_utm_source}, "
+ f"with_unmatched_utm_source={response.events_with_unmatched_utm_source})"
+ )
+ lines.append("")
+ lines.append(_NON_INTEGRATED_SPLIT_INSTRUCTIONS)
+
+ if response.by_event:
+ lines.append("\n## Events")
+ for name, count in response.by_event:
+ lines.append(f"- {_sanitize_for_prompt(name)}: {count}")
+ if response.by_utm_source:
+ lines.append("\n## utm_source breakdown")
+ for src, count in response.by_utm_source:
+ lines.append(f"- {_sanitize_for_prompt(src)}: {count}")
+ if response.by_matched_integration:
+ lines.append("\n## Matched to integration")
+ for integration, count in response.by_matched_integration:
+ lines.append(f"- {_sanitize_for_prompt(integration)}: {count}")
+ if response.samples:
+ lines.append("\n## Sample events (up to 10)")
+ for s in response.samples:
+ lines.append(
+ f"- {s.timestamp} distinct_id={_sanitize_for_prompt(s.distinct_id)} "
+ f"utm_source={_sanitize_for_prompt(s.utm_source)!r} "
+ f"utm_campaign={_sanitize_for_prompt(s.utm_campaign)!r} "
+ f"matched={_sanitize_for_prompt(s.matched_integration)!r}"
+ )
+ if response.notes:
+ lines.append("\n## Notes")
+ for note in response.notes:
+ lines.append(f"- {note}")
+ return "\n".join(lines)
+
+
+def _format_audit_utm_for_llm(response) -> str:
+ lines: list[str] = [
+ f"UTM audit: {response.campaigns_with_issues} of {response.total_campaigns} campaigns have issues. "
+ f"Total spend at risk: {response.total_spend_at_risk:.2f}.",
+ ]
+ issue_campaigns = [r for r in response.results if r.issues]
+ if issue_campaigns:
+ lines.append("\n## Campaigns with issues")
+ for r in issue_campaigns[:20]:
+ issue_summary = "; ".join(f"{i.severity}: {i.message}" for i in r.issues)
+ lines.append(
+ f"- **{_sanitize_for_prompt(r.campaign_name)}** ({_sanitize_for_prompt(r.source_name)}) — "
+ f"spend={r.spend}, clicks={r.clicks}, events={r.event_count}: {issue_summary}"
+ )
+ if response.all_utm_events:
+ unmatched = [e for e in response.all_utm_events if e.campaign_match == "none" or e.source_match == "none"]
+ if unmatched:
+ lines.append(f"\n## Unmatched UTM events (top 10 of {len(unmatched)})")
+ for e in unmatched[:10]:
+ lines.append(
+ f"- utm_source={_sanitize_for_prompt(e.utm_source)!r} "
+ f"utm_campaign={_sanitize_for_prompt(e.utm_campaign)!r} "
+ f"events={e.event_count} src_match={e.source_match} camp_match={e.campaign_match}"
+ )
+ return "\n".join(lines)
+
+
+def _format_event_suggestions_for_llm(response) -> str:
+ if not response.candidates:
+ return (
+ "No suitable candidate events found. Try lowering min_count or check that your project has custom events."
+ )
+ lines: list[str] = [
+ f"{len(response.candidates)} candidate events ranked by suitability as conversion goals "
+ f"(lookback={response.lookback_days}d):",
+ "",
+ ]
+ for c in response.candidates:
+ top_utm = (
+ ", ".join(f"{_sanitize_for_prompt(src)}({n})" for src, n in c.top_utm_sources[:3])
+ if c.top_utm_sources
+ else "(no utm_source samples)"
+ )
+ flag = " (already a goal)" if c.is_already_a_goal else ""
+ lines.append(
+ f"- **{_sanitize_for_prompt(c.event_name)}**{flag} — score={c.suggestion_score}, "
+ f"30d_count={c.last_30d_count}, users={c.distinct_users_30d}, "
+ f"utm_source_pct={c.pct_with_utm_source}%, utm_campaign_pct={c.pct_with_utm_campaign}%, "
+ f"top_utm=[{top_utm}]"
+ )
+ # Built from numeric stats today, but sanitize to stay safe if that changes.
+ lines.append(f" reason: {_sanitize_for_prompt(c.suggestion_reason, max_len=400)}")
+ return "\n".join(lines)
+
+
+def _format_utm_mapping_suggestions_for_llm(response) -> str:
+ window = f"the last {response.lookback_days_used} days"
+ lines: list[str] = [
+ f"Lookback window: {window}.",
+ f"Total events with utm_source in {window}: {response.total_events_with_utm_in_window}.",
+ f"Total events with UNMATCHED utm_source in {window}: {response.total_unmatched_events_in_window}.",
+ "",
+ "REPORTING INSTRUCTIONS for the assistant:",
+ "- DO NOT run a SQL query for this — `full_utm_source_catalogue` below already lists every utm_source value with counts and integration matches.",
+ "- ONLY report values that appear in `full_utm_source_catalogue` or `raw_unmatched_samples`. DO NOT invent canonical variants — those are already mapped canonically (see `current_mappings`).",
+ "- Many unmatched values are NOT ad platforms (organic, direct, test, newsletter, partner, twitter without a Twitter Ads integration). Don't suggest mapping those — recommend leaving them as non-integrated.",
+ "- Always qualify with the lookback window. Never say 'no UTMs ever' unless 1095+ days were checked.",
+ "",
+ ]
+
+ # Full catalogue first — this is the primary signal for the LLM.
+ if response.full_utm_source_catalogue:
+ lines.append(
+ f"## All utm_source values seen in {window} (top {len(response.full_utm_source_catalogue)} by event count)"
+ )
+ lines.append("| utm_source | events | matched? |")
+ lines.append("|---|---|---|")
+ for entry in response.full_utm_source_catalogue:
+ if entry.matched_integration_display_name:
+ match_col = f"✅ {entry.matched_integration_display_name}"
+ elif entry.suggested_integration:
+ match_col = f"≈ likely {entry.suggested_integration} (alias token)"
+ else:
+ match_col = "❌ unmatched"
+ lines.append(f"| `{_sanitize_for_prompt(entry.raw_utm_source)}` | {entry.event_count} | {match_col} |")
+ lines.append("")
+
+ # Suggestions: value's token matches a known alias, ready to apply
+ if response.source_suggestions:
+ lines.append(f"## Suggestions ({len(response.source_suggestions)})")
+ for s in response.source_suggestions:
+ lines.append(
+ f"- raw `{_sanitize_for_prompt(s.raw_utm_source)}` → **{s.suggested_target_display_name}** "
+ f"(events_in_window={s.event_count_30d})"
+ )
+ # `reason` embeds the raw utm_source value — sanitize.
+ lines.append(f" {_sanitize_for_prompt(s.reason, max_len=400)}")
+ lines.append("")
+ else:
+ lines.append("## Suggestions: none")
+ lines.append("")
+
+ # Raw catalogue: every unmatched value we saw, with the alias-token hint if any
+ if response.raw_unmatched_samples:
+ lines.append(
+ f"## Raw unmatched utm_source values seen in {window} "
+ f"(top {len(response.raw_unmatched_samples)} by event count)"
+ )
+ lines.append(
+ "These are the actual values arriving on events. Many will be organic/direct/test "
+ "and should NOT be mapped to ad platforms. Use this list to give a SPECIFIC answer."
+ )
+ for s in response.raw_unmatched_samples:
+ hint = (
+ f" — likely {s.suggested_integration} (alias token)"
+ if s.suggested_integration
+ else " — no alias match (likely organic/direct/test, or a typo to judge yourself)"
+ )
+ lines.append(f"- `{_sanitize_for_prompt(s.raw_utm_source)}` ({s.event_count} events){hint}")
+ lines.append("")
+
+ # Current mappings: canonical + team-custom
+ if response.current_mappings:
+ canonical = [m for m in response.current_mappings if m.source == "canonical"]
+ team_custom = [m for m in response.current_mappings if m.source == "team_custom"]
+ lines.append("## Already-active mappings (canonical aliases hardcoded by PostHog)")
+ # Group canonical by target for readability
+ by_target: dict[str, list[str]] = {}
+ for m in canonical:
+ by_target.setdefault(m.target_display_name, []).append(m.raw_utm_source)
+ for target, raws in sorted(by_target.items()):
+ lines.append(f"- **{target}**: {', '.join(sorted(raws))}")
+ if team_custom:
+ lines.append("")
+ lines.append("## Team-custom mappings already configured")
+ tc_by_target: dict[str, list[str]] = {}
+ for m in team_custom:
+ tc_by_target.setdefault(m.target_display_name, []).append(m.raw_utm_source)
+ for target, raws in sorted(tc_by_target.items()):
+ lines.append(f"- **{target}**: {', '.join(sorted(raws))}")
+ else:
+ lines.append("")
+ lines.append("## Team-custom mappings already configured: none")
+ lines.append("")
+
+ if response.notes:
+ lines.append("## Notes")
+ for note in response.notes:
+ lines.append(f"- {note}")
+ return "\n".join(lines)
diff --git a/products/marketing_analytics/backend/services/attribution_health.py b/products/marketing_analytics/backend/services/attribution_health.py
new file mode 100644
index 000000000000..9d2cfe984995
--- /dev/null
+++ b/products/marketing_analytics/backend/services/attribution_health.py
@@ -0,0 +1,309 @@
+"""Attribution-side health: are `utm_source` events arriving and do their values
+match each native integration?
+
+The DW-sync side lives in `data_source_health`; cross-domain correlation in
+`marketing_diagnostic`.
+"""
+
+import re
+from dataclasses import asdict, dataclass, field
+from datetime import datetime, timedelta
+from typing import Any, cast
+
+from django.utils import timezone
+
+import structlog
+
+from posthog.hogql import ast
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.clickhouse.query_tagging import Feature, Product, tags_context
+from posthog.models.team.team import Team
+from posthog.sync import database_sync_to_async
+
+from products.marketing_analytics.backend.services.native_integrations import (
+ EXTERNAL_SOURCE_TYPE_TO_NATIVE,
+ NATIVE_TO_KEY,
+ NativeIntegration,
+ build_combined_alias_map,
+ display_name_for_key,
+ lookup_in,
+ normalize,
+)
+
+logger = structlog.get_logger(__name__)
+
+# Default lookback window. Chosen to match `utm_audit` and the Marketing
+# Analytics dashboard's typical "last 7 days" view.
+DEFAULT_LOOKBACK_DAYS = 7
+
+# Cap on how many distinct utm_source values we report as samples per
+# integration. Keep small — this is fed to LLMs and dashboards.
+MAX_SAMPLE_UNMATCHED = 5
+
+# Cap on how many globally-unmatched raw values we surface. Higher than
+# MAX_SAMPLE_UNMATCHED because callers like `mapping_suggester` need the full
+# unmatched catalogue to reason about it.
+MAX_GLOBAL_UNMATCHED = 50
+
+# Cap on how many distinct utm_source values we pull from ClickHouse, ordered
+# by event count. Beyond this is long-tail typos; the response flags
+# `utm_source_catalogue_truncated` when the cap is hit so callers know the
+# totals are top-N subtotals rather than the full count.
+HOGQL_GROUP_LIMIT = 500
+
+
+@dataclass
+class UnmatchedUtmSample:
+ """A raw utm_source value that doesn't match any integration. `suggested_integration`
+ is set when one of its tokens is a known alias (e.g. `facebook_paid` → Meta)."""
+
+ raw_value: str
+ event_count: int
+ suggested_integration: NativeIntegration | None
+
+
+@dataclass
+class AttributionHealthEntry:
+ integration_key: NativeIntegration
+ display_name: str
+ events_with_utm_last_7d: int
+ events_matched_last_7d: int
+ events_unmatched_likely_yours_last_7d: int
+ last_event_with_matching_utm_at: datetime | None
+ matched_pct: float
+ sample_unmatched_utm_sources: list[UnmatchedUtmSample] = field(default_factory=list)
+
+
+@dataclass
+class UtmSourceSample:
+ """Catalogue entry for a raw utm_source value (matched or not). `matched_integration`
+ is an exact alias hit; `suggested_integration` is a softer token-level guess."""
+
+ raw_value: str
+ event_count: int
+ matched_integration: NativeIntegration | None
+ suggested_integration: NativeIntegration | None
+
+
+@dataclass
+class AttributionHealthResponse:
+ lookback_days: int
+ integrations: list[AttributionHealthEntry] = field(default_factory=list)
+ total_events_with_utm: int = 0
+ total_events_matched_to_any_integration: int = 0
+ total_events_unmatched: int = 0
+ sample_globally_unmatched: list[UnmatchedUtmSample] = field(default_factory=list)
+ # Full catalogue of utm_source values seen in the window (top N by count),
+ # both matched and unmatched. Lets callers answer "what utm_sources arrive
+ # on this team's events?" without a separate SQL roundtrip.
+ all_utm_source_samples: list[UtmSourceSample] = field(default_factory=list)
+ # Distinct utm_source values among the top `HOGQL_GROUP_LIMIT` by event count.
+ # When `utm_source_catalogue_truncated` is true this is a subtotal (capped at
+ # HOGQL_GROUP_LIMIT), not the true distinct count.
+ total_distinct_utm_sources: int = 0
+ # True when the ClickHouse aggregation hit HOGQL_GROUP_LIMIT distinct
+ # utm_source values: the long tail beyond that is uncounted, so
+ # `total_events_with_utm` and the totals above are top-N subtotals.
+ utm_source_catalogue_truncated: bool = False
+
+ def to_dict(self) -> dict[str, Any]:
+ return asdict(self)
+
+
+async def get_attribution_health(
+ team: Team,
+ *,
+ source_type: str | None = None,
+ lookback_days: int = DEFAULT_LOOKBACK_DAYS,
+ custom_source_mappings: dict | None = None,
+) -> AttributionHealthResponse:
+ """Aggregate UTM-tagged event counts per native integration over `lookback_days`.
+
+ `source_type` filters output to a single integration (same key as
+ data_source_health); aggregate totals still reflect full team activity.
+ `custom_source_mappings` lets callers pass a pre-loaded config to avoid a
+ Postgres roundtrip; when None, the service loads it itself.
+ """
+ rows = await _fetch_utm_groups(team, lookback_days=lookback_days)
+ if custom_source_mappings is None:
+ alias_map = await _build_team_alias_map(team)
+ else:
+ alias_map = build_combined_alias_map(custom_source_mappings)
+
+ targets = list(NATIVE_TO_KEY.values())
+ if source_type is not None:
+ native = EXTERNAL_SOURCE_TYPE_TO_NATIVE.get(source_type)
+ targets = [NATIVE_TO_KEY[native]] if native else []
+
+ allowed = set(targets)
+ per_integration: dict[NativeIntegration, _IntegrationAccumulator] = {
+ key: _IntegrationAccumulator(key=key) for key in targets
+ }
+ globally_unmatched: list[UnmatchedUtmSample] = []
+ all_samples: list[UtmSourceSample] = []
+ total_with_utm = 0
+ total_matched_any = 0
+ total_unmatched = 0
+
+ for row in rows:
+ raw_value: str = row.raw_utm_source
+ count: int = row.event_count
+ last_at: datetime | None = row.last_seen_at
+
+ total_with_utm += count
+
+ matched_key = lookup_in(raw_value, alias_map)
+ suggestion = _suggest_integration_by_alias_token(raw_value, alias_map, allowed)
+ all_samples.append(
+ UtmSourceSample(
+ raw_value=raw_value,
+ event_count=count,
+ matched_integration=matched_key,
+ suggested_integration=suggestion,
+ )
+ )
+
+ if matched_key is not None:
+ total_matched_any += count
+ acc = per_integration.get(matched_key)
+ if acc is not None:
+ acc.matched_count += count
+ candidates = [d for d in (acc.last_matched_at, last_at) if d is not None]
+ acc.last_matched_at = max(candidates) if candidates else None
+ continue
+
+ # Unmatched at the alias level.
+ sample = UnmatchedUtmSample(
+ raw_value=raw_value,
+ event_count=count,
+ suggested_integration=suggestion,
+ )
+ globally_unmatched.append(sample)
+ total_unmatched += count
+ if suggestion is not None:
+ acc = per_integration[suggestion]
+ acc.likely_yours_count += count
+ acc.likely_yours_samples.append(sample)
+
+ entries = [acc.to_entry(total_with_utm) for acc in per_integration.values()]
+ globally_unmatched.sort(key=lambda s: s.event_count, reverse=True)
+ all_samples.sort(key=lambda s: s.event_count, reverse=True)
+
+ return AttributionHealthResponse(
+ lookback_days=lookback_days,
+ integrations=entries,
+ total_events_with_utm=total_with_utm,
+ total_events_matched_to_any_integration=total_matched_any,
+ total_events_unmatched=total_unmatched,
+ sample_globally_unmatched=globally_unmatched[:MAX_GLOBAL_UNMATCHED],
+ all_utm_source_samples=all_samples[:MAX_GLOBAL_UNMATCHED],
+ total_distinct_utm_sources=len(all_samples),
+ utm_source_catalogue_truncated=len(rows) >= HOGQL_GROUP_LIMIT,
+ )
+
+
+@dataclass
+class _UtmRow:
+ raw_utm_source: str
+ event_count: int
+ last_seen_at: datetime | None
+
+
+@dataclass
+class _IntegrationAccumulator:
+ key: NativeIntegration
+ matched_count: int = 0
+ likely_yours_count: int = 0
+ last_matched_at: datetime | None = None
+ likely_yours_samples: list[UnmatchedUtmSample] = field(default_factory=list)
+
+ def to_entry(self, total_with_utm: int) -> AttributionHealthEntry:
+ display = display_name_for_key(self.key)
+
+ matched_pct = 0.0
+ if total_with_utm > 0:
+ matched_pct = round((self.matched_count / total_with_utm) * 100, 2)
+
+ self.likely_yours_samples.sort(key=lambda s: s.event_count, reverse=True)
+ return AttributionHealthEntry(
+ integration_key=self.key,
+ display_name=display,
+ events_with_utm_last_7d=total_with_utm,
+ events_matched_last_7d=self.matched_count,
+ events_unmatched_likely_yours_last_7d=self.likely_yours_count,
+ last_event_with_matching_utm_at=self.last_matched_at,
+ matched_pct=matched_pct,
+ sample_unmatched_utm_sources=self.likely_yours_samples[:MAX_SAMPLE_UNMATCHED],
+ )
+
+
+@database_sync_to_async
+def _build_team_alias_map(team: Team) -> dict[str, NativeIntegration]:
+ """Merge canonical aliases with the team's `custom_source_mappings` so user
+ overrides are honored when classifying utm_source values."""
+ config = getattr(team, "marketing_analytics_config", None)
+ custom = config.custom_source_mappings if config is not None else {}
+ return build_combined_alias_map(custom)
+
+
+@database_sync_to_async
+def _fetch_utm_groups(team: Team, *, lookback_days: int) -> list[_UtmRow]:
+ """HogQL aggregation of utm_source counts and latest timestamp within the window.
+
+ Intentionally not restricted to `$pageview` — conversion goals are often custom
+ events, so attribution should reflect all UTM-tagged activity.
+ """
+ since = timezone.now() - timedelta(days=lookback_days)
+ hogql = """
+ SELECT
+ lower(trim(properties.utm_source)) AS raw_utm_source,
+ count() AS event_count,
+ max(timestamp) AS last_seen_at
+ FROM events
+ WHERE
+ timestamp >= {since}
+ AND properties.utm_source IS NOT NULL
+ AND properties.utm_source != ''
+ GROUP BY raw_utm_source
+ ORDER BY event_count DESC
+ LIMIT {limit}
+ """
+ with tags_context(product=Product.MARKETING_ANALYTICS, feature=Feature.HEALTH_CHECK, team_id=team.pk):
+ result = execute_hogql_query(
+ hogql,
+ team,
+ placeholders={
+ "since": ast.Constant(value=since),
+ "limit": ast.Constant(value=HOGQL_GROUP_LIMIT),
+ },
+ )
+ rows: list[_UtmRow] = []
+ for row in result.results or []:
+ raw, count, last_at = row[0], row[1], row[2]
+ if not raw:
+ continue
+ rows.append(
+ _UtmRow(
+ raw_utm_source=cast(str, raw),
+ event_count=int(count or 0),
+ last_seen_at=last_at if isinstance(last_at, datetime) else None,
+ )
+ )
+ return rows
+
+
+def _suggest_integration_by_alias_token(
+ raw_utm_source: str, alias_map: dict[str, NativeIntegration], allowed: set[NativeIntegration]
+) -> NativeIntegration | None:
+ """Suggest an integration for a value that didn't match exactly, when one of
+ its tokens is a known alias (canonical or team-custom) — e.g. `facebook_paid`
+ → Meta via the `facebook` token.
+
+ `allowed` scopes the result to the integrations the caller is reporting on, so
+ a `source_type` filter can't yield an out-of-scope integration."""
+ for token in re.split(r"[^a-z0-9]+", raw_utm_source.lower()):
+ integration = alias_map.get(normalize(token))
+ if integration is not None and integration in allowed:
+ return integration
+ return None
diff --git a/products/marketing_analytics/backend/services/conversion_goals_inspector.py b/products/marketing_analytics/backend/services/conversion_goals_inspector.py
new file mode 100644
index 000000000000..bbdac6c8804d
--- /dev/null
+++ b/products/marketing_analytics/backend/services/conversion_goals_inspector.py
@@ -0,0 +1,690 @@
+"""Inspect configured conversion goals: shape, last-30d counts, integrated split,
+and per-goal event breakdowns. Read-only.
+
+Goal matching mirrors the dashboard (ActionsNode uses `action_to_expr`, so URL/property
+filters apply). The deliberate difference: counts use a fixed 30d window and ignore the
+team's `attribution_window_days`/attribution model — answering "how many of these events
+happened, and were they UTM-tagged?", not "how much credit did each channel get?". Flagged
+via `ConversionGoalSummary.is_approximate`.
+"""
+
+import re
+import asyncio
+from dataclasses import asdict, dataclass, field
+from datetime import UTC, datetime, timedelta
+from typing import Any, Literal, cast
+
+from django.utils import timezone
+
+import structlog
+
+from posthog.schema import DateRange
+
+from posthog.hogql import ast
+from posthog.hogql.property import action_to_expr
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.clickhouse.query_tagging import Feature, Product, tags_context
+from posthog.models.team.team import Team
+from posthog.sync import database_sync_to_async
+
+from products.actions.backend.models.action import Action
+from products.marketing_analytics.backend.services.native_integrations import (
+ NativeIntegration,
+ build_combined_alias_map,
+ lookup_in,
+)
+
+logger = structlog.get_logger(__name__)
+
+# Sanity-check that DataWarehouseNode `table_name` and `timestamp_field` look
+# like identifiers before passing them into the HogQL AST. The AST builder
+# itself never interpolates these as raw SQL (we use `ast.Field(chain=...)`
+# and `ast.Constant`), so this isn't security — it's a clear, early "your
+# config is malformed" rejection vs. a downstream HogQL parse error.
+_DW_TABLE_PATTERN = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*$")
+_DW_COLUMN_PATTERN = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
+
+GoalKind = Literal["EventsNode", "ActionsNode", "DataWarehouseNode"]
+DEFAULT_LOOKBACK_DAYS = 30
+# Hard cap on how far back `explain_conversion_goal` will scan, so an LLM- or
+# user-supplied date range can't trigger an unbounded multi-year events scan.
+MAX_LOOKBACK_DAYS = 365
+EXPLAIN_SAMPLE_LIMIT = 10
+EXPLAIN_BREAKDOWN_LIMIT = 20
+# Max events scanned by `explain_conversion_goal`. When a goal exceeds this in
+# the period, total_count and the breakdowns are a most-recent sample, not the
+# full count — the response carries a note saying so.
+EXPLAIN_EVENT_SCAN_LIMIT = 5000
+
+
+@dataclass
+class ConversionGoalSummary:
+ id: str
+ name: str
+ kind: GoalKind
+ target_label: str
+ last_30d_count: int
+ integrated_count: int | None
+ # Non-integrated events split by ROOT CAUSE — these have OPPOSITE fixes:
+ # - `events_without_utm_source`: event has NO utm_source at all. Fix is to
+ # tag UTMs on the conversion page (or use server-side persistence). NOT
+ # solvable by adding custom_source_mappings.
+ # - `events_with_unmatched_utm_source`: event has utm_source set but it
+ # doesn't match any known integration alias. Fix is custom_source_mappings
+ # (or fix UTM tagging upstream). Solvable from settings.
+ events_without_utm_source: int | None
+ events_with_unmatched_utm_source: int | None
+ non_integrated_count: int | None
+ integrated_pct: float | None
+ is_misconfigured: bool
+ misconfig_reason: str | None
+ # True when this 30d count may differ from the dashboard's attribution-windowed
+ # number (attribution_window_days != 30). Goal matching itself is exact.
+ is_approximate: bool = False
+ approximation_reason: str | None = None
+
+
+@dataclass
+class ConversionGoalsListResponse:
+ goals: list[ConversionGoalSummary] = field(default_factory=list)
+ attribution_window_days: int = 0
+ attribution_mode: str = "last_touch"
+ has_misconfigured: bool = False
+
+ def to_dict(self) -> dict[str, Any]:
+ return asdict(self)
+
+
+@dataclass
+class GoalEventSample:
+ event_uuid: str
+ timestamp: datetime
+ distinct_id: str
+ utm_source: str | None
+ utm_campaign: str | None
+ matched_integration: str | None
+
+
+@dataclass
+class GoalExplanation:
+ goal_id: str
+ goal_name: str
+ kind: GoalKind
+ period: DateRange
+ total_count: int
+ integrated_count: int | None
+ # See `ConversionGoalSummary` for why we split non-integrated by root cause
+ # — these two have OPPOSITE fixes.
+ events_without_utm_source: int | None
+ events_with_unmatched_utm_source: int | None
+ non_integrated_count: int | None
+ by_event: list[tuple[str, int]]
+ by_utm_source: list[tuple[str, int]]
+ by_matched_integration: list[tuple[str, int]]
+ samples: list[GoalEventSample]
+ notes: list[str] = field(default_factory=list)
+
+ def to_dict(self) -> dict[str, Any]:
+ return asdict(self)
+
+
+async def list_conversion_goals(team: Team) -> ConversionGoalsListResponse:
+ """Return one summary entry per configured conversion goal."""
+ goals_raw, attribution_window, attribution_mode = await _read_team_goal_config(team)
+ alias_map = await _build_team_alias_map(team)
+
+ results = await asyncio.gather(
+ *(_summarize_goal(team, goal, alias_map, attribution_window) for goal in goals_raw),
+ return_exceptions=True,
+ )
+ # Degrade a failing goal to a misconfigured entry instead of failing the whole list.
+ summaries: list[ConversionGoalSummary] = []
+ for goal, result in zip(goals_raw, results):
+ if isinstance(result, BaseException):
+ logger.error("conversion_goal_summary_failed", goal=goal.get("conversion_goal_id"), error=str(result))
+ summaries.append(_failed_goal_summary(goal, result))
+ else:
+ summaries.append(result)
+
+ return ConversionGoalsListResponse(
+ goals=summaries,
+ attribution_window_days=attribution_window,
+ attribution_mode=attribution_mode,
+ has_misconfigured=any(s.is_misconfigured for s in summaries),
+ )
+
+
+def _failed_goal_summary(goal: dict[str, Any], exc: BaseException) -> ConversionGoalSummary:
+ goal_id = str(goal.get("conversion_goal_id") or goal.get("id") or "")
+ return ConversionGoalSummary(
+ id=goal_id,
+ name=goal.get("conversion_goal_name") or goal.get("name") or goal_id,
+ kind=cast(GoalKind, goal.get("kind", "EventsNode")),
+ target_label="(unavailable)",
+ last_30d_count=0,
+ integrated_count=None,
+ events_without_utm_source=None,
+ events_with_unmatched_utm_source=None,
+ non_integrated_count=None,
+ integrated_pct=None,
+ is_misconfigured=True,
+ misconfig_reason=f"Failed to summarize goal: {exc}",
+ )
+
+
+async def explain_conversion_goal(
+ team: Team,
+ goal_id: str,
+ period: DateRange | None = None,
+) -> GoalExplanation:
+ """Resolve a goal by id and break down its events by name, utm_source,
+ and matched integration."""
+ goals_raw, _, _ = await _read_team_goal_config(team)
+ goal = next((g for g in goals_raw if str(g.get("conversion_goal_id") or g.get("id") or "") == goal_id), None)
+ if goal is None:
+ raise ValueError(f"Conversion goal '{goal_id}' not found in team config")
+ alias_map = await _build_team_alias_map(team)
+
+ kind = cast(GoalKind, goal.get("kind", "EventsNode"))
+ name = goal.get("conversion_goal_name") or goal.get("name") or goal_id
+ resolved_period = period or _default_period()
+
+ if kind == "DataWarehouseNode":
+ return GoalExplanation(
+ goal_id=goal_id,
+ goal_name=name,
+ kind=kind,
+ period=resolved_period,
+ total_count=0,
+ integrated_count=None,
+ events_without_utm_source=None,
+ events_with_unmatched_utm_source=None,
+ non_integrated_count=None,
+ by_event=[],
+ by_utm_source=[],
+ by_matched_integration=[],
+ samples=[],
+ notes=[
+ "DataWarehouseNode goals are computed against an external table; per-event "
+ "breakdown is not available in this service. Use the marketing analytics "
+ "dashboard or query the underlying table directly."
+ ],
+ )
+
+ rows = await _query_goal_events(team, goal, resolved_period)
+ notes: list[str] = [
+ "This is a flat breakdown of each conversion event by its own utm_source/utm_campaign. "
+ "It is NOT the dashboard's attribution calculation: first-touch, last-touch and multi-touch "
+ "(linear/time-decay/position-based) models distribute credit across touchpoints differently."
+ ]
+ if len(rows) >= EXPLAIN_EVENT_SCAN_LIMIT:
+ notes.append(
+ f"Only the {EXPLAIN_EVENT_SCAN_LIMIT} most recent events in the period were scanned. "
+ "total_count and the breakdowns below are a recent-events sample, not the full count."
+ )
+
+ by_event: dict[str, int] = {}
+ by_utm: dict[str, int] = {}
+ by_integration: dict[str, int] = {}
+ samples: list[GoalEventSample] = []
+ integrated_count = 0
+ without_utm_count = 0
+ unmatched_with_utm_count = 0
+ total_count = 0
+
+ for row in rows:
+ event_uuid, ts, distinct_id, event_name, utm_source, utm_campaign = row
+ total_count += 1
+ by_event[event_name] = by_event.get(event_name, 0) + 1
+
+ utm_source_str = (utm_source or "").strip().lower()
+ if utm_source_str:
+ by_utm[utm_source_str] = by_utm.get(utm_source_str, 0) + 1
+
+ matched = lookup_in(utm_source_str, alias_map) if utm_source_str else None
+ if matched is not None:
+ by_integration[matched] = by_integration.get(matched, 0) + 1
+ integrated_count += 1
+ elif utm_source_str:
+ unmatched_with_utm_count += 1
+ else:
+ without_utm_count += 1
+
+ if len(samples) < EXPLAIN_SAMPLE_LIMIT:
+ samples.append(
+ GoalEventSample(
+ event_uuid=str(event_uuid),
+ timestamp=ts,
+ distinct_id=str(distinct_id or ""),
+ utm_source=utm_source_str or None,
+ utm_campaign=(utm_campaign or "").strip() or None,
+ matched_integration=matched,
+ )
+ )
+
+ return GoalExplanation(
+ goal_id=goal_id,
+ goal_name=name,
+ kind=kind,
+ period=resolved_period,
+ total_count=total_count,
+ integrated_count=integrated_count,
+ events_without_utm_source=without_utm_count,
+ events_with_unmatched_utm_source=unmatched_with_utm_count,
+ non_integrated_count=without_utm_count + unmatched_with_utm_count,
+ by_event=sorted(by_event.items(), key=lambda kv: kv[1], reverse=True)[:EXPLAIN_BREAKDOWN_LIMIT],
+ by_utm_source=sorted(by_utm.items(), key=lambda kv: kv[1], reverse=True)[:EXPLAIN_BREAKDOWN_LIMIT],
+ by_matched_integration=sorted(by_integration.items(), key=lambda kv: kv[1], reverse=True),
+ samples=samples,
+ notes=notes,
+ )
+
+
+@database_sync_to_async
+def _read_team_goal_config(team: Team) -> tuple[list[dict], int, str]:
+ """Return (raw_goals_list, attribution_window_days, attribution_mode)."""
+ config = getattr(team, "marketing_analytics_config", None)
+ if config is None:
+ return [], 90, "last_touch"
+ goals = config.conversion_goals or []
+ return list(goals), int(config.attribution_window_days or 90), str(config.attribution_mode or "last_touch")
+
+
+@database_sync_to_async
+def _build_team_alias_map(team: Team) -> dict[str, NativeIntegration]:
+ """Combine canonical alias table with the team's `custom_source_mappings` so
+ user-defined source overrides (e.g. `meta2 -> MetaAds`) count as integrated."""
+ config = getattr(team, "marketing_analytics_config", None)
+ custom = config.custom_source_mappings if config is not None else {}
+ return build_combined_alias_map(custom)
+
+
+async def _summarize_goal(
+ team: Team,
+ goal: dict,
+ alias_map: dict[str, NativeIntegration],
+ attribution_window_days: int,
+) -> ConversionGoalSummary:
+ goal_id = str(goal.get("conversion_goal_id") or goal.get("id") or "")
+ name = goal.get("conversion_goal_name") or goal.get("name") or goal_id
+ # `kind_raw: str` keeps the "unknown kind" fallback reachable — a GoalKind
+ # would let mypy treat the branches below as exhaustive.
+ kind_raw: str = goal.get("kind") or "EventsNode"
+ kind = cast(GoalKind, kind_raw)
+
+ # 30d, non-attribution-windowed count. Flag approximate when the team's window
+ # differs so the LLM doesn't claim the dashboard would agree.
+ base_approximate = attribution_window_days != DEFAULT_LOOKBACK_DAYS
+ base_reason = (
+ f"fast {DEFAULT_LOOKBACK_DAYS}d count without attribution windowing; "
+ f"team is configured for a {attribution_window_days}d attribution window — "
+ "the dashboard's number may differ"
+ if base_approximate
+ else None
+ )
+
+ if kind_raw == "EventsNode":
+ target_label = goal.get("event") or "(all events)"
+ total, integrated, without_utm, unmatched_with_utm = await _count_event_goal(team, goal, alias_map)
+ return _summary_with_split(
+ goal_id,
+ name,
+ kind,
+ target_label,
+ total,
+ integrated,
+ without_utm,
+ unmatched_with_utm,
+ is_approximate=base_approximate,
+ approximation_reason=base_reason,
+ )
+
+ if kind_raw == "ActionsNode":
+ action, action_error = await _resolve_action(team, goal_id)
+ if action is None:
+ return ConversionGoalSummary(
+ id=goal_id,
+ name=name,
+ kind=kind,
+ target_label=f"Action #{goal_id}",
+ last_30d_count=0,
+ integrated_count=None,
+ events_without_utm_source=None,
+ events_with_unmatched_utm_source=None,
+ non_integrated_count=None,
+ integrated_pct=None,
+ is_misconfigured=True,
+ misconfig_reason=action_error or f"Action {goal_id} no longer exists",
+ )
+ target_label = f"Action: {action.name}"
+ total, integrated, without_utm, unmatched_with_utm = await _count_action_goal(team, action, alias_map)
+ return _summary_with_split(
+ goal_id,
+ name,
+ kind,
+ target_label,
+ total,
+ integrated,
+ without_utm,
+ unmatched_with_utm,
+ is_approximate=base_approximate,
+ approximation_reason=base_reason,
+ )
+
+ if kind_raw == "DataWarehouseNode":
+ table_name = goal.get("table_name") or "(unknown table)"
+ target_label = f"{table_name}"
+ last_30d_count, dw_misconfig = await _count_dw_goal(team, goal)
+ return ConversionGoalSummary(
+ id=goal_id,
+ name=name,
+ kind=kind,
+ target_label=target_label,
+ last_30d_count=last_30d_count,
+ integrated_count=None,
+ events_without_utm_source=None,
+ events_with_unmatched_utm_source=None,
+ non_integrated_count=None,
+ integrated_pct=None,
+ is_misconfigured=dw_misconfig is not None,
+ misconfig_reason=dw_misconfig,
+ is_approximate=base_approximate,
+ approximation_reason=base_reason,
+ )
+
+ return ConversionGoalSummary(
+ id=goal_id,
+ name=name,
+ kind=kind,
+ target_label="(unknown kind)",
+ last_30d_count=0,
+ integrated_count=None,
+ events_without_utm_source=None,
+ events_with_unmatched_utm_source=None,
+ non_integrated_count=None,
+ integrated_pct=None,
+ is_misconfigured=True,
+ misconfig_reason=f"Unknown goal kind: {kind_raw}",
+ )
+
+
+def _summary_with_split(
+ goal_id: str,
+ name: str,
+ kind: GoalKind,
+ target_label: str,
+ total: int,
+ integrated: int,
+ without_utm: int,
+ unmatched_with_utm: int,
+ *,
+ is_approximate: bool = False,
+ approximation_reason: str | None = None,
+) -> ConversionGoalSummary:
+ integrated_pct = round((integrated / total) * 100, 2) if total > 0 else 0.0
+ return ConversionGoalSummary(
+ id=goal_id,
+ name=name,
+ kind=kind,
+ target_label=target_label,
+ last_30d_count=total,
+ integrated_count=integrated,
+ events_without_utm_source=without_utm,
+ events_with_unmatched_utm_source=unmatched_with_utm,
+ non_integrated_count=without_utm + unmatched_with_utm,
+ integrated_pct=integrated_pct,
+ is_misconfigured=False,
+ misconfig_reason=None,
+ is_approximate=is_approximate,
+ approximation_reason=approximation_reason,
+ )
+
+
+@database_sync_to_async
+def _resolve_action(team: Team, goal_id: str) -> tuple[Action | None, str | None]:
+ try:
+ action_id_int = int(goal_id)
+ except (TypeError, ValueError):
+ return None, f"Goal id '{goal_id}' is not a valid integer for ActionsNode"
+ try:
+ return Action.objects.get(id=action_id_int, team_id=team.pk, deleted=False), None
+ except Action.DoesNotExist:
+ return None, f"Action {goal_id} does not exist or is deleted"
+
+
+@database_sync_to_async
+def _count_event_goal(
+ team: Team, goal: dict[str, Any], alias_map: dict[str, NativeIntegration]
+) -> tuple[int, int, int, int]:
+ """For EventsNode: count last 30d events matching the goal, split by utm_source match.
+
+ `goal["event"]` may be None, meaning "match any event" (rare but valid)."""
+ since = timezone.now() - timedelta(days=DEFAULT_LOOKBACK_DAYS)
+ event_name = goal.get("event")
+ where: ast.Expr = (
+ ast.CompareOperation(
+ left=ast.Field(chain=["event"]),
+ op=ast.CompareOperationOp.Eq,
+ right=ast.Constant(value=event_name),
+ )
+ if event_name
+ else ast.Constant(value=True) # `goal["event"]` is None — "match any event"
+ )
+ return _execute_count_with_split(team, where, {"since": ast.Constant(value=since)}, alias_map)
+
+
+@database_sync_to_async
+def _count_action_goal(
+ team: Team, action: Action, alias_map: dict[str, NativeIntegration]
+) -> tuple[int, int, int, int]:
+ """For ActionsNode: count last 30d events matching the action's full definition
+ (`action_to_expr`, same as the dashboard), split by utm_source.
+
+ Returns (total, integrated, without_utm, unmatched_with_utm)."""
+ # No steps → `action_to_expr` returns `true`; short-circuit so we don't count
+ # the entire events table.
+ if not action.steps:
+ return 0, 0, 0, 0
+ since = timezone.now() - timedelta(days=DEFAULT_LOOKBACK_DAYS)
+ return _execute_count_with_split(team, action_to_expr(action), {"since": ast.Constant(value=since)}, alias_map)
+
+
+def _execute_count_with_split(
+ team: Team, where: ast.Expr, placeholders: dict[str, ast.Expr], alias_map: dict[str, NativeIntegration]
+) -> tuple[int, int, int, int]:
+ """Returns (total, integrated, without_utm, unmatched_with_utm).
+
+ The split is computed in ClickHouse via `countIf`, not `GROUP BY utm_source`
+ plus a Python sum — a `GROUP BY` inherits the default query row limit and
+ would silently undercount goals with a long utm_source tail (>100 distinct
+ values). The two non-integrated buckets have OPPOSITE fixes (UTM tagging vs.
+ custom_source_mappings), so they're surfaced separately.
+
+ `where` is the goal-matching predicate (event comparison or `action_to_expr`).
+ `norm_utm` mirrors `native_integrations.normalize()` (lowercase + alphanumerics)
+ so a raw value matches the alias keys.
+ """
+ hogql = """
+ SELECT
+ count() AS total,
+ countIf(norm_utm IN {aliases}) AS integrated,
+ countIf(raw_utm = '') AS without_utm,
+ countIf(raw_utm != '' AND norm_utm NOT IN {aliases}) AS unmatched_with_utm
+ FROM (
+ SELECT
+ lower(trim(coalesce(properties.utm_source, ''))) AS raw_utm,
+ replaceRegexpAll(lower(trim(coalesce(properties.utm_source, ''))), '[^a-z0-9]', '') AS norm_utm
+ FROM events
+ WHERE {where} AND timestamp >= {since}
+ )
+ """
+ query_placeholders: dict[str, ast.Expr] = {
+ **placeholders,
+ "where": where,
+ "aliases": ast.Tuple(exprs=[ast.Constant(value=key) for key in alias_map]),
+ }
+ with tags_context(product=Product.MARKETING_ANALYTICS, feature=Feature.HEALTH_CHECK, team_id=team.pk):
+ result = execute_hogql_query(hogql, team, placeholders=query_placeholders)
+ rows = result.results or []
+ if not rows:
+ return 0, 0, 0, 0
+ total, integrated, without_utm, unmatched_with_utm = rows[0]
+ return int(total or 0), int(integrated or 0), int(without_utm or 0), int(unmatched_with_utm or 0)
+
+
+@database_sync_to_async
+def _count_dw_goal(team: Team, goal: dict[str, Any]) -> tuple[int, str | None]:
+ """For DataWarehouseNode: a row count against the configured table.
+
+ Returns (count, misconfig_reason). `table_name`/`timestamp_field` come from
+ team-editable JSON, so they're validated against a strict identifier regex
+ before going into the AST (constants are bound via placeholders).
+ """
+ table_name = goal.get("table_name")
+ timestamp_field = goal.get("timestamp_field")
+ if not table_name or not timestamp_field:
+ return 0, "DataWarehouseNode goal is missing table_name or timestamp_field"
+
+ if not _DW_TABLE_PATTERN.fullmatch(str(table_name)):
+ return 0, f"DataWarehouseNode goal has invalid table_name: {table_name!r}"
+ if not _DW_COLUMN_PATTERN.fullmatch(str(timestamp_field)):
+ return 0, f"DataWarehouseNode goal has invalid timestamp_field: {timestamp_field!r}"
+
+ since = timezone.now() - timedelta(days=DEFAULT_LOOKBACK_DAYS)
+ table_chain: list[str | int] = list(str(table_name).split("."))
+ timestamp_chain: list[str | int] = [str(timestamp_field)]
+ query = ast.SelectQuery(
+ select=[ast.Call(name="count", args=[])],
+ select_from=ast.JoinExpr(table=ast.Field(chain=table_chain)),
+ where=ast.CompareOperation(
+ left=ast.Field(chain=timestamp_chain),
+ op=ast.CompareOperationOp.GtEq,
+ right=ast.Constant(value=since),
+ ),
+ )
+ try:
+ with tags_context(product=Product.MARKETING_ANALYTICS, feature=Feature.HEALTH_CHECK, team_id=team.pk):
+ result = execute_hogql_query(query, team)
+ except Exception as exc:
+ logger.warning(
+ "marketing_analytics.dw_goal_query_failed",
+ team_id=team.pk,
+ table_name=table_name,
+ error=str(exc),
+ )
+ return 0, f"DW table or column not queryable: {exc}"
+
+ if result.results and len(result.results) > 0:
+ return int(result.results[0][0] or 0), None
+ return 0, None
+
+
+async def _query_goal_events(team: Team, goal: dict[str, Any], period: DateRange) -> list[tuple[Any, ...]]:
+ """Raw event rows for a goal in `period` (EventsNode/ActionsNode only; DW is
+ short-circuited by the caller)."""
+ kind = goal.get("kind")
+ since, until = _resolve_period(period)
+ placeholders: dict[str, ast.Expr]
+
+ if kind == "EventsNode":
+ event_name = goal.get("event")
+ if event_name:
+ hogql = """
+ SELECT uuid, timestamp, distinct_id, event,
+ properties.utm_source, properties.utm_campaign
+ FROM events
+ WHERE event = {event_name} AND timestamp >= {since} AND timestamp <= {until}
+ ORDER BY timestamp DESC
+ LIMIT {scan_limit}
+ """
+ placeholders = {
+ "event_name": ast.Constant(value=event_name),
+ "since": ast.Constant(value=since),
+ "until": ast.Constant(value=until),
+ "scan_limit": ast.Constant(value=EXPLAIN_EVENT_SCAN_LIMIT),
+ }
+ else:
+ hogql = """
+ SELECT uuid, timestamp, distinct_id, event,
+ properties.utm_source, properties.utm_campaign
+ FROM events
+ WHERE timestamp >= {since} AND timestamp <= {until}
+ ORDER BY timestamp DESC
+ LIMIT {scan_limit}
+ """
+ placeholders = {
+ "since": ast.Constant(value=since),
+ "until": ast.Constant(value=until),
+ "scan_limit": ast.Constant(value=EXPLAIN_EVENT_SCAN_LIMIT),
+ }
+ return await _run_hogql(team, hogql, placeholders)
+
+ if kind == "ActionsNode":
+ goal_id = str(goal.get("conversion_goal_id") or goal.get("id") or "")
+ action, _ = await _resolve_action(team, goal_id)
+ if action is None:
+ return []
+ match_expr = await _action_match_expr(action)
+ if match_expr is None:
+ return []
+ hogql = """
+ SELECT uuid, timestamp, distinct_id, event,
+ properties.utm_source, properties.utm_campaign
+ FROM events
+ WHERE {match} AND timestamp >= {since} AND timestamp <= {until}
+ ORDER BY timestamp DESC
+ LIMIT {scan_limit}
+ """
+ placeholders = {
+ "match": match_expr,
+ "since": ast.Constant(value=since),
+ "until": ast.Constant(value=until),
+ "scan_limit": ast.Constant(value=EXPLAIN_EVENT_SCAN_LIMIT),
+ }
+ return await _run_hogql(team, hogql, placeholders)
+
+ return []
+
+
+@database_sync_to_async
+def _action_match_expr(action: Action) -> ast.Expr | None:
+ """The action's full match predicate (`action_to_expr`) for use against the
+ events table. None when the action has no steps (would otherwise match all)."""
+ if not action.steps:
+ return None
+ return action_to_expr(action)
+
+
+@database_sync_to_async
+def _run_hogql(team: Team, hogql: str, placeholders: dict[str, ast.Expr]) -> list[tuple[Any, ...]]:
+ with tags_context(product=Product.MARKETING_ANALYTICS, feature=Feature.HEALTH_CHECK, team_id=team.pk):
+ result = execute_hogql_query(hogql, team, placeholders=placeholders)
+ return list(result.results or [])
+
+
+def _resolve_period(period: DateRange) -> tuple[datetime, datetime]:
+ now = timezone.now()
+ until = _parse_date_or(period.date_to, default=now)
+ since = _parse_date_or(period.date_from, default=now - timedelta(days=DEFAULT_LOOKBACK_DAYS))
+ earliest = now - timedelta(days=MAX_LOOKBACK_DAYS)
+ since = max(since, earliest)
+ if until < since: # inverted or fully-clamped range → empty window
+ until = since
+ return since, until
+
+
+def _parse_date_or(raw: str | None, *, default: datetime) -> datetime:
+ if not raw:
+ return default
+ try:
+ parsed = datetime.fromisoformat(raw.replace("Z", "+00:00"))
+ except (TypeError, ValueError):
+ return default
+ # Keep everything timezone-aware so comparisons against `now` don't raise.
+ return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=UTC)
+
+
+def _default_period() -> DateRange:
+ now = timezone.now()
+ return DateRange(date_from=(now - timedelta(days=DEFAULT_LOOKBACK_DAYS)).isoformat(), date_to=now.isoformat())
diff --git a/products/marketing_analytics/backend/services/data_source_health.py b/products/marketing_analytics/backend/services/data_source_health.py
new file mode 100644
index 000000000000..9e7af35aa9ca
--- /dev/null
+++ b/products/marketing_analytics/backend/services/data_source_health.py
@@ -0,0 +1,458 @@
+from dataclasses import asdict, dataclass, field
+from datetime import datetime, timedelta
+from typing import Literal
+
+from django.db.models import Sum
+from django.utils import timezone
+
+import structlog
+
+from posthog.schema import NativeMarketingSource
+
+from posthog.models.team.team import Team
+from posthog.sync import database_sync_to_async
+
+from products.marketing_analytics.backend.hogql_queries.constants import (
+ MARKETING_ANALYTICS_SCHEMA,
+ NEEDED_FIELDS_FOR_NATIVE_MARKETING_ANALYTICS,
+)
+from products.marketing_analytics.backend.services.native_integrations import (
+ DISPLAY_NAMES,
+ EXTERNAL_SOURCE_TYPE_TO_NATIVE,
+)
+from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+
+logger = structlog.get_logger(__name__)
+
+SyncStatus = Literal[
+ "ok",
+ "stale",
+ "error",
+ "never",
+ "not_connected",
+ "tables_failed", # at least one required table has status=Failed
+ "tables_disabled", # at least one required table has should_sync=False
+ "tables_missing", # at least one required table is not present at all
+]
+OverallStatus = Literal["healthy", "degraded", "broken", "no_sources"]
+
+# A connection is "stale" if its last completed sync is older than this.
+STALE_THRESHOLD = timedelta(hours=24)
+
+_REQUIRED_SCHEMA_COLUMNS: list[str] = [
+ col.value for col, cfg in MARKETING_ANALYTICS_SCHEMA.items() if cfg.get("required")
+]
+
+# Hash anchor (#marketing-settings), not a path slash — the slash form 404s.
+_MARKETING_SETTINGS_URL = "/settings/environment-marketing-analytics#marketing-settings"
+_MARKETING_PAGE_URL = "/marketing"
+
+
+def _source_schemas_url(source_id: str | None) -> str | None:
+ """URL to the per-source Schemas tab (enable/disable tables, retry syncs, reconnect).
+ Frontend prefixes the source UUID with `managed-` to disambiguate managed sources."""
+ if not source_id:
+ return None
+ return f"/data-management/sources/managed-{source_id}/schemas"
+
+
+@dataclass
+class RequiredTableStatus:
+ table_name: str
+ present: bool
+ should_sync: bool
+ status: str | None # ExternalDataSchema.Status value (Completed/Running/Failed/Paused/Cancelled) or None
+ last_synced_at: datetime | None
+
+
+@dataclass
+class DataSourceHealthEntry:
+ source_type: str
+ is_native: bool
+ display_name: str
+ connected: bool
+ last_sync_at: datetime | None
+ last_sync_status: SyncStatus
+ last_error: str | None
+ rows_last_24h: int
+ rows_last_7d: int
+ sources_map_present: bool
+ schema_columns_mapped: list[str]
+ schema_columns_required_missing: list[str]
+ required_tables: list[RequiredTableStatus]
+ # Marketing analytics global settings (mappings, goals, attribution).
+ settings_url: str
+ # Per-source Schemas tab — used for table-level fixes (enable/disable required
+ # tables, retry failed syncs, reconnect auth). `None` if the source isn't
+ # connected (no UUID to link to).
+ schemas_url: str | None
+ diagnosis: str
+ fix_suggestion: str | None
+
+
+@dataclass
+class DataSourceHealthResponse:
+ integrations: list[DataSourceHealthEntry] = field(default_factory=list)
+ has_any_data: bool = False
+ overall_status: OverallStatus = "no_sources"
+ issues_summary: list[str] = field(default_factory=list)
+
+ def to_dict(self) -> dict:
+ return asdict(self)
+
+
+async def get_data_source_health(
+ team: Team,
+ *,
+ source_type: str | None = None,
+ sources_map: dict[str, dict] | None = None,
+) -> DataSourceHealthResponse:
+ """Check the platform → DW side of marketing integrations: connection state,
+ sync recency, row counts, and schema-mapping coverage for every native source.
+
+ This service does NOT look at PostHog events / UTM attribution — that is
+ `attribution_health`. Cross-domain correlation (e.g. "syncing fine but no UTM
+ events arrive") lives in the `marketing_diagnostic` aggregator.
+
+ Native (Google Ads, Meta Ads, Bing Ads, LinkedIn Ads, Reddit Ads, Pinterest Ads,
+ Snapchat Ads, TikTok Ads) is the v1 scope. BigQuery / self-managed sources will
+ be added in a follow-up.
+
+ `sources_map` lets the diagnostic aggregator pass an already-loaded
+ `marketing_analytics_config.sources_map` instead of triggering another
+ Postgres roundtrip. None → service loads it itself.
+ """
+ targets = EXTERNAL_SOURCE_TYPE_TO_NATIVE
+ if source_type is not None:
+ targets = {k: v for k, v in targets.items() if k == source_type}
+
+ config_sources_map = sources_map if sources_map is not None else await _get_sources_map(team)
+ sources_by_type = await _get_sources_by_type(team, list(targets.keys()))
+
+ entries: list[DataSourceHealthEntry] = []
+ for type_key, native in targets.items():
+ source = sources_by_type.get(type_key)
+ entries.append(
+ await _build_entry(
+ source_type=type_key,
+ native=native,
+ source=source,
+ config_sources_map=config_sources_map,
+ )
+ )
+
+ has_any_data = any(e.rows_last_7d > 0 for e in entries)
+ overall_status = _compute_overall_status(entries)
+ issues_summary = _build_issues_summary(entries)
+
+ return DataSourceHealthResponse(
+ integrations=entries,
+ has_any_data=has_any_data,
+ overall_status=overall_status,
+ issues_summary=issues_summary,
+ )
+
+
+@database_sync_to_async
+def _get_sources_map(team: Team) -> dict[str, dict]:
+ config = getattr(team, "marketing_analytics_config", None)
+ return config.sources_map if config is not None else {}
+
+
+@database_sync_to_async
+def _get_sources_by_type(team: Team, source_types: list[str]) -> dict[str, ExternalDataSource]:
+ """Index live sources by source_type. We pick the most recently created if
+ the team has more than one of the same type — this is uncommon in practice."""
+ qs = ExternalDataSource.objects.filter(team=team, source_type__in=source_types, deleted=False).order_by(
+ "source_type", "-created_at"
+ )
+ by_type: dict[str, ExternalDataSource] = {}
+ for src in qs:
+ by_type.setdefault(src.source_type, src)
+ return by_type
+
+
+async def _build_entry(
+ *,
+ source_type: str,
+ native: NativeMarketingSource,
+ source: ExternalDataSource | None,
+ config_sources_map: dict[str, dict],
+) -> DataSourceHealthEntry:
+ display_name = DISPLAY_NAMES[native]
+
+ if source is None:
+ return DataSourceHealthEntry(
+ source_type=source_type,
+ is_native=True,
+ display_name=display_name,
+ connected=False,
+ last_sync_at=None,
+ last_sync_status="not_connected",
+ last_error=None,
+ rows_last_24h=0,
+ rows_last_7d=0,
+ sources_map_present=False,
+ schema_columns_mapped=[],
+ # Native sources don't require column mapping — that's only for
+ # self-managed (BigQuery, S3, etc.) sources where the user provides
+ # custom tables. The mapped/missing columns concept doesn't apply
+ # to native integrations at all.
+ schema_columns_required_missing=[],
+ required_tables=[
+ RequiredTableStatus(table_name=name, present=False, should_sync=False, status=None, last_synced_at=None)
+ for name in NEEDED_FIELDS_FOR_NATIVE_MARKETING_ANALYTICS.get(native, [])
+ ],
+ settings_url=_MARKETING_SETTINGS_URL,
+ schemas_url=None,
+ diagnosis=f"{display_name} is not connected.",
+ fix_suggestion=f"Connect {display_name} from {_MARKETING_SETTINGS_URL}.",
+ )
+
+ last_completed_at, last_error_text = await _get_last_job_state(source)
+ rows_24h, rows_7d = await _get_rows_synced(source)
+ required_tables = await _get_required_tables_status(source, native)
+
+ source_id_str = str(source.id)
+ field_mapping = config_sources_map.get(source_id_str, {})
+ mapped_keys = list(field_mapping.keys())
+ # Native sources don't use sources_map for column mapping. Only non-native
+ # (BigQuery, S3, self-managed) sources track per-column mappings here.
+ missing_required: list[str] = []
+
+ last_sync_status = _resolve_sync_status(
+ last_completed_at=last_completed_at,
+ last_error_text=last_error_text,
+ required_tables=required_tables,
+ )
+
+ diagnosis, fix_suggestion = _diagnose(
+ display_name=display_name,
+ last_sync_status=last_sync_status,
+ last_completed_at=last_completed_at,
+ last_error_text=last_error_text,
+ sources_map_present=bool(field_mapping),
+ missing_required=missing_required,
+ rows_last_7d=rows_7d,
+ required_tables=required_tables,
+ source_id=source_id_str,
+ )
+
+ return DataSourceHealthEntry(
+ source_type=source_type,
+ is_native=True,
+ display_name=display_name,
+ connected=True,
+ last_sync_at=last_completed_at,
+ last_sync_status=last_sync_status,
+ last_error=last_error_text,
+ rows_last_24h=rows_24h,
+ rows_last_7d=rows_7d,
+ sources_map_present=bool(field_mapping),
+ schema_columns_mapped=mapped_keys,
+ schema_columns_required_missing=missing_required,
+ required_tables=required_tables,
+ settings_url=_MARKETING_SETTINGS_URL,
+ schemas_url=_source_schemas_url(source_id_str),
+ diagnosis=diagnosis,
+ fix_suggestion=fix_suggestion,
+ )
+
+
+@database_sync_to_async
+def _get_required_tables_status(source: ExternalDataSource, native: NativeMarketingSource) -> list[RequiredTableStatus]:
+ required_names = NEEDED_FIELDS_FOR_NATIVE_MARKETING_ANALYTICS.get(native, [])
+ if not required_names:
+ return []
+
+ schemas_by_name: dict[str, ExternalDataSchema] = {
+ s.name: s for s in ExternalDataSchema.objects.filter(source=source, deleted=False)
+ }
+ out: list[RequiredTableStatus] = []
+ for name in required_names:
+ schema = schemas_by_name.get(name)
+ if schema is None:
+ out.append(
+ RequiredTableStatus(table_name=name, present=False, should_sync=False, status=None, last_synced_at=None)
+ )
+ else:
+ out.append(
+ RequiredTableStatus(
+ table_name=name,
+ present=True,
+ should_sync=schema.should_sync,
+ status=schema.status,
+ last_synced_at=getattr(schema, "last_synced_at", None),
+ )
+ )
+ return out
+
+
+@database_sync_to_async
+def _get_last_job_state(source: ExternalDataSource) -> tuple[datetime | None, str | None]:
+ """Return (last_completed_finished_at, last_unresolved_error_text) for a source.
+
+ `last_unresolved_error_text` is the latest FAILED job's error message *only
+ if* its created_at is newer than the most recent COMPLETED job — otherwise
+ the failure has been resolved by a subsequent successful sync.
+ """
+ last_completed = (
+ ExternalDataJob.objects.filter(pipeline=source, status=ExternalDataJob.Status.COMPLETED)
+ .order_by("-finished_at")
+ .values_list("finished_at", flat=True)
+ .first()
+ )
+ last_failed = (
+ ExternalDataJob.objects.filter(pipeline=source, status=ExternalDataJob.Status.FAILED)
+ .exclude(latest_error__isnull=True)
+ .order_by("-created_at")
+ .values("created_at", "latest_error")
+ .first()
+ )
+
+ error_text: str | None = None
+ if last_failed is not None:
+ if last_completed is None or last_failed["created_at"] > last_completed:
+ error_text = last_failed["latest_error"]
+
+ return last_completed, error_text
+
+
+@database_sync_to_async
+def _get_rows_synced(source: ExternalDataSource) -> tuple[int, int]:
+ now = timezone.now()
+ in_24h = (
+ ExternalDataJob.objects.filter(
+ pipeline=source,
+ status=ExternalDataJob.Status.COMPLETED,
+ finished_at__gte=now - timedelta(hours=24),
+ ).aggregate(total=Sum("rows_synced"))["total"]
+ or 0
+ )
+ in_7d = (
+ ExternalDataJob.objects.filter(
+ pipeline=source,
+ status=ExternalDataJob.Status.COMPLETED,
+ finished_at__gte=now - timedelta(days=7),
+ ).aggregate(total=Sum("rows_synced"))["total"]
+ or 0
+ )
+ return int(in_24h), int(in_7d)
+
+
+def _resolve_sync_status(
+ *,
+ last_completed_at: datetime | None,
+ last_error_text: str | None,
+ required_tables: list[RequiredTableStatus],
+) -> SyncStatus:
+ """Resolve the source-level sync status. Per-required-table state takes
+ priority over the source-level job state, because the Marketing analytics
+ dashboard surfaces those schema-level issues directly to users (banner)."""
+ missing = [t for t in required_tables if not t.present]
+ if missing:
+ return "tables_missing"
+ failed = [t for t in required_tables if t.status == "Failed"]
+ if failed:
+ return "tables_failed"
+ disabled = [t for t in required_tables if t.present and not t.should_sync]
+ if disabled:
+ return "tables_disabled"
+ if last_error_text is not None:
+ return "error"
+ if last_completed_at is None:
+ return "never"
+ if timezone.now() - last_completed_at > STALE_THRESHOLD:
+ return "stale"
+ return "ok"
+
+
+def _diagnose(
+ *,
+ display_name: str,
+ last_sync_status: SyncStatus,
+ last_completed_at: datetime | None,
+ last_error_text: str | None,
+ sources_map_present: bool,
+ missing_required: list[str],
+ rows_last_7d: int,
+ required_tables: list[RequiredTableStatus],
+ source_id: str | None,
+) -> tuple[str, str | None]:
+ # Per-source Schemas tab — the place to enable/disable required tables,
+ # retry failed syncs, and reconnect. Falls back to the global settings page
+ # when we don't have a source UUID (shouldn't happen for connected sources).
+ schemas_link = _source_schemas_url(source_id) or _MARKETING_SETTINGS_URL
+ if last_sync_status == "tables_missing":
+ names = ", ".join(t.table_name for t in required_tables if not t.present)
+ return (
+ f"{display_name} is missing required tables: {names}.",
+ f"Open {schemas_link} and enable those tables for sync.",
+ )
+ if last_sync_status == "tables_failed":
+ names = ", ".join(t.table_name for t in required_tables if t.status == "Failed")
+ return (
+ f"{display_name} required tables failed to sync: {names}.",
+ f"Open {schemas_link}, inspect the failure and retry the sync.",
+ )
+ if last_sync_status == "tables_disabled":
+ names = ", ".join(t.table_name for t in required_tables if t.present and not t.should_sync)
+ return (
+ f"{display_name} required tables are present but not selected for import: {names}.",
+ f"Open {schemas_link} and enable sync for those tables.",
+ )
+ if last_sync_status == "error":
+ return (
+ f"{display_name} last sync failed: {(last_error_text or '')[:200]}",
+ f"Open {schemas_link} and reconnect or retry the sync.",
+ )
+ if last_sync_status == "never":
+ return (
+ f"{display_name} is connected but has never finished a sync.",
+ f"Trigger a manual sync at {schemas_link}, or wait for the next scheduled run.",
+ )
+ if last_sync_status == "stale":
+ return (
+ f"{display_name} last successful sync is older than 24h.",
+ f"Check the schedule at {schemas_link} or trigger a manual run.",
+ )
+ if missing_required:
+ # Only relevant for non-native sources (BigQuery, S3, self-managed).
+ return (
+ f"{display_name} is syncing but required schema columns are not mapped: {', '.join(missing_required)}.",
+ f"Open {_MARKETING_SETTINGS_URL} and map those columns for {display_name}.",
+ )
+ if rows_last_7d == 0:
+ return (
+ f"{display_name} is healthy but has not synced any rows in the last 7 days.",
+ "Verify that the connected account has active campaigns in the date range.",
+ )
+ return (f"{display_name} is healthy.", None)
+
+
+def _compute_overall_status(entries: list[DataSourceHealthEntry]) -> OverallStatus:
+ connected = [e for e in entries if e.connected]
+ if not connected:
+ return "no_sources"
+ healthy = [e for e in connected if e.last_sync_status == "ok" and not e.schema_columns_required_missing]
+ blocking_states = ("error", "tables_failed", "tables_missing", "tables_disabled")
+ blocked = [e for e in connected if e.last_sync_status in blocking_states]
+ if blocked and not healthy:
+ return "broken"
+ if blocked or any(e.schema_columns_required_missing for e in connected):
+ return "degraded"
+ if all(e.last_sync_status == "ok" for e in connected) and healthy:
+ return "healthy"
+ return "degraded"
+
+
+def _build_issues_summary(entries: list[DataSourceHealthEntry]) -> list[str]:
+ issues: list[str] = []
+ for entry in entries:
+ if entry.connected and entry.last_sync_status != "ok":
+ issues.append(f"{entry.display_name}: {entry.diagnosis}")
+ elif entry.connected and entry.schema_columns_required_missing:
+ issues.append(f"{entry.display_name}: {entry.diagnosis}")
+ return issues
diff --git a/products/marketing_analytics/backend/services/event_suggestions.py b/products/marketing_analytics/backend/services/event_suggestions.py
new file mode 100644
index 000000000000..0279d934bcde
--- /dev/null
+++ b/products/marketing_analytics/backend/services/event_suggestions.py
@@ -0,0 +1,242 @@
+"""Suggest custom events that are good candidates for becoming conversion goals.
+
+Read-only. Ranks events by volume, UTM-tag coverage, and unique users; excludes
+autocaptured/system events and de-prioritizes events already configured as goals.
+"""
+
+from dataclasses import asdict, dataclass, field
+from datetime import timedelta
+from typing import Any
+
+from django.utils import timezone
+
+import structlog
+
+from posthog.hogql import ast
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.clickhouse.query_tagging import Feature, Product, tags_context
+from posthog.models.team.team import Team
+from posthog.sync import database_sync_to_async
+from posthog.taxonomy.taxonomy import CORE_FILTER_DEFINITIONS_BY_GROUP
+
+logger = structlog.get_logger(__name__)
+
+DEFAULT_LOOKBACK_DAYS = 30
+DEFAULT_TOP_N = 20
+DEFAULT_MIN_COUNT = 50
+TOP_UTM_SOURCES_PER_EVENT = 3
+HOGQL_GROUP_LIMIT = 200
+
+# System/autocaptured events excluded. Driven from `CORE_FILTER_DEFINITIONS_BY_GROUP`
+# so new taxonomy events roll in automatically. Overlay covers convention-based events
+# that aren't `$`-prefixed (Surveys: "survey shown"/"sent"/"dismissed").
+_TAXONOMY_OVERLAY_EXCLUDED: frozenset[str] = frozenset(
+ {
+ "survey shown",
+ "survey sent",
+ "survey dismissed",
+ }
+)
+
+
+def _build_default_excluded_events() -> frozenset[str]:
+ taxonomy_events = {key for key in CORE_FILTER_DEFINITIONS_BY_GROUP.get("events", {}) if key.startswith("$")}
+ return frozenset(taxonomy_events | _TAXONOMY_OVERLAY_EXCLUDED)
+
+
+DEFAULT_EXCLUDED_EVENTS: frozenset[str] = _build_default_excluded_events()
+
+# Score weights — tuned so that high-volume events with consistent UTM tagging
+# rank above niche events with perfect UTMs. Tweak before the LLM consumes this.
+SCORE_WEIGHT_VOLUME = 0.40
+SCORE_WEIGHT_UTM_COVERAGE = 0.40
+SCORE_WEIGHT_NOT_ALREADY_GOAL = 0.20
+
+
+@dataclass
+class CandidateEvent:
+ event_name: str
+ last_30d_count: int
+ distinct_users_30d: int
+ pct_with_utm_source: float
+ pct_with_utm_campaign: float
+ top_utm_sources: list[tuple[str, int]]
+ is_already_a_goal: bool
+ suggestion_score: float
+ suggestion_reason: str
+
+
+@dataclass
+class EventSuggestionsResponse:
+ candidates: list[CandidateEvent] = field(default_factory=list)
+ lookback_days: int = DEFAULT_LOOKBACK_DAYS
+ excluded_events_count: int = 0
+
+ def to_dict(self) -> dict[str, Any]:
+ return asdict(self)
+
+
+async def suggest_conversion_goals(
+ team: Team,
+ *,
+ top_n: int = DEFAULT_TOP_N,
+ exclude_autocapture: bool = True,
+ min_count: int = DEFAULT_MIN_COUNT,
+ lookback_days: int = DEFAULT_LOOKBACK_DAYS,
+) -> EventSuggestionsResponse:
+ rows = await _fetch_candidate_rows(team, min_count=min_count, lookback_days=lookback_days)
+ existing_goal_events = await _read_existing_goal_event_names(team)
+ excluded = DEFAULT_EXCLUDED_EVENTS if exclude_autocapture else frozenset()
+
+ # max_volume over the post-exclusion set, so an excluded high-volume event
+ # (e.g. $pageview) doesn't deflate every real candidate's volume score.
+ candidate_rows = [r for r in rows if r["event_name"] not in excluded]
+ max_volume = max((r["count"] for r in candidate_rows), default=1)
+ candidates: list[CandidateEvent] = []
+ for row in candidate_rows:
+ event_name: str = row["event_name"]
+ count = row["count"]
+ users = row["users"]
+ with_utm_source = row["with_utm_source"]
+ with_utm_campaign = row["with_utm_campaign"]
+
+ pct_utm_source = (with_utm_source / count * 100) if count else 0.0
+ pct_utm_campaign = (with_utm_campaign / count * 100) if count else 0.0
+ is_goal = event_name in existing_goal_events
+
+ score = _compute_score(
+ count=count,
+ max_volume=max_volume,
+ pct_utm_source=pct_utm_source,
+ is_already_a_goal=is_goal,
+ )
+ reason = _build_reason(
+ count=count,
+ pct_utm_source=pct_utm_source,
+ is_already_a_goal=is_goal,
+ )
+
+ candidates.append(
+ CandidateEvent(
+ event_name=event_name,
+ last_30d_count=count,
+ distinct_users_30d=users,
+ pct_with_utm_source=round(pct_utm_source, 2),
+ pct_with_utm_campaign=round(pct_utm_campaign, 2),
+ top_utm_sources=row["top_utm_sources"],
+ is_already_a_goal=is_goal,
+ suggestion_score=round(score, 4),
+ suggestion_reason=reason,
+ )
+ )
+
+ candidates.sort(key=lambda c: c.suggestion_score, reverse=True)
+ return EventSuggestionsResponse(
+ candidates=candidates[:top_n],
+ lookback_days=lookback_days,
+ excluded_events_count=len(excluded),
+ )
+
+
+@database_sync_to_async
+def _fetch_candidate_rows(team: Team, *, min_count: int, lookback_days: int) -> list[dict[str, Any]]:
+ """One pass over events: grouped by event name with UTM coverage signals plus
+ the per-event top-K utm_source via ClickHouse's `topK` aggregate."""
+ since = timezone.now() - timedelta(days=lookback_days)
+ aggregate_hogql = """
+ SELECT
+ event,
+ count() AS c,
+ uniq(distinct_id) AS u,
+ countIf(properties.utm_source IS NOT NULL AND properties.utm_source != '') AS with_utm_source,
+ countIf(properties.utm_campaign IS NOT NULL AND properties.utm_campaign != '') AS with_utm_campaign,
+ topK({top_utm})(lower(trim(properties.utm_source))) AS top_utm_sources_raw
+ FROM events
+ WHERE timestamp >= {since}
+ GROUP BY event
+ HAVING c >= {min_count}
+ ORDER BY c DESC
+ LIMIT {limit}
+ """
+ placeholders = {
+ "since": ast.Constant(value=since),
+ "min_count": ast.Constant(value=min_count),
+ "limit": ast.Constant(value=HOGQL_GROUP_LIMIT),
+ "top_utm": ast.Constant(value=TOP_UTM_SOURCES_PER_EVENT),
+ }
+ with tags_context(product=Product.MARKETING_ANALYTICS, feature=Feature.HEALTH_CHECK, team_id=team.pk):
+ aggregated = execute_hogql_query(aggregate_hogql, team, placeholders=placeholders)
+
+ rows: list[dict[str, Any]] = []
+ for row in aggregated.results or []:
+ event_name = row[0]
+ if not event_name:
+ continue
+ # `topK` returns values without counts. For a single source, attribute the
+ # event's total utm_source count; for multiple, use 0 (avoids a second query).
+ raw_top = row[5] or []
+ with_utm_total = int(row[3] or 0)
+ if isinstance(raw_top, list) and len(raw_top) == 1 and raw_top[0]:
+ top_utm_sources = [(str(raw_top[0]), with_utm_total)]
+ else:
+ top_utm_sources = [(str(value), 0) for value in raw_top if value]
+ rows.append(
+ {
+ "event_name": event_name,
+ "count": int(row[1] or 0),
+ "users": int(row[2] or 0),
+ "with_utm_source": with_utm_total,
+ "with_utm_campaign": int(row[4] or 0),
+ "top_utm_sources": top_utm_sources,
+ }
+ )
+
+ return rows
+
+
+@database_sync_to_async
+def _read_existing_goal_event_names(team: Team) -> set[str]:
+ config = getattr(team, "marketing_analytics_config", None)
+ if config is None:
+ return set()
+ goals = config.conversion_goals or []
+ names: set[str] = set()
+ for goal in goals:
+ if goal.get("kind") == "EventsNode":
+ event = goal.get("event")
+ if event:
+ names.add(event)
+ return names
+
+
+def _compute_score(*, count: int, max_volume: int, pct_utm_source: float, is_already_a_goal: bool) -> float:
+ volume_norm = (count / max_volume) if max_volume > 0 else 0.0
+ utm_norm = pct_utm_source / 100.0
+ not_goal_bonus = 0.0 if is_already_a_goal else 1.0
+ return (
+ SCORE_WEIGHT_VOLUME * volume_norm
+ + SCORE_WEIGHT_UTM_COVERAGE * utm_norm
+ + SCORE_WEIGHT_NOT_ALREADY_GOAL * not_goal_bonus
+ )
+
+
+def _build_reason(*, count: int, pct_utm_source: float, is_already_a_goal: bool) -> str:
+ parts = []
+ if count >= 1000:
+ parts.append(f"high volume ({count:,} events)")
+ elif count >= 100:
+ parts.append(f"steady volume ({count:,} events)")
+ else:
+ parts.append(f"{count:,} events")
+ if pct_utm_source >= 70:
+ parts.append(f"strong UTM coverage ({pct_utm_source:.0f}%)")
+ elif pct_utm_source >= 30:
+ parts.append(f"partial UTM coverage ({pct_utm_source:.0f}%)")
+ else:
+ parts.append(f"low UTM coverage ({pct_utm_source:.0f}%)")
+ if is_already_a_goal:
+ parts.append("already configured as a goal")
+ else:
+ parts.append("not yet a goal")
+ return ", ".join(parts)
diff --git a/products/marketing_analytics/backend/services/mapping_suggester.py b/products/marketing_analytics/backend/services/mapping_suggester.py
new file mode 100644
index 000000000000..0e4357b7cfa8
--- /dev/null
+++ b/products/marketing_analytics/backend/services/mapping_suggester.py
@@ -0,0 +1,274 @@
+"""Suggest `custom_source_mappings` entries from recent unmatched UTM-tagged events.
+
+Reuses `attribution_health`'s alias-token suggestions (canonical + team-custom) so
+"unmatched" stays consistent across both surfaces. Ambiguous values are left in the
+catalogue for the LLM to interpret.
+"""
+
+from collections import defaultdict
+from dataclasses import asdict, dataclass, field
+from typing import Any, Literal
+
+import structlog
+
+from posthog.schema import NativeMarketingSource
+
+from posthog.models.team.team import Team
+from posthog.sync import database_sync_to_async
+
+from products.marketing_analytics.backend.services.attribution_health import UnmatchedUtmSample, get_attribution_health
+from products.marketing_analytics.backend.services.native_integrations import (
+ NATIVE_TO_KEY,
+ NativeIntegration,
+ canonical_source_aliases,
+ display_name_for_key,
+)
+
+logger = structlog.get_logger(__name__)
+
+MappingMethod = Literal["exact_alias", "llm"]
+
+# Minimum 30d event count worth suggesting — tiny tails don't justify config changes.
+DEFAULT_MIN_EVENT_COUNT = 10
+
+# Cap suggestions per integration to keep the output digestible by LLMs and UIs.
+MAX_SUGGESTIONS_PER_INTEGRATION = 10
+
+
+@dataclass
+class SourceMappingSuggestion:
+ raw_utm_source: str
+ suggested_target: NativeIntegration
+ suggested_target_display_name: str
+ reason: str
+ event_count_30d: int
+
+
+@dataclass
+class CampaignMappingSuggestion:
+ integration: NativeIntegration
+ integration_display_name: str
+ suggested_clean_name: str
+ raw_campaign_values: list[str]
+ confidence: float
+ method: MappingMethod
+ reason: str
+ event_count_30d: int
+
+
+@dataclass
+class RawUnmatchedSample:
+ """A raw utm_source value that doesn't match any integration. Distinct from
+ `SourceMappingSuggestion`: this is informational (here is what the team
+ has), without committing to a mapping recommendation."""
+
+ raw_utm_source: str
+ event_count: int
+ suggested_integration: NativeIntegration | None
+
+
+@dataclass
+class CurrentMapping:
+ raw_utm_source: str
+ target: NativeIntegration
+ target_display_name: str
+ source: Literal["canonical", "team_custom"]
+
+
+@dataclass
+class CatalogueEntry:
+ """Every utm_source value seen in the window, matched ones included, for a complete picture."""
+
+ raw_utm_source: str
+ event_count: int
+ matched_integration: NativeIntegration | None
+ matched_integration_display_name: str | None
+ suggested_integration: NativeIntegration | None
+
+
+@dataclass
+class UtmMappingSuggestionsResponse:
+ source_suggestions: list[SourceMappingSuggestion] = field(default_factory=list)
+ campaign_suggestions: list[CampaignMappingSuggestion] = field(default_factory=list)
+ raw_unmatched_samples: list[RawUnmatchedSample] = field(default_factory=list)
+ full_utm_source_catalogue: list[CatalogueEntry] = field(default_factory=list)
+ current_mappings: list[CurrentMapping] = field(default_factory=list)
+ total_unmatched_events_in_window: int = 0
+ total_events_with_utm_in_window: int = 0
+ lookback_days_used: int = 0
+ notes: list[str] = field(default_factory=list)
+
+ def to_dict(self) -> dict[str, Any]:
+ return asdict(self)
+
+
+async def suggest_utm_mappings(
+ team: Team,
+ *,
+ min_event_count: int = DEFAULT_MIN_EVENT_COUNT,
+ max_per_integration: int = MAX_SUGGESTIONS_PER_INTEGRATION,
+ lookback_days: int = 90,
+) -> UtmMappingSuggestionsResponse:
+ """Detect unmatched utm_source values and propose target integrations.
+
+ `lookback_days` defaults to 90 (vs attribution_health's 7) to catch typo'd or
+ one-off values worth mapping; widen further for catalog-style audits.
+ """
+ attribution = await get_attribution_health(team, lookback_days=lookback_days)
+ current_mappings = await _read_current_mappings(team)
+ notes: list[str] = []
+
+ # 1. Suggestions: unmatched raw values whose token matches a known alias
+ # (canonical or custom), so they're safe to propose directly. Aggregate
+ # across integrations so each raw value appears once.
+ # Source candidates from the global unmatched list (capped at
+ # MAX_GLOBAL_UNMATCHED), not each integration's per-entry samples — those
+ # are capped at the much smaller MAX_SAMPLE_UNMATCHED, which would make
+ # `max_per_integration` unreachable.
+ by_raw: dict[str, SourceMappingSuggestion] = {}
+ for sample in attribution.sample_globally_unmatched:
+ if sample.event_count < min_event_count or sample.suggested_integration is None:
+ continue
+ if sample.raw_value not in by_raw:
+ by_raw[sample.raw_value] = _to_source_suggestion(sample, sample.suggested_integration)
+
+ # Cap per integration to keep output digestible.
+ grouped: dict[NativeIntegration, list[SourceMappingSuggestion]] = defaultdict(list)
+ for suggestion in by_raw.values():
+ grouped[suggestion.suggested_target].append(suggestion)
+ source_suggestions: list[SourceMappingSuggestion] = []
+ for key, items in grouped.items():
+ items.sort(key=lambda s: s.event_count_30d, reverse=True)
+ if len(items) > max_per_integration:
+ notes.append(
+ f"{display_name_for_key(key)}: showing top {max_per_integration} of {len(items)} candidate values."
+ )
+ source_suggestions.extend(items[:max_per_integration])
+ source_suggestions.sort(key=lambda s: s.event_count_30d, reverse=True)
+
+ # 2. ALL raw unmatched samples, including ones with no suggestion. The LLM
+ # needs the actual catalogue (not just confident guesses) to produce useful
+ # explanations like "you have 152 conversions tagged utm_source=organic —
+ # these are not from any ad platform".
+ raw_unmatched: list[RawUnmatchedSample] = []
+ for s in attribution.sample_globally_unmatched:
+ if s.event_count < min_event_count:
+ continue
+ raw_unmatched.append(
+ RawUnmatchedSample(
+ raw_utm_source=s.raw_value,
+ event_count=s.event_count,
+ suggested_integration=s.suggested_integration,
+ )
+ )
+
+ if attribution.total_events_unmatched > 0 and not source_suggestions:
+ notes.append(
+ f"{attribution.total_events_unmatched} events with unmatched utm_source were seen "
+ f"in the last {lookback_days} days but none had a token matching a known alias. "
+ "The raw values are listed under `raw_unmatched_samples` for the LLM/user to review "
+ "manually — many will be 'organic', 'direct', test campaigns, or partner traffic that "
+ "should NOT be mapped to ad platforms."
+ )
+
+ if attribution.total_events_with_utm == 0:
+ notes.append(
+ f"No events with utm_source were seen in the last {lookback_days} days. This does NOT "
+ "mean the team has never had UTM data — try widening `lookback_days` (e.g. 365) before "
+ "concluding that UTM tagging has never worked. If the longer window also shows 0, then "
+ "UTMs really aren't being captured (check ad URL tagging, SDK install on landing pages, "
+ "and redirects that may strip query params)."
+ )
+
+ if attribution.utm_source_catalogue_truncated:
+ notes.append(
+ "This team has more distinct utm_source values than the analysis cap, so the catalogue "
+ "and the total/matched event counts are top-N subtotals, not exact totals — present them "
+ "as approximate and don't claim an exact distinct-source count."
+ )
+
+ final_notes = [
+ *notes,
+ "Campaign clustering (campaign_name_mappings) is not yet implemented; "
+ "this v1 only proposes custom_source_mappings entries.",
+ ]
+ catalogue: list[CatalogueEntry] = []
+ for entry in attribution.all_utm_source_samples:
+ catalogue.append(
+ CatalogueEntry(
+ raw_utm_source=entry.raw_value,
+ event_count=entry.event_count,
+ matched_integration=entry.matched_integration,
+ matched_integration_display_name=(
+ display_name_for_key(entry.matched_integration) if entry.matched_integration else None
+ ),
+ suggested_integration=entry.suggested_integration,
+ )
+ )
+
+ return UtmMappingSuggestionsResponse(
+ source_suggestions=source_suggestions,
+ campaign_suggestions=[], # campaign clustering disabled in v1
+ raw_unmatched_samples=raw_unmatched,
+ full_utm_source_catalogue=catalogue,
+ current_mappings=current_mappings,
+ total_unmatched_events_in_window=attribution.total_events_unmatched,
+ total_events_with_utm_in_window=attribution.total_events_with_utm,
+ lookback_days_used=lookback_days,
+ notes=final_notes,
+ )
+
+
+@database_sync_to_async
+def _read_team_custom_mappings(team: Team) -> dict:
+ config = getattr(team, "marketing_analytics_config", None)
+ return config.custom_source_mappings if config is not None else {}
+
+
+async def _read_current_mappings(team: Team) -> list[CurrentMapping]:
+ """Return the full list of utm_source → integration mappings already in
+ effect for this team: hardcoded canonical aliases plus the team's
+ `custom_source_mappings`. Allows the LLM to say 'fb is already covered
+ canonically' instead of suggesting it again."""
+ custom = await _read_team_custom_mappings(team)
+ out: list[CurrentMapping] = []
+
+ for alias, target in sorted(canonical_source_aliases().items()):
+ out.append(
+ CurrentMapping(
+ raw_utm_source=alias,
+ target=target,
+ target_display_name=display_name_for_key(target),
+ source="canonical",
+ )
+ )
+ if custom:
+ for integration_type, raw_values in custom.items():
+ try:
+ native = NativeMarketingSource(integration_type)
+ except ValueError:
+ continue
+ custom_target = NATIVE_TO_KEY.get(native)
+ if custom_target is None:
+ continue
+ for raw in raw_values or []:
+ out.append(
+ CurrentMapping(
+ raw_utm_source=str(raw),
+ target=custom_target,
+ target_display_name=display_name_for_key(custom_target),
+ source="team_custom",
+ )
+ )
+ return out
+
+
+def _to_source_suggestion(sample: UnmatchedUtmSample, target: NativeIntegration) -> SourceMappingSuggestion:
+ display = display_name_for_key(target)
+ return SourceMappingSuggestion(
+ raw_utm_source=sample.raw_value,
+ suggested_target=target,
+ suggested_target_display_name=display,
+ reason=f"'{sample.raw_value}' contains a known alias of {display}.",
+ event_count_30d=sample.event_count,
+ )
diff --git a/products/marketing_analytics/backend/services/marketing_diagnostic.py b/products/marketing_analytics/backend/services/marketing_diagnostic.py
new file mode 100644
index 000000000000..61676c2446cc
--- /dev/null
+++ b/products/marketing_analytics/backend/services/marketing_diagnostic.py
@@ -0,0 +1,480 @@
+"""End-to-end marketing analytics diagnostic.
+
+Aggregates `data_source_health` (sync state), `attribution_health` (UTM events),
+and `conversion_goals_inspector` (goal config) into a single per-integration
+`overall_status`. The only service that does cross-domain reasoning: status
+reflects whichever side is most broken, not an AND of "both ok".
+"""
+
+import asyncio
+from collections.abc import Coroutine
+from dataclasses import asdict, dataclass, field
+from typing import Any, Literal, cast
+
+import structlog
+
+from posthog.models.team.team import Team
+from posthog.sync import database_sync_to_async
+
+from products.marketing_analytics.backend.services.attribution_health import (
+ AttributionHealthEntry,
+ AttributionHealthResponse,
+ get_attribution_health,
+)
+from products.marketing_analytics.backend.services.conversion_goals_inspector import (
+ ConversionGoalsListResponse,
+ list_conversion_goals,
+)
+from products.marketing_analytics.backend.services.data_source_health import (
+ DataSourceHealthEntry,
+ DataSourceHealthResponse,
+ get_data_source_health,
+)
+from products.marketing_analytics.backend.services.native_integrations import (
+ EXTERNAL_SOURCE_TYPE_TO_NATIVE,
+ NATIVE_TO_KEY,
+ NativeIntegration,
+ display_name_for_key,
+)
+
+logger = structlog.get_logger(__name__)
+
+
+@database_sync_to_async
+def _load_marketing_config_snapshot(team: Team) -> tuple[dict, dict]:
+ """Read the team's marketing config once and return the two slices the
+ downstream services need: (sources_map, custom_source_mappings). One
+ Postgres trip vs. the previous three (one per service).
+ """
+ config = getattr(team, "marketing_analytics_config", None)
+ if config is None:
+ return {}, {}
+ return (config.sources_map or {}), (config.custom_source_mappings or {})
+
+
+IntegrationStatus = Literal[
+ "healthy", # sync ok + events matched arriving
+ "sync_broken", # sync error/stale
+ "events_broken", # sync ok but no UTM-matched events
+ "events_unmatched", # events arrive but UTM values don't match (fb vs facebook)
+ "events_only", # no platform sync but UTM-matched events arrive (rare)
+ "schema_misconfigured", # connected and syncing but required schema columns unmapped
+ "not_connected", # no source for this integration
+]
+
+OverallStatus = Literal[
+ "healthy",
+ "degraded",
+ "broken",
+ "no_sources",
+]
+
+ActionSeverity = Literal["error", "warning", "info"]
+
+
+@dataclass
+class RecommendedAction:
+ title: str
+ detail: str
+ severity: ActionSeverity
+ target_tool: str | None = None # MaxTool / MCP tool name to invoke next, if any
+
+
+@dataclass
+class IntegrationDiagnostic:
+ integration_key: NativeIntegration
+ source_type: str
+ display_name: str
+ overall_status: IntegrationStatus
+ diagnosis: str
+ data_source: DataSourceHealthEntry | None
+ attribution: AttributionHealthEntry | None
+ recommended_actions: list[RecommendedAction] = field(default_factory=list)
+
+
+@dataclass
+class MarketingDiagnosticResponse:
+ integrations: list[IntegrationDiagnostic] = field(default_factory=list)
+ overall_status: OverallStatus = "no_sources"
+ summary: str = ""
+ conversion_goals: ConversionGoalsListResponse | None = None
+ recommended_actions: list[RecommendedAction] = field(default_factory=list)
+
+ def to_dict(self) -> dict[str, Any]:
+ return asdict(self)
+
+
+async def get_marketing_diagnostic(
+ team: Team,
+ *,
+ source_type: str | None = None,
+ include_conversion_goals: bool = True,
+ attribution_lookback_days: int = 7,
+) -> MarketingDiagnosticResponse:
+ """Fetch all per-domain signals in parallel and combine into a unified view.
+
+ `attribution_lookback_days` defaults to 7 (the canonical "is it healthy
+ right now?" window). Widen it when the diagnostic is being asked over a
+ longer period.
+ """
+ sources_map, custom_source_mappings = await _load_marketing_config_snapshot(team)
+
+ coros: list[Coroutine[Any, Any, Any]] = [
+ get_data_source_health(team, source_type=source_type, sources_map=sources_map),
+ get_attribution_health(
+ team,
+ source_type=source_type,
+ lookback_days=attribution_lookback_days,
+ custom_source_mappings=custom_source_mappings,
+ ),
+ ]
+ if include_conversion_goals:
+ coros.append(list_conversion_goals(team))
+
+ # `return_exceptions=True` so one failing sub-service doesn't abort the whole
+ # diagnostic. Data-source and attribution health are required to diagnose, so
+ # we re-raise those; conversion goals are supplementary and degrade to None.
+ results = await asyncio.gather(*coros, return_exceptions=True)
+
+ data_source_result = results[0]
+ if isinstance(data_source_result, BaseException):
+ logger.error("marketing_diagnostic.data_source_health_failed", team_id=team.pk, error=str(data_source_result))
+ raise data_source_result
+ attribution_result = results[1]
+ if isinstance(attribution_result, BaseException):
+ logger.error("marketing_diagnostic.attribution_health_failed", team_id=team.pk, error=str(attribution_result))
+ raise attribution_result
+ data_source = cast(DataSourceHealthResponse, data_source_result)
+ attribution = cast(AttributionHealthResponse, attribution_result)
+
+ goals: ConversionGoalsListResponse | None = None
+ if include_conversion_goals:
+ goals_result = results[2]
+ if isinstance(goals_result, BaseException):
+ logger.warning("marketing_diagnostic.conversion_goals_failed", team_id=team.pk, error=str(goals_result))
+ else:
+ goals = cast(ConversionGoalsListResponse, goals_result)
+
+ integrations = _build_integration_diagnostics(data_source, attribution)
+ overall = _compute_overall_status(integrations)
+ summary = _build_summary(integrations, overall, goals)
+ top_actions = _global_recommended_actions(integrations, goals)
+
+ return MarketingDiagnosticResponse(
+ integrations=integrations,
+ overall_status=overall,
+ summary=summary,
+ conversion_goals=goals,
+ recommended_actions=top_actions,
+ )
+
+
+def _build_integration_diagnostics(
+ data_source: DataSourceHealthResponse,
+ attribution: AttributionHealthResponse,
+) -> list[IntegrationDiagnostic]:
+ """For each integration that appears in either side, derive its overall_status,
+ diagnosis text, and a small set of recommended next steps."""
+ ds_by_source_type: dict[str, DataSourceHealthEntry] = {
+ entry.source_type: entry for entry in data_source.integrations
+ }
+ attribution_by_key: dict[NativeIntegration, AttributionHealthEntry] = {
+ entry.integration_key: entry for entry in attribution.integrations
+ }
+
+ diagnostics: list[IntegrationDiagnostic] = []
+ seen_keys: set[NativeIntegration] = set()
+
+ # Iterate through the canonical native list so output ordering is stable.
+ for source_type_str, native in EXTERNAL_SOURCE_TYPE_TO_NATIVE.items():
+ key = NATIVE_TO_KEY[native]
+ seen_keys.add(key)
+ ds_entry = ds_by_source_type.get(source_type_str)
+ attribution_entry = attribution_by_key.get(key)
+ diagnostics.append(_diagnose_one(source_type_str, key, ds_entry, attribution_entry))
+
+ # Surface attribution-only entries (events matching an integration the team
+ # never connected) — that's the `events_only` corner case.
+ for key, attribution_entry in attribution_by_key.items():
+ if key in seen_keys:
+ continue
+ seen_keys.add(key)
+ # Resolve back to the canonical source_type string for completeness.
+ source_type_str = next(
+ (st for st, native in EXTERNAL_SOURCE_TYPE_TO_NATIVE.items() if NATIVE_TO_KEY[native] == key),
+ key,
+ )
+ diagnostics.append(_diagnose_one(source_type_str, key, None, attribution_entry))
+
+ return diagnostics
+
+
+def _diagnose_one(
+ source_type_str: str,
+ key: NativeIntegration,
+ ds: DataSourceHealthEntry | None,
+ attr: AttributionHealthEntry | None,
+) -> IntegrationDiagnostic:
+ display = display_name_for_key(key)
+ actions: list[RecommendedAction] = []
+
+ sync_ok = ds is not None and ds.connected and ds.last_sync_status == "ok"
+ sync_broken = ds is not None and ds.connected and ds.last_sync_status in ("error", "stale", "never")
+ tables_broken = (
+ ds is not None
+ and ds.connected
+ and ds.last_sync_status
+ in (
+ "tables_failed",
+ "tables_missing",
+ "tables_disabled",
+ )
+ )
+ schema_missing = ds is not None and bool(ds.schema_columns_required_missing)
+ not_connected = ds is None or not ds.connected
+
+ has_matched_events = attr is not None and attr.events_matched_last_7d > 0
+ has_likely_yours = attr is not None and attr.events_unmatched_likely_yours_last_7d > 0
+
+ if not_connected and not has_matched_events and not has_likely_yours:
+ return IntegrationDiagnostic(
+ integration_key=key,
+ source_type=source_type_str,
+ display_name=display,
+ overall_status="not_connected",
+ diagnosis=f"{display} is not connected and no events with matching utm_source were seen.",
+ data_source=ds,
+ attribution=attr,
+ recommended_actions=[],
+ )
+
+ if not_connected and (has_matched_events or has_likely_yours):
+ actions.append(
+ RecommendedAction(
+ title=f"Connect {display}",
+ detail=(
+ f"Events with utm_source matching {display} are arriving "
+ f"({attr.events_matched_last_7d if attr else 0} matched, "
+ f"{attr.events_unmatched_likely_yours_last_7d if attr else 0} likely-yours), "
+ "but the platform is not connected. Connect it to enable cost/ROAS analysis."
+ ),
+ severity="warning",
+ target_tool=None,
+ )
+ )
+ return IntegrationDiagnostic(
+ integration_key=key,
+ source_type=source_type_str,
+ display_name=display,
+ overall_status="events_only",
+ diagnosis=(
+ f"{display} is not connected, but UTM-tagged events for it are arriving. "
+ "Connect the platform to attribute spend to those events."
+ ),
+ data_source=ds,
+ attribution=attr,
+ recommended_actions=actions,
+ )
+
+ # `ds` is non-None past the not_connected early-returns; narrow for mypy.
+ assert ds is not None
+
+ if sync_broken or tables_broken:
+ actions.append(
+ RecommendedAction(
+ title=f"Fix sync for {display}",
+ detail=ds.fix_suggestion or "Inspect Data warehouse and retry the sync.",
+ severity="error",
+ target_tool=None,
+ )
+ )
+ return IntegrationDiagnostic(
+ integration_key=key,
+ source_type=source_type_str,
+ display_name=display,
+ overall_status="sync_broken",
+ diagnosis=ds.diagnosis,
+ data_source=ds,
+ attribution=attr,
+ recommended_actions=actions,
+ )
+
+ if sync_ok and schema_missing:
+ actions.append(
+ RecommendedAction(
+ title=f"Map required schema columns for {display}",
+ detail=ds.fix_suggestion or "Open Marketing analytics settings and complete the column mapping.",
+ severity="error",
+ target_tool=None,
+ )
+ )
+ return IntegrationDiagnostic(
+ integration_key=key,
+ source_type=source_type_str,
+ display_name=display,
+ overall_status="schema_misconfigured",
+ diagnosis=ds.diagnosis,
+ data_source=ds,
+ attribution=attr,
+ recommended_actions=actions,
+ )
+
+ if sync_ok and not has_matched_events and has_likely_yours:
+ # `has_likely_yours` is only true when `attr is not None`; narrow for mypy.
+ assert attr is not None
+ actions.append(
+ RecommendedAction(
+ title=f"Map UTM source variants to {display}",
+ detail=(
+ f"{attr.events_unmatched_likely_yours_last_7d} events look like they belong to "
+ f"{display} (e.g. 'fb', 'facebook') but don't match exactly. Use suggest_utm_mappings to "
+ "propose custom_source_mappings entries, then add them at "
+ "/settings/environment-marketing-analytics#marketing-settings."
+ ),
+ severity="warning",
+ target_tool="marketing_suggest_utm_mappings",
+ )
+ )
+ return IntegrationDiagnostic(
+ integration_key=key,
+ source_type=source_type_str,
+ display_name=display,
+ overall_status="events_unmatched",
+ diagnosis=(
+ f"{display} is syncing fine, but {attr.events_unmatched_likely_yours_last_7d} likely-{display} "
+ "events arrive with UTM values that don't match. Mapping them will fix attribution."
+ ),
+ data_source=ds,
+ attribution=attr,
+ recommended_actions=actions,
+ )
+
+ if sync_ok and not has_matched_events and not has_likely_yours:
+ actions.append(
+ RecommendedAction(
+ title=f"Verify UTM tagging for {display}",
+ detail=(
+ f"{display} is syncing fine but no events with matching utm_source arrived in the last 7 "
+ "days. Check that ad URLs include the correct utm_source parameter, and that PostHog is "
+ "capturing events on the landing pages."
+ ),
+ severity="warning",
+ target_tool="marketing_audit_utm",
+ )
+ )
+ return IntegrationDiagnostic(
+ integration_key=key,
+ source_type=source_type_str,
+ display_name=display,
+ overall_status="events_broken",
+ diagnosis=(
+ f"{display} is healthy on the data side but no UTM-matched events arrived in the last 7 "
+ "days. Either the platform isn't driving traffic, or UTMs aren't being captured."
+ ),
+ data_source=ds,
+ attribution=attr,
+ recommended_actions=actions,
+ )
+
+ return IntegrationDiagnostic(
+ integration_key=key,
+ source_type=source_type_str,
+ display_name=display,
+ overall_status="healthy",
+ diagnosis=(
+ f"{display} is healthy: syncing on schedule and "
+ f"{attr.events_matched_last_7d if attr else 0} matched events in the last 7 days."
+ ),
+ data_source=ds,
+ attribution=attr,
+ recommended_actions=actions,
+ )
+
+
+def _compute_overall_status(integrations: list[IntegrationDiagnostic]) -> OverallStatus:
+ statuses = [i.overall_status for i in integrations]
+ relevant = [s for s in statuses if s != "not_connected"]
+ if not relevant:
+ return "no_sources"
+ if all(s == "healthy" for s in relevant):
+ return "healthy"
+ if any(s in ("sync_broken", "schema_misconfigured") for s in relevant) and not any(
+ s == "healthy" for s in relevant
+ ):
+ return "broken"
+ return "degraded"
+
+
+def _build_summary(
+ integrations: list[IntegrationDiagnostic],
+ overall: OverallStatus,
+ goals: ConversionGoalsListResponse | None,
+) -> str:
+ connected_count = sum(1 for i in integrations if i.overall_status != "not_connected")
+ if overall == "no_sources":
+ return "No marketing integrations are connected for this project."
+
+ healthy_count = sum(1 for i in integrations if i.overall_status == "healthy")
+ if overall == "healthy":
+ base = f"{healthy_count} of {connected_count} integrations are healthy."
+ elif overall == "broken":
+ base = f"All {connected_count} relevant integrations have problems."
+ else:
+ problem_count = connected_count - healthy_count
+ base = f"{problem_count} of {connected_count} integrations have problems."
+
+ if goals is not None:
+ if goals.has_misconfigured:
+ base += f" {sum(1 for g in goals.goals if g.is_misconfigured)} conversion goal(s) are misconfigured."
+ elif goals.goals:
+ base += f" {len(goals.goals)} conversion goal(s) configured."
+ else:
+ base += " No conversion goals configured."
+
+ return base
+
+
+def _global_recommended_actions(
+ integrations: list[IntegrationDiagnostic],
+ goals: ConversionGoalsListResponse | None,
+) -> list[RecommendedAction]:
+ """Promote per-integration actions and add cross-integration ones."""
+ actions: list[RecommendedAction] = []
+
+ if goals is not None:
+ if not goals.goals:
+ actions.append(
+ RecommendedAction(
+ title="Configure at least one conversion goal",
+ detail=(
+ "No conversion goals are configured. Use suggest_conversion_goals to see ranked "
+ "candidates from your existing custom events."
+ ),
+ severity="warning",
+ target_tool="marketing_suggest_conversion_goals",
+ )
+ )
+ elif goals.has_misconfigured:
+ misconfigured = [g for g in goals.goals if g.is_misconfigured]
+ actions.append(
+ RecommendedAction(
+ title=f"Fix {len(misconfigured)} misconfigured conversion goal(s)",
+ detail=(
+ "Some conversion goals reference missing actions or DW tables: "
+ + ", ".join(g.name for g in misconfigured[:3])
+ + ("..." if len(misconfigured) > 3 else "")
+ ),
+ severity="error",
+ target_tool=None,
+ )
+ )
+
+ # Lift the most severe per-integration action up to the global list, capped.
+ severity_order = {"error": 0, "warning": 1, "info": 2}
+ per_integration_actions: list[RecommendedAction] = []
+ for integration in integrations:
+ per_integration_actions.extend(integration.recommended_actions)
+ per_integration_actions.sort(key=lambda a: severity_order.get(a.severity, 99))
+ actions.extend(per_integration_actions[:5])
+
+ return actions
diff --git a/products/marketing_analytics/backend/services/native_integrations.py b/products/marketing_analytics/backend/services/native_integrations.py
new file mode 100644
index 000000000000..7e1a90359c59
--- /dev/null
+++ b/products/marketing_analytics/backend/services/native_integrations.py
@@ -0,0 +1,164 @@
+"""Canonical metadata for native marketing integrations: snake-case keys, display
+names, and the static UTM aliases used to recognize ad-platform traffic.
+
+Keep alias keys lowercase and alphanumeric-only — `normalize()` strips everything
+else before lookup.
+"""
+
+from collections.abc import Iterator, Mapping
+from functools import cache
+from types import MappingProxyType
+from typing import Literal
+
+from posthog.schema import NativeMarketingSource
+
+NativeIntegration = Literal[
+ "google_ads",
+ "meta_ads",
+ "bing_ads",
+ "linkedin_ads",
+ "reddit_ads",
+ "pinterest_ads",
+ "snapchat_ads",
+ "tiktok_ads",
+]
+
+
+# Mapping from NativeMarketingSource to the snake-case key used everywhere
+# downstream (URL params, scope hints, suggestion targets).
+NATIVE_TO_KEY: dict[NativeMarketingSource, NativeIntegration] = {
+ NativeMarketingSource.GOOGLE_ADS: "google_ads",
+ NativeMarketingSource.META_ADS: "meta_ads",
+ NativeMarketingSource.BING_ADS: "bing_ads",
+ NativeMarketingSource.LINKEDIN_ADS: "linkedin_ads",
+ NativeMarketingSource.REDDIT_ADS: "reddit_ads",
+ NativeMarketingSource.PINTEREST_ADS: "pinterest_ads",
+ NativeMarketingSource.SNAPCHAT_ADS: "snapchat_ads",
+ NativeMarketingSource.TIK_TOK_ADS: "tiktok_ads",
+}
+
+KEY_TO_NATIVE: dict[NativeIntegration, NativeMarketingSource] = {v: k for k, v in NATIVE_TO_KEY.items()}
+
+
+# Mapping from `ExternalDataSource.source_type` (PascalCase strings the DW
+# layer uses) to NativeMarketingSource. Pinned explicitly because
+# ExternalDataSourceType has many non-marketing entries.
+EXTERNAL_SOURCE_TYPE_TO_NATIVE: dict[str, NativeMarketingSource] = {
+ "GoogleAds": NativeMarketingSource.GOOGLE_ADS,
+ "MetaAds": NativeMarketingSource.META_ADS,
+ "BingAds": NativeMarketingSource.BING_ADS,
+ "LinkedinAds": NativeMarketingSource.LINKEDIN_ADS,
+ "RedditAds": NativeMarketingSource.REDDIT_ADS,
+ "PinterestAds": NativeMarketingSource.PINTEREST_ADS,
+ "SnapchatAds": NativeMarketingSource.SNAPCHAT_ADS,
+ "TikTokAds": NativeMarketingSource.TIK_TOK_ADS,
+}
+
+# Human-facing names for surfaces that produce text (LLMs, UI, error messages).
+DISPLAY_NAMES: dict[NativeMarketingSource, str] = {
+ NativeMarketingSource.GOOGLE_ADS: "Google Ads",
+ NativeMarketingSource.META_ADS: "Meta Ads",
+ NativeMarketingSource.BING_ADS: "Bing Ads",
+ NativeMarketingSource.LINKEDIN_ADS: "LinkedIn Ads",
+ NativeMarketingSource.REDDIT_ADS: "Reddit Ads",
+ NativeMarketingSource.PINTEREST_ADS: "Pinterest Ads",
+ NativeMarketingSource.SNAPCHAT_ADS: "Snapchat Ads",
+ NativeMarketingSource.TIK_TOK_ADS: "TikTok Ads",
+}
+
+
+def display_name_for_key(key: NativeIntegration) -> str:
+ return DISPLAY_NAMES[KEY_TO_NATIVE[key]]
+
+
+def normalize(value: str) -> str:
+ """Lowercase and strip non-alphanumerics. `Facebook-Ads` → `facebookads`."""
+ return "".join(c.lower() for c in value if c.isalnum())
+
+
+def _build_canonical_aliases() -> dict[str, NativeIntegration]:
+ """Build the alias table from `INTEGRATION_DEFAULT_SOURCES` (the source of truth
+ shared with adapters and the dashboard, so they agree on what's integrated).
+
+ Lazy to avoid a circular import: the constants module imports services
+ indirectly during Django app boot.
+ """
+ from products.marketing_analytics.backend.hogql_queries.constants import INTEGRATION_DEFAULT_SOURCES
+
+ out: dict[str, NativeIntegration] = {}
+ for native, defaults in INTEGRATION_DEFAULT_SOURCES.items():
+ target = NATIVE_TO_KEY.get(native)
+ if target is None:
+ continue
+ for value in defaults:
+ out[normalize(value)] = target
+ return out
+
+
+@cache
+def canonical_source_aliases() -> Mapping[str, NativeIntegration]:
+ """Canonical alias table from the official `*DefaultSources` enums. Cached and
+ returned as a read-only `MappingProxyType`; keys are normalized."""
+ return MappingProxyType(_build_canonical_aliases())
+
+
+def lookup_alias(raw_utm_source: str) -> NativeIntegration | None:
+ """Exact hit against the canonical alias table only. To also honor a team's
+ `custom_source_mappings`, use `build_combined_alias_map` + `lookup_in`."""
+ return canonical_source_aliases().get(normalize(raw_utm_source))
+
+
+@cache
+def aliases_for(integration: NativeIntegration) -> frozenset[str]:
+ """All known raw values resolving to this integration (normalized).
+
+ Cached — `attribution_health` and `mapping_suggester` call this in tight loops.
+ """
+ return frozenset(alias for alias, target in canonical_source_aliases().items() if target == integration)
+
+
+def iter_custom_source_mappings(
+ custom_source_mappings: dict | None,
+) -> Iterator[tuple[NativeIntegration, str]]:
+ """Yield (target_native_key, raw_utm_source) pairs from a team's
+ `custom_source_mappings`, skipping unknown integration types.
+
+ Single source of truth for iterating the config — both the alias map and
+ `utm_audit` consume this so enum-resolution rules don't drift.
+ """
+ if not custom_source_mappings:
+ return
+ for integration_type, custom_sources in custom_source_mappings.items():
+ try:
+ native = NativeMarketingSource(integration_type)
+ except ValueError:
+ continue
+ target = NATIVE_TO_KEY.get(native)
+ if target is None:
+ continue
+ for raw in custom_sources or []:
+ if not raw:
+ continue
+ yield target, str(raw)
+
+
+def build_combined_alias_map(custom_source_mappings: dict | None) -> dict[str, NativeIntegration]:
+ """Merge the canonical alias table with the team's `custom_source_mappings`.
+
+ The team config keys are PascalCase NativeMarketingSource values (e.g.
+ 'GoogleAds') and the values are arbitrary user-configured raw utm_source
+ strings (e.g. `['meta2', 'fb-paid']`). We normalize keys consistently so a
+ single dict lookup answers the question.
+
+ Team mappings WIN over the canonical table — a user can override `fb` to
+ point somewhere unusual if they really want to.
+ """
+ combined: dict[str, NativeIntegration] = dict(canonical_source_aliases())
+ for target, raw in iter_custom_source_mappings(custom_source_mappings):
+ combined[normalize(raw)] = target
+ return combined
+
+
+def lookup_in(value: str, alias_map: dict[str, NativeIntegration]) -> NativeIntegration | None:
+ """Lookup against a precomputed alias map (typically from `build_combined_alias_map`)."""
+ return alias_map.get(normalize(value))
diff --git a/products/marketing_analytics/backend/services/test_attribution_health.py b/products/marketing_analytics/backend/services/test_attribution_health.py
new file mode 100644
index 000000000000..12f1e61f7335
--- /dev/null
+++ b/products/marketing_analytics/backend/services/test_attribution_health.py
@@ -0,0 +1,354 @@
+from datetime import UTC, datetime, timedelta
+
+import pytest
+from posthog.test.base import APIBaseTest, BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
+from unittest.mock import AsyncMock, patch
+
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from products.marketing_analytics.backend.services.attribution_health import (
+ HOGQL_GROUP_LIMIT,
+ _suggest_integration_by_alias_token,
+ _UtmRow,
+ get_attribution_health,
+)
+from products.marketing_analytics.backend.services.native_integrations import NATIVE_TO_KEY, build_combined_alias_map
+
+_ALIAS_MAP = build_combined_alias_map({})
+_ALL_TARGETS = set(NATIVE_TO_KEY.values())
+
+
+class TestSuggestIntegrationByAliasToken:
+ @parameterized.expand(
+ [
+ ("no_token_match", "zzzzzz"),
+ ("empty_string", ""),
+ ("typo_is_not_a_token", "fcebook"),
+ ]
+ )
+ def test_returns_none(self, _name, raw):
+ assert _suggest_integration_by_alias_token(raw, _ALIAS_MAP, _ALL_TARGETS) is None
+
+ def test_token_matches_a_known_alias(self):
+ alias, integration = next(iter(_ALIAS_MAP.items()))
+ assert _suggest_integration_by_alias_token(f"{alias}_paid", _ALIAS_MAP, _ALL_TARGETS) == integration
+
+ def test_respects_allowed_scope(self):
+ alias, integration = next(iter(_ALIAS_MAP.items()))
+ allowed_without = _ALL_TARGETS - {integration}
+ assert _suggest_integration_by_alias_token(f"{alias}_paid", _ALIAS_MAP, allowed_without) is None
+
+
+class TestGetAttributionHealth(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ from products.marketing_analytics.backend.services.native_integrations import canonical_source_aliases
+
+ fetch_patcher = patch(
+ "products.marketing_analytics.backend.services.attribution_health._fetch_utm_groups",
+ new_callable=AsyncMock,
+ )
+ alias_patcher = patch(
+ "products.marketing_analytics.backend.services.attribution_health._build_team_alias_map",
+ new_callable=AsyncMock,
+ )
+ self.mock_fetch = fetch_patcher.start()
+ self.mock_alias = alias_patcher.start()
+ self.addCleanup(fetch_patcher.stop)
+ self.addCleanup(alias_patcher.stop)
+
+ self.mock_fetch.return_value = []
+ # Real canonical alias table — gives tests realistic match behavior
+ # without going through the team's marketing_analytics_config.
+ self.mock_alias.return_value = dict(canonical_source_aliases())
+
+ @pytest.mark.asyncio
+ async def test_no_events_returns_zeroed_response(self):
+ response = await get_attribution_health(self.team)
+ assert response.total_events_with_utm == 0
+ assert response.total_events_matched_to_any_integration == 0
+ assert response.total_events_unmatched == 0
+ assert response.sample_globally_unmatched == []
+ assert all(e.events_matched_last_7d == 0 for e in response.integrations)
+
+ @pytest.mark.asyncio
+ async def test_known_alias_counts_as_matched(self):
+ self.mock_fetch.return_value = [
+ _UtmRow(raw_utm_source="facebook", event_count=120, last_seen_at=None),
+ _UtmRow(raw_utm_source="adwords", event_count=80, last_seen_at=None),
+ ]
+
+ response = await get_attribution_health(self.team)
+
+ assert response.total_events_with_utm == 200
+ assert response.total_events_matched_to_any_integration == 200
+ assert response.total_events_unmatched == 0
+
+ meta = next(e for e in response.integrations if e.integration_key == "meta_ads")
+ google = next(e for e in response.integrations if e.integration_key == "google_ads")
+ assert meta.events_matched_last_7d == 120
+ assert google.events_matched_last_7d == 80
+ assert meta.matched_pct == round(120 / 200 * 100, 2)
+
+ @pytest.mark.asyncio
+ async def test_token_variant_classified_as_likely_yours(self):
+ self.mock_fetch.return_value = [
+ _UtmRow(raw_utm_source="facebook_paid", event_count=50, last_seen_at=None),
+ ]
+
+ response = await get_attribution_health(self.team)
+
+ meta = next(e for e in response.integrations if e.integration_key == "meta_ads")
+ assert meta.events_matched_last_7d == 0
+ assert meta.events_unmatched_likely_yours_last_7d == 50
+ assert response.total_events_unmatched == 50
+ assert response.sample_globally_unmatched
+ first_sample = response.sample_globally_unmatched[0]
+ assert first_sample.raw_value == "facebook_paid"
+ assert first_sample.suggested_integration == "meta_ads"
+
+ @pytest.mark.asyncio
+ async def test_completely_unrelated_value_unmatched_no_likely(self):
+ self.mock_fetch.return_value = [
+ _UtmRow(raw_utm_source="zzz123", event_count=10, last_seen_at=None),
+ ]
+
+ response = await get_attribution_health(self.team)
+
+ assert response.total_events_unmatched == 10
+ for entry in response.integrations:
+ assert entry.events_unmatched_likely_yours_last_7d == 0
+
+ @pytest.mark.asyncio
+ async def test_filter_by_source_type_limits_output_but_not_totals(self):
+ self.mock_fetch.return_value = [
+ _UtmRow(raw_utm_source="facebook", event_count=100, last_seen_at=None),
+ _UtmRow(raw_utm_source="adwords", event_count=200, last_seen_at=None),
+ ]
+
+ response = await get_attribution_health(self.team, source_type="GoogleAds")
+
+ assert len(response.integrations) == 1
+ assert response.integrations[0].integration_key == "google_ads"
+ # Totals reflect ALL events the team had (intentional — overall context still useful).
+ assert response.total_events_with_utm == 300
+ assert response.total_events_matched_to_any_integration == 300
+
+ @pytest.mark.asyncio
+ async def test_unknown_source_type_filter_returns_empty(self):
+ self.mock_fetch.return_value = [
+ _UtmRow(raw_utm_source="facebook", event_count=100, last_seen_at=None),
+ ]
+ response = await get_attribution_health(self.team, source_type="NotASource")
+ assert response.integrations == []
+
+ @pytest.mark.asyncio
+ async def test_last_event_with_matching_utm_is_max_across_aliases(self):
+ earlier = datetime(2026, 4, 1, 12, 0, tzinfo=UTC)
+ later = datetime(2026, 4, 30, 12, 0, tzinfo=UTC)
+ self.mock_fetch.return_value = [
+ _UtmRow(raw_utm_source="facebook", event_count=10, last_seen_at=earlier),
+ _UtmRow(raw_utm_source="fb", event_count=5, last_seen_at=later),
+ _UtmRow(raw_utm_source="instagram", event_count=3, last_seen_at=earlier),
+ ]
+
+ response = await get_attribution_health(self.team)
+
+ meta = next(e for e in response.integrations if e.integration_key == "meta_ads")
+ assert meta.last_event_with_matching_utm_at == later
+ assert meta.events_matched_last_7d == 18
+
+ @pytest.mark.asyncio
+ async def test_globally_unmatched_sorted_by_event_count(self):
+ self.mock_fetch.return_value = [
+ _UtmRow(raw_utm_source="zzz1", event_count=5, last_seen_at=None),
+ _UtmRow(raw_utm_source="zzz2", event_count=50, last_seen_at=None),
+ _UtmRow(raw_utm_source="zzz3", event_count=20, last_seen_at=None),
+ ]
+
+ response = await get_attribution_health(self.team)
+
+ counts = [s.event_count for s in response.sample_globally_unmatched]
+ assert counts == sorted(counts, reverse=True)
+
+
+def _pageview(team: object, distinct_id: str, utm_source: str | None = None) -> None:
+ props: dict = {}
+ if utm_source is not None:
+ props["utm_source"] = utm_source
+ _create_event(
+ distinct_id=distinct_id,
+ event="$pageview",
+ team=team,
+ properties=props,
+ timestamp=timezone.now() - timedelta(hours=1),
+ )
+
+
+class TestAttributionHealthKnownSourcesClickhouse(ClickhouseTestMixin, BaseTest):
+ CLASS_DATA_LEVEL_SETUP = False
+
+ def setUp(self) -> None:
+ super().setUp()
+ _pageview(self.team, "u1", utm_source="google")
+ _pageview(self.team, "u2", utm_source="google")
+ _pageview(self.team, "u3", utm_source="facebook")
+ flush_persons_and_events()
+
+ def tearDown(self) -> None:
+ flush_persons_and_events()
+ super().tearDown()
+
+ @pytest.mark.asyncio
+ async def test_known_integration_source_counted_as_matched(self) -> None:
+ response = await get_attribution_health(self.team, lookback_days=30)
+
+ assert response.total_events_with_utm == 3
+ assert response.total_events_matched_to_any_integration == 3
+ assert response.total_events_unmatched == 0
+
+ google = next((e for e in response.integrations if e.integration_key == "google_ads"), None)
+ meta = next((e for e in response.integrations if e.integration_key == "meta_ads"), None)
+ assert google is not None
+ assert meta is not None
+ assert google.events_matched_last_7d == 2
+ assert meta.events_matched_last_7d == 1
+
+
+class TestAttributionHealthMisspelledSourceClickhouse(ClickhouseTestMixin, BaseTest):
+ CLASS_DATA_LEVEL_SETUP = False
+
+ def setUp(self) -> None:
+ super().setUp()
+ _pageview(self.team, "u1", utm_source="fcebook")
+ flush_persons_and_events()
+
+ def tearDown(self) -> None:
+ flush_persons_and_events()
+ super().tearDown()
+
+ @pytest.mark.asyncio
+ async def test_misspelled_source_counted_as_unmatched_not_matched(self) -> None:
+ response = await get_attribution_health(self.team, lookback_days=30)
+
+ assert response.total_events_with_utm == 1
+ assert response.total_events_matched_to_any_integration == 0
+ assert response.total_events_unmatched == 1
+ assert len(response.sample_globally_unmatched) == 1
+ assert response.sample_globally_unmatched[0].raw_value == "fcebook"
+
+
+class TestAttributionHealthNoUtmClickhouse(ClickhouseTestMixin, BaseTest):
+ CLASS_DATA_LEVEL_SETUP = False
+
+ def setUp(self) -> None:
+ super().setUp()
+ _pageview(self.team, "u1", utm_source=None)
+ _pageview(self.team, "u2", utm_source=None)
+ flush_persons_and_events()
+
+ def tearDown(self) -> None:
+ flush_persons_and_events()
+ super().tearDown()
+
+ @pytest.mark.asyncio
+ async def test_events_without_utm_source_not_counted(self) -> None:
+ response = await get_attribution_health(self.team, lookback_days=30)
+
+ assert response.total_events_with_utm == 0
+ assert response.total_distinct_utm_sources == 0
+
+
+class TestAttributionHealthUtmNormalizationClickhouse(ClickhouseTestMixin, BaseTest):
+ CLASS_DATA_LEVEL_SETUP = False
+
+ def setUp(self) -> None:
+ super().setUp()
+ _pageview(self.team, "u1", utm_source=" Google ")
+ _pageview(self.team, "u2", utm_source="GOOGLE")
+ flush_persons_and_events()
+
+ def tearDown(self) -> None:
+ flush_persons_and_events()
+ super().tearDown()
+
+ @pytest.mark.asyncio
+ async def test_hogql_trims_and_lowercases_utm_source(self) -> None:
+ response = await get_attribution_health(self.team, lookback_days=30)
+
+ assert response.total_events_with_utm == 2
+ assert response.total_events_matched_to_any_integration == 2
+ raw_values = {s.raw_value for s in response.all_utm_source_samples}
+ assert "google" in raw_values
+ assert " Google " not in raw_values
+ assert "GOOGLE" not in raw_values
+
+
+class TestAttributionHealthMixedSourcesClickhouse(ClickhouseTestMixin, BaseTest):
+ CLASS_DATA_LEVEL_SETUP = False
+
+ def setUp(self) -> None:
+ super().setUp()
+ _pageview(self.team, "u1", utm_source="google")
+ _pageview(self.team, "u2", utm_source="fcebook")
+ _pageview(self.team, "u3", utm_source="organic")
+ _pageview(self.team, "u4", utm_source=None)
+ flush_persons_and_events()
+
+ def tearDown(self) -> None:
+ flush_persons_and_events()
+ super().tearDown()
+
+ @pytest.mark.asyncio
+ async def test_mixed_sources_total_events_correct(self) -> None:
+ response = await get_attribution_health(self.team, lookback_days=30)
+
+ assert response.total_events_with_utm == 3
+ assert response.total_distinct_utm_sources == 3
+ assert response.utm_source_catalogue_truncated is False
+
+
+class TestAttributionHealthCatalogueTruncatedClickhouse(ClickhouseTestMixin, BaseTest):
+ CLASS_DATA_LEVEL_SETUP = False
+
+ def setUp(self) -> None:
+ super().setUp()
+ for i in range(HOGQL_GROUP_LIMIT):
+ _pageview(self.team, f"u{i}", utm_source=f"unique_source_{i}")
+ _pageview(self.team, "u_extra", utm_source="overflow_source")
+ flush_persons_and_events()
+
+ def tearDown(self) -> None:
+ flush_persons_and_events()
+ super().tearDown()
+
+ @pytest.mark.asyncio
+ async def test_utm_source_catalogue_truncated_flag_when_limit_hit(self) -> None:
+ response = await get_attribution_health(self.team, lookback_days=30)
+
+ assert response.utm_source_catalogue_truncated is True
+
+
+class TestAttributionHealthSourceTypeFilterClickhouse(ClickhouseTestMixin, BaseTest):
+ CLASS_DATA_LEVEL_SETUP = False
+
+ def setUp(self) -> None:
+ super().setUp()
+ _pageview(self.team, "u1", utm_source="google")
+ _pageview(self.team, "u2", utm_source="facebook")
+ flush_persons_and_events()
+
+ def tearDown(self) -> None:
+ flush_persons_and_events()
+ super().tearDown()
+
+ @pytest.mark.asyncio
+ async def test_source_type_filter_limits_integration_output(self) -> None:
+ response = await get_attribution_health(self.team, lookback_days=30, source_type="GoogleAds")
+
+ assert len(response.integrations) == 1
+ assert response.integrations[0].integration_key == "google_ads"
+ assert response.total_events_with_utm == 2
+ assert response.total_events_matched_to_any_integration == 2
diff --git a/products/marketing_analytics/backend/services/test_conversion_goals_inspector.py b/products/marketing_analytics/backend/services/test_conversion_goals_inspector.py
new file mode 100644
index 000000000000..67adde5241ee
--- /dev/null
+++ b/products/marketing_analytics/backend/services/test_conversion_goals_inspector.py
@@ -0,0 +1,654 @@
+from datetime import UTC, datetime, timedelta
+
+import pytest
+from posthog.test.base import APIBaseTest, BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
+from unittest.mock import AsyncMock, MagicMock, patch
+
+from django.utils import timezone
+
+from posthog.schema import DateRange
+
+from products.actions.backend.models.action import Action
+from products.marketing_analytics.backend.services.conversion_goals_inspector import (
+ explain_conversion_goal,
+ list_conversion_goals,
+)
+
+
+def _events_goal(goal_id: str = "purchase", event: str | None = "purchase"):
+ return {
+ "conversion_goal_id": goal_id,
+ "conversion_goal_name": goal_id,
+ "kind": "EventsNode",
+ "event": event,
+ "schema_map": {},
+ }
+
+
+def _actions_goal(goal_id: str = "42"):
+ return {
+ "conversion_goal_id": goal_id,
+ "conversion_goal_name": "Sign up action",
+ "kind": "ActionsNode",
+ "schema_map": {},
+ }
+
+
+def _dw_goal(goal_id: str = "stripe_charges", table_name: str = "stripe.charges"):
+ return {
+ "conversion_goal_id": goal_id,
+ "conversion_goal_name": "Stripe charges",
+ "kind": "DataWarehouseNode",
+ "table_name": table_name,
+ "id_field": "id",
+ "distinct_id_field": "customer_email",
+ "timestamp_field": "created_at",
+ "schema_map": {},
+ }
+
+
+class _InspectorMixin(APIBaseTest):
+ """Shared setUp that patches all DB helpers used by list/explain conversion goals."""
+
+ def setUp(self):
+ super().setUp()
+ from products.marketing_analytics.backend.services.native_integrations import canonical_source_aliases
+
+ _targets = {
+ "config": "products.marketing_analytics.backend.services.conversion_goals_inspector._read_team_goal_config",
+ "alias_map": "products.marketing_analytics.backend.services.conversion_goals_inspector._build_team_alias_map",
+ "event_count": "products.marketing_analytics.backend.services.conversion_goals_inspector._count_event_goal",
+ "action_count": "products.marketing_analytics.backend.services.conversion_goals_inspector._count_action_goal",
+ "dw_count": "products.marketing_analytics.backend.services.conversion_goals_inspector._count_dw_goal",
+ "resolve_action": "products.marketing_analytics.backend.services.conversion_goals_inspector._resolve_action",
+ }
+ self.mocks: dict[str, AsyncMock] = {}
+ for key, target in _targets.items():
+ p = patch(target, new_callable=AsyncMock)
+ self.mocks[key] = p.start()
+ self.addCleanup(p.stop)
+
+ self.mocks["config"].return_value = ([], 90, "last_touch")
+ self.mocks["alias_map"].return_value = dict(canonical_source_aliases())
+ self.mocks["event_count"].return_value = (0, 0, 0, 0)
+ self.mocks["action_count"].return_value = (0, 0, 0, 0)
+ self.mocks["dw_count"].return_value = (0, None)
+ self.mocks["resolve_action"].return_value = (None, None)
+
+
+class TestListConversionGoals(_InspectorMixin):
+ @pytest.mark.asyncio
+ async def test_no_goals_returns_empty(self):
+ response = await list_conversion_goals(self.team)
+ assert response.goals == []
+ assert response.has_misconfigured is False
+ assert response.attribution_window_days == 90
+
+ @pytest.mark.asyncio
+ async def test_events_node_goal_summarized_with_split(self):
+ self.mocks["config"].return_value = ([_events_goal("purchase")], 60, "first_touch")
+ # 200 total: 80 integrated, 70 events without utm_source, 50 with unmatched utm_source
+ self.mocks["event_count"].return_value = (200, 80, 70, 50)
+
+ response = await list_conversion_goals(self.team)
+
+ assert response.attribution_window_days == 60
+ assert response.attribution_mode == "first_touch"
+ assert len(response.goals) == 1
+ goal = response.goals[0]
+ assert goal.id == "purchase"
+ assert goal.kind == "EventsNode"
+ assert goal.target_label == "purchase"
+ assert goal.last_30d_count == 200
+ assert goal.integrated_count == 80
+ assert goal.events_without_utm_source == 70
+ assert goal.events_with_unmatched_utm_source == 50
+ assert goal.non_integrated_count == 120
+ assert goal.integrated_pct == 40.0
+ assert goal.is_misconfigured is False
+
+ @pytest.mark.asyncio
+ async def test_events_node_with_null_event_uses_all_events_label(self):
+ self.mocks["config"].return_value = ([_events_goal("any", event=None)], 90, "last_touch")
+ self.mocks["event_count"].return_value = (10, 0, 10, 0)
+
+ response = await list_conversion_goals(self.team)
+ assert response.goals[0].target_label == "(all events)"
+ assert response.goals[0].events_without_utm_source == 10
+ assert response.goals[0].events_with_unmatched_utm_source == 0
+
+ @pytest.mark.asyncio
+ async def test_actions_node_with_missing_action_marks_misconfigured(self):
+ self.mocks["config"].return_value = ([_actions_goal("999")], 90, "last_touch")
+ self.mocks["resolve_action"].return_value = (None, "Action 999 does not exist or is deleted")
+
+ response = await list_conversion_goals(self.team)
+ assert response.has_misconfigured is True
+ assert response.goals[0].is_misconfigured is True
+ assert "999" in (response.goals[0].misconfig_reason or "")
+
+ @pytest.mark.asyncio
+ async def test_actions_node_with_resolved_action_uses_action_name(self):
+ action_mock = MagicMock()
+ action_mock.name = "Sign up"
+ self.mocks["config"].return_value = ([_actions_goal("42")], 90, "last_touch")
+ self.mocks["resolve_action"].return_value = (action_mock, None)
+ # 50 total: 30 integrated, 12 without utm_source, 8 with unmatched utm_source.
+ self.mocks["action_count"].return_value = (50, 30, 12, 8)
+
+ response = await list_conversion_goals(self.team)
+ goal = response.goals[0]
+ assert goal.kind == "ActionsNode"
+ assert goal.target_label == "Action: Sign up"
+ assert goal.last_30d_count == 50
+ assert goal.integrated_count == 30
+ assert goal.events_without_utm_source == 12
+ assert goal.events_with_unmatched_utm_source == 8
+ assert goal.non_integrated_count == 20
+ assert goal.is_misconfigured is False
+
+ @pytest.mark.asyncio
+ async def test_data_warehouse_node_returns_count_without_split(self):
+ self.mocks["config"].return_value = ([_dw_goal()], 90, "last_touch")
+ self.mocks["dw_count"].return_value = (1500, None)
+
+ response = await list_conversion_goals(self.team)
+ goal = response.goals[0]
+ assert goal.kind == "DataWarehouseNode"
+ assert goal.target_label == "stripe.charges"
+ assert goal.last_30d_count == 1500
+ assert goal.integrated_count is None
+ assert goal.events_without_utm_source is None
+ assert goal.events_with_unmatched_utm_source is None
+ assert goal.non_integrated_count is None
+ assert goal.integrated_pct is None
+ assert goal.is_misconfigured is False
+
+ @pytest.mark.asyncio
+ async def test_data_warehouse_node_with_query_error_marks_misconfigured(self):
+ self.mocks["config"].return_value = ([_dw_goal()], 90, "last_touch")
+ self.mocks["dw_count"].return_value = (0, "DW table or column not queryable: relation does not exist")
+
+ response = await list_conversion_goals(self.team)
+ assert response.goals[0].is_misconfigured is True
+ assert "not queryable" in (response.goals[0].misconfig_reason or "")
+
+ @pytest.mark.asyncio
+ async def test_unknown_kind_marks_misconfigured(self):
+ self.mocks["config"].return_value = (
+ [{"conversion_goal_id": "x", "conversion_goal_name": "x", "kind": "UnknownKind", "schema_map": {}}],
+ 90,
+ "last_touch",
+ )
+
+ response = await list_conversion_goals(self.team)
+ assert response.goals[0].is_misconfigured is True
+ assert "UnknownKind" in (response.goals[0].misconfig_reason or "")
+
+
+class TestExplainConversionGoal(_InspectorMixin):
+ @pytest.mark.asyncio
+ async def test_unknown_goal_id_raises(self):
+ with pytest.raises(ValueError, match="not found"):
+ await explain_conversion_goal(self.team, "nonexistent")
+
+ @pytest.mark.asyncio
+ async def test_data_warehouse_goal_short_circuits_with_note(self):
+ self.mocks["config"].return_value = ([_dw_goal()], 90, "last_touch")
+
+ explanation = await explain_conversion_goal(self.team, "stripe_charges")
+
+ assert explanation.kind == "DataWarehouseNode"
+ assert explanation.total_count == 0
+ assert explanation.samples == []
+ assert any("DataWarehouseNode" in n for n in explanation.notes)
+
+ @pytest.mark.asyncio
+ async def test_events_goal_aggregates_breakdowns_and_classifies_integrated(self):
+ self.mocks["config"].return_value = ([_events_goal("purchase")], 90, "last_touch")
+
+ ts1 = datetime(2026, 4, 1, tzinfo=UTC)
+ ts2 = datetime(2026, 4, 2, tzinfo=UTC)
+ rows = [
+ ("uuid-1", ts1, "user-a", "purchase", "facebook", "spring_sale"),
+ ("uuid-2", ts1, "user-b", "purchase", "google", "spring_sale"),
+ ("uuid-3", ts2, "user-c", "purchase", None, None),
+ ("uuid-4", ts2, "user-d", "purchase", "twitter", "tweet_drive"), # no alias hit
+ ]
+ with patch(
+ "products.marketing_analytics.backend.services.conversion_goals_inspector._query_goal_events",
+ new=AsyncMock(return_value=rows),
+ ):
+ explanation = await explain_conversion_goal(
+ self.team,
+ "purchase",
+ period=DateRange(date_from="2026-04-01T00:00:00+00:00", date_to="2026-04-03T00:00:00+00:00"),
+ )
+
+ assert explanation.total_count == 4
+ assert explanation.integrated_count == 2
+ # 1 row had utm_source=None (without_utm), 1 row had utm_source='twitter' (unmatched_with_utm)
+ assert explanation.events_without_utm_source == 1
+ assert explanation.events_with_unmatched_utm_source == 1
+ assert explanation.non_integrated_count == 2
+ assert dict(explanation.by_event) == {"purchase": 4}
+
+ utm_dict = dict(explanation.by_utm_source)
+ assert utm_dict.get("facebook") == 1
+ assert utm_dict.get("google") == 1
+ assert utm_dict.get("twitter") == 1
+
+ integration_dict = dict(explanation.by_matched_integration)
+ assert integration_dict.get("meta_ads") == 1
+ assert integration_dict.get("google_ads") == 1
+ assert "twitter" not in integration_dict
+
+ assert len(explanation.samples) == 4
+
+ @pytest.mark.asyncio
+ async def test_events_goal_caps_samples(self):
+ self.mocks["config"].return_value = ([_events_goal("purchase")], 90, "last_touch")
+ rows = [(f"uuid-{i}", datetime(2026, 4, 1, tzinfo=UTC), f"u-{i}", "purchase", "google", "c") for i in range(50)]
+ with patch(
+ "products.marketing_analytics.backend.services.conversion_goals_inspector._query_goal_events",
+ new=AsyncMock(return_value=rows),
+ ):
+ explanation = await explain_conversion_goal(self.team, "purchase")
+
+ assert explanation.total_count == 50
+ assert len(explanation.samples) == 10 # EXPLAIN_SAMPLE_LIMIT
+
+
+class TestResolveAction(APIBaseTest):
+ @pytest.mark.asyncio
+ async def test_filters_by_team_id(self):
+ from asgiref.sync import sync_to_async
+
+ from posthog.models import Organization, Team
+
+ from products.marketing_analytics.backend.services.conversion_goals_inspector import _resolve_action
+
+ # Create a second team in a separate organization to ensure cross-team isolation.
+ other_org = await sync_to_async(Organization.objects.create)(name="Other Org")
+ other_team = await sync_to_async(Team.objects.create)(organization=other_org, name="Other Team")
+ other_action = await sync_to_async(Action.objects.create)(team=other_team, name="Other Team Action")
+
+ # _resolve_action scoped to self.team must NOT return an action that belongs
+ # to other_team — otherwise team A could read team B's action name and step
+ # events through the diagnostic tool.
+ action, error = await _resolve_action(self.team, str(other_action.pk))
+ assert action is None
+ assert error is not None
+
+ @pytest.mark.asyncio
+ async def test_invalid_goal_id_returns_error_without_query(self):
+ from products.marketing_analytics.backend.services.conversion_goals_inspector import _resolve_action
+
+ with patch(
+ "products.marketing_analytics.backend.services.conversion_goals_inspector.Action.objects.get",
+ ) as p_get:
+ action, error = await _resolve_action(self.team, "not-an-int")
+ assert action is None
+ assert error is not None
+ p_get.assert_not_called()
+
+
+class TestCountDwGoalSafety:
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "table_name,timestamp_field",
+ [
+ ("stripe.charges", "created_at; DROP TABLE foo"),
+ ("stripe; DROP TABLE foo", "created_at"),
+ ("stripe.charges", "created_at OR 1=1"),
+ ("'; SELECT 1 --", "created_at"),
+ ("stripe..charges", "created_at"),
+ ],
+ )
+ async def test_rejects_invalid_identifiers_without_executing(self, table_name, timestamp_field):
+ from products.marketing_analytics.backend.services.conversion_goals_inspector import _count_dw_goal
+
+ team = MagicMock()
+ goal = {"table_name": table_name, "timestamp_field": timestamp_field}
+ with patch(
+ "products.marketing_analytics.backend.services.conversion_goals_inspector.execute_hogql_query",
+ ) as p_exec:
+ count, reason = await _count_dw_goal(team, goal)
+ assert count == 0
+ assert reason is not None
+ p_exec.assert_not_called()
+
+
+def _make_events_goal(goal_id: str, event: str | None) -> dict:
+ return {
+ "id": goal_id,
+ "name": goal_id,
+ "conversion_goal_id": goal_id,
+ "conversion_goal_name": goal_id,
+ "kind": "EventsNode",
+ "event": event,
+ "schema_map": {},
+ }
+
+
+class TestExplainGoalBasicCountClickhouse(ClickhouseTestMixin, BaseTest):
+ CLASS_DATA_LEVEL_SETUP = False
+
+ def setUp(self) -> None:
+ super().setUp()
+ self.team.marketing_analytics_config.conversion_goals = [_make_events_goal("purchase", "purchase")]
+ self.team.marketing_analytics_config.save()
+ for i in range(5):
+ _create_event(
+ distinct_id=f"user_{i}",
+ event="purchase",
+ team=self.team,
+ properties={"utm_source": "google", "utm_campaign": "spring"},
+ timestamp=timezone.now() - timedelta(hours=1),
+ )
+ flush_persons_and_events()
+
+ def tearDown(self) -> None:
+ flush_persons_and_events()
+ super().tearDown()
+
+ @pytest.mark.asyncio
+ async def test_explain_events_goal_counts_seeded_events(self) -> None:
+ explanation = await explain_conversion_goal(self.team, "purchase")
+
+ assert explanation.total_count == 5
+ assert explanation.kind == "EventsNode"
+
+
+class TestExplainGoalUtmSplitClickhouse(ClickhouseTestMixin, BaseTest):
+ CLASS_DATA_LEVEL_SETUP = False
+
+ def setUp(self) -> None:
+ super().setUp()
+ self.team.marketing_analytics_config.conversion_goals = [_make_events_goal("purchase", "purchase")]
+ self.team.marketing_analytics_config.save()
+ for i in range(3):
+ _create_event(
+ distinct_id=f"google_user_{i}",
+ event="purchase",
+ team=self.team,
+ properties={"utm_source": "google"},
+ timestamp=timezone.now() - timedelta(hours=1),
+ )
+ for i in range(2):
+ _create_event(
+ distinct_id=f"fb_user_{i}",
+ event="purchase",
+ team=self.team,
+ properties={"utm_source": "facebook"},
+ timestamp=timezone.now() - timedelta(hours=1),
+ )
+ _create_event(
+ distinct_id="no_utm_user",
+ event="purchase",
+ team=self.team,
+ properties={},
+ timestamp=timezone.now() - timedelta(hours=1),
+ )
+ flush_persons_and_events()
+
+ def tearDown(self) -> None:
+ flush_persons_and_events()
+ super().tearDown()
+
+ @pytest.mark.asyncio
+ async def test_explain_events_goal_splits_by_utm_source(self) -> None:
+ explanation = await explain_conversion_goal(self.team, "purchase")
+
+ assert explanation.total_count == 6
+ assert explanation.integrated_count == 5
+ assert explanation.events_without_utm_source == 1
+ assert explanation.events_with_unmatched_utm_source == 0
+
+ utm_dict = dict(explanation.by_utm_source)
+ assert utm_dict.get("google") == 3
+ assert utm_dict.get("facebook") == 2
+
+ integration_dict = dict(explanation.by_matched_integration)
+ assert integration_dict.get("google_ads") == 3
+ assert integration_dict.get("meta_ads") == 2
+
+ @pytest.mark.asyncio
+ async def test_explain_events_goal_by_event_breakdown(self) -> None:
+ explanation = await explain_conversion_goal(self.team, "purchase")
+
+ by_event = dict(explanation.by_event)
+ assert by_event.get("purchase") == 6
+
+
+class TestExplainGoalUnmatchedUtmClickhouse(ClickhouseTestMixin, BaseTest):
+ CLASS_DATA_LEVEL_SETUP = False
+
+ def setUp(self) -> None:
+ super().setUp()
+ self.team.marketing_analytics_config.conversion_goals = [_make_events_goal("purchase", "purchase")]
+ self.team.marketing_analytics_config.save()
+ _create_event(
+ distinct_id="user_a",
+ event="purchase",
+ team=self.team,
+ properties={"utm_source": "some_unknown_source"},
+ timestamp=timezone.now() - timedelta(hours=1),
+ )
+ _create_event(
+ distinct_id="user_b",
+ event="purchase",
+ team=self.team,
+ properties={},
+ timestamp=timezone.now() - timedelta(hours=1),
+ )
+ flush_persons_and_events()
+
+ def tearDown(self) -> None:
+ flush_persons_and_events()
+ super().tearDown()
+
+ @pytest.mark.asyncio
+ async def test_explain_events_goal_unmatched_utm_counted_separately(self) -> None:
+ explanation = await explain_conversion_goal(self.team, "purchase")
+
+ assert explanation.total_count == 2
+ assert explanation.integrated_count == 0
+ assert explanation.events_with_unmatched_utm_source == 1
+ assert explanation.events_without_utm_source == 1
+ assert explanation.non_integrated_count == 2
+
+
+class TestExplainGoalSampleCapClickhouse(ClickhouseTestMixin, BaseTest):
+ CLASS_DATA_LEVEL_SETUP = False
+
+ def setUp(self) -> None:
+ super().setUp()
+ self.team.marketing_analytics_config.conversion_goals = [_make_events_goal("purchase", "purchase")]
+ self.team.marketing_analytics_config.save()
+ for i in range(20):
+ _create_event(
+ distinct_id=f"user_{i}",
+ event="purchase",
+ team=self.team,
+ properties={"utm_source": "google"},
+ timestamp=timezone.now() - timedelta(hours=1),
+ )
+ flush_persons_and_events()
+
+ def tearDown(self) -> None:
+ flush_persons_and_events()
+ super().tearDown()
+
+ @pytest.mark.asyncio
+ async def test_explain_samples_capped_at_limit(self) -> None:
+ explanation = await explain_conversion_goal(self.team, "purchase")
+
+ assert explanation.total_count == 20
+ assert len(explanation.samples) == 10
+
+
+class TestListGoalCountsClickhouse(ClickhouseTestMixin, BaseTest):
+ CLASS_DATA_LEVEL_SETUP = False
+
+ def setUp(self) -> None:
+ super().setUp()
+ self.team.marketing_analytics_config.conversion_goals = [_make_events_goal("signup", "signup")]
+ self.team.marketing_analytics_config.save()
+ for i in range(3):
+ _create_event(
+ distinct_id=f"user_{i}",
+ event="signup",
+ team=self.team,
+ properties={"utm_source": "google"},
+ timestamp=timezone.now() - timedelta(hours=1),
+ )
+ flush_persons_and_events()
+
+ def tearDown(self) -> None:
+ flush_persons_and_events()
+ super().tearDown()
+
+ @pytest.mark.asyncio
+ async def test_list_events_goal_counts_last_30d(self) -> None:
+ response = await list_conversion_goals(self.team)
+
+ assert len(response.goals) == 1
+ goal = response.goals[0]
+ assert goal.id == "signup"
+ assert goal.kind == "EventsNode"
+ assert goal.last_30d_count == 3
+ assert goal.integrated_count == 3
+ assert goal.events_without_utm_source == 0
+ assert goal.is_misconfigured is False
+
+
+class TestListGoalIntegratedSplitClickhouse(ClickhouseTestMixin, BaseTest):
+ CLASS_DATA_LEVEL_SETUP = False
+
+ def setUp(self) -> None:
+ super().setUp()
+ self.team.marketing_analytics_config.conversion_goals = [_make_events_goal("purchase", "purchase")]
+ self.team.marketing_analytics_config.save()
+ _create_event(
+ distinct_id="u1",
+ event="purchase",
+ team=self.team,
+ properties={"utm_source": "google"},
+ timestamp=timezone.now() - timedelta(hours=1),
+ )
+ _create_event(
+ distinct_id="u2",
+ event="purchase",
+ team=self.team,
+ properties={"utm_source": "facebook"},
+ timestamp=timezone.now() - timedelta(hours=1),
+ )
+ _create_event(
+ distinct_id="u3",
+ event="purchase",
+ team=self.team,
+ properties={},
+ timestamp=timezone.now() - timedelta(hours=1),
+ )
+ flush_persons_and_events()
+
+ def tearDown(self) -> None:
+ flush_persons_and_events()
+ super().tearDown()
+
+ @pytest.mark.asyncio
+ async def test_list_events_goal_integrated_split_correct(self) -> None:
+ response = await list_conversion_goals(self.team)
+
+ goal = response.goals[0]
+ assert goal.last_30d_count == 3
+ assert goal.integrated_count == 2
+ assert goal.events_without_utm_source == 1
+ assert goal.events_with_unmatched_utm_source == 0
+ assert goal.non_integrated_count == 1
+ assert goal.integrated_pct == pytest.approx(66.67, abs=0.1)
+
+
+class TestListGoalNoGoalsClickhouse(ClickhouseTestMixin, BaseTest):
+ CLASS_DATA_LEVEL_SETUP = False
+
+ def setUp(self) -> None:
+ super().setUp()
+ self.team.marketing_analytics_config.conversion_goals = []
+ self.team.marketing_analytics_config.save()
+ flush_persons_and_events()
+
+ def tearDown(self) -> None:
+ flush_persons_and_events()
+ super().tearDown()
+
+ @pytest.mark.asyncio
+ async def test_list_no_goals_returns_empty(self) -> None:
+ response = await list_conversion_goals(self.team)
+
+ assert response.goals == []
+
+
+# ActionsNode goals match the action's full definition (event + property/URL filters),
+# not just its step events — otherwise filtered actions overcount.
+class TestListActionGoalFiltersClickhouse(ClickhouseTestMixin, BaseTest):
+ CLASS_DATA_LEVEL_SETUP = False
+
+ def setUp(self) -> None:
+ super().setUp()
+ self.action = Action.objects.create(
+ team=self.team,
+ name="Pro purchase",
+ steps_json=[
+ {
+ "event": "purchase",
+ "properties": [{"key": "plan", "value": "pro", "operator": "exact", "type": "event"}],
+ }
+ ],
+ )
+ self.team.marketing_analytics_config.conversion_goals = [
+ {
+ "id": str(self.action.id),
+ "name": "Pro purchase",
+ "conversion_goal_id": str(self.action.id),
+ "conversion_goal_name": "Pro purchase",
+ "kind": "ActionsNode",
+ "schema_map": {},
+ }
+ ]
+ self.team.marketing_analytics_config.save()
+ # Two `purchase` events match (plan=pro); the `plan=free` one is excluded by
+ # the action's property filter. Step-event-only matching would count all three.
+ for distinct_id in ("u1", "u2"):
+ _create_event(
+ distinct_id=distinct_id,
+ event="purchase",
+ team=self.team,
+ properties={"plan": "pro", "utm_source": "google"},
+ timestamp=timezone.now() - timedelta(hours=1),
+ )
+ _create_event(
+ distinct_id="u3",
+ event="purchase",
+ team=self.team,
+ properties={"plan": "free", "utm_source": "google"},
+ timestamp=timezone.now() - timedelta(hours=1),
+ )
+ flush_persons_and_events()
+
+ def tearDown(self) -> None:
+ flush_persons_and_events()
+ super().tearDown()
+
+ @pytest.mark.asyncio
+ async def test_list_action_goal_respects_property_filter(self) -> None:
+ response = await list_conversion_goals(self.team)
+
+ goal = response.goals[0]
+ assert goal.kind == "ActionsNode"
+ assert goal.is_misconfigured is False
+ # 2, not 3 — the `plan=free` purchase is excluded by the action filter.
+ assert goal.last_30d_count == 2
+ assert goal.integrated_count == 2
+ assert response.has_misconfigured is False
diff --git a/products/marketing_analytics/backend/services/test_data_source_health.py b/products/marketing_analytics/backend/services/test_data_source_health.py
new file mode 100644
index 000000000000..889ad8b73bf6
--- /dev/null
+++ b/products/marketing_analytics/backend/services/test_data_source_health.py
@@ -0,0 +1,245 @@
+from datetime import timedelta
+from typing import Any
+
+import pytest
+from freezegun import freeze_time
+from posthog.test.base import APIBaseTest
+from unittest.mock import AsyncMock, patch
+
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from products.marketing_analytics.backend.services.data_source_health import (
+ STALE_THRESHOLD,
+ DataSourceHealthEntry,
+ _build_issues_summary,
+ _compute_overall_status,
+ _resolve_sync_status,
+ get_data_source_health,
+)
+
+
+@freeze_time("2025-06-15")
+class TestResolveSyncStatus:
+ @parameterized.expand(
+ [
+ ("never_synced_returns_never", None, None, "never"),
+ ("recent_completed_returns_ok", timedelta(minutes=10), None, "ok"),
+ ("old_completed_returns_stale", STALE_THRESHOLD + timedelta(minutes=1), None, "stale"),
+ ("error_text_takes_priority_over_completed", timedelta(minutes=10), "boom", "error"),
+ ]
+ )
+ def test_resolve_sync_status(self, _name, age, last_error_text, expected):
+ last_completed_at = None if age is None else timezone.now() - age
+ assert (
+ _resolve_sync_status(
+ last_completed_at=last_completed_at, last_error_text=last_error_text, required_tables=[]
+ )
+ == expected
+ )
+
+
+def _entry(**kwargs: Any) -> DataSourceHealthEntry:
+ defaults: dict[str, Any] = {
+ "source_type": "GoogleAds",
+ "is_native": True,
+ "display_name": "Google Ads",
+ "connected": True,
+ "last_sync_at": None,
+ "last_sync_status": "ok",
+ "last_error": None,
+ "rows_last_24h": 0,
+ "rows_last_7d": 0,
+ "sources_map_present": True,
+ "schema_columns_mapped": ["campaign", "source", "cost", "date"],
+ "schema_columns_required_missing": [],
+ "required_tables": [],
+ "settings_url": "/settings/environment-marketing-analytics#marketing-settings",
+ "schemas_url": None,
+ "diagnosis": "ok",
+ "fix_suggestion": None,
+ }
+ defaults.update(kwargs)
+ return DataSourceHealthEntry(**defaults)
+
+
+def _entries_for_status_test(case_name: str) -> list[DataSourceHealthEntry]:
+ if case_name == "no_connected":
+ return [_entry(connected=False, last_sync_status="not_connected")]
+ if case_name == "all_ok":
+ return [_entry(), _entry(source_type="MetaAds", display_name="Meta Ads")]
+ if case_name == "all_errored":
+ return [_entry(last_sync_status="error", last_error="x")]
+ if case_name == "mixed":
+ return [_entry(), _entry(source_type="MetaAds", last_sync_status="error")]
+ if case_name == "required_missing":
+ return [_entry(schema_columns_required_missing=["campaign"])]
+ raise ValueError(f"unknown case: {case_name}")
+
+
+class TestComputeOverallStatus:
+ @parameterized.expand(
+ [
+ ("no_connected_sources_is_no_sources", "no_connected", "no_sources"),
+ ("all_connected_and_ok_is_healthy", "all_ok", "healthy"),
+ ("all_errored_is_broken", "all_errored", "broken"),
+ ("mixed_is_degraded", "mixed", "degraded"),
+ ("required_missing_is_degraded", "required_missing", "degraded"),
+ ]
+ )
+ def test_compute_overall_status(self, _name, case_name, expected):
+ entries = _entries_for_status_test(case_name)
+ assert _compute_overall_status(entries) == expected
+
+
+class TestBuildIssuesSummary:
+ @parameterized.expand(
+ [
+ (
+ "only_lists_problematic_entries",
+ [
+ _entry(last_sync_status="ok", schema_columns_required_missing=[]),
+ _entry(
+ source_type="MetaAds",
+ display_name="Meta Ads",
+ last_sync_status="error",
+ last_error="rate limit",
+ diagnosis="Meta Ads last sync failed.",
+ ),
+ ],
+ 1,
+ "Meta Ads",
+ ),
+ (
+ "schema_missing_surfaces_in_summary_even_if_sync_ok",
+ [
+ _entry(
+ source_type="MetaAds",
+ display_name="Meta Ads",
+ last_sync_status="ok",
+ schema_columns_required_missing=["cost"],
+ diagnosis="Meta Ads is syncing but required schema columns are not mapped.",
+ ),
+ ],
+ 1,
+ "Meta Ads",
+ ),
+ ]
+ )
+ def test_build_issues_summary(
+ self,
+ _name: str,
+ entries: list[DataSourceHealthEntry],
+ expected_count: int,
+ expected_substring: str,
+ ) -> None:
+ summary = _build_issues_summary(entries)
+ assert len(summary) == expected_count
+ assert expected_substring in summary[0]
+
+
+class _FakeSource:
+ def __init__(self, source_id: str = "src-uuid-1", source_type: str = "GoogleAds"):
+ self.id = source_id
+ self.source_type = source_type
+
+
+@freeze_time("2025-06-15")
+class TestGetDataSourceHealthOrchestration(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ _TARGETS = {
+ "sources_map": "products.marketing_analytics.backend.services.data_source_health._get_sources_map",
+ "sources_by_type": "products.marketing_analytics.backend.services.data_source_health._get_sources_by_type",
+ "last_job_state": "products.marketing_analytics.backend.services.data_source_health._get_last_job_state",
+ "rows_synced": "products.marketing_analytics.backend.services.data_source_health._get_rows_synced",
+ "required_tables": "products.marketing_analytics.backend.services.data_source_health._get_required_tables_status",
+ }
+ patchers = {key: patch(target, new_callable=AsyncMock) for key, target in _TARGETS.items()}
+ self.mocks = {key: p.start() for key, p in patchers.items()}
+ for p in patchers.values():
+ self.addCleanup(p.stop)
+
+ # Defaults: empty config, no sources, never synced, no rows, no required tables.
+ self.mocks["sources_map"].return_value = {}
+ self.mocks["sources_by_type"].return_value = {}
+ self.mocks["last_job_state"].return_value = (None, None)
+ self.mocks["rows_synced"].return_value = (0, 0)
+ self.mocks["required_tables"].return_value = []
+
+ @pytest.mark.asyncio
+ async def test_no_sources_returns_no_sources_status(self):
+ response = await get_data_source_health(self.team)
+ assert response.overall_status == "no_sources"
+ assert response.has_any_data is False
+ assert all(e.connected is False for e in response.integrations)
+ assert all(e.last_sync_status == "not_connected" for e in response.integrations)
+
+ @pytest.mark.asyncio
+ async def test_native_source_with_recent_sync_is_ok(self):
+ self.mocks["sources_by_type"].return_value = {"GoogleAds": _FakeSource()}
+ self.mocks["last_job_state"].return_value = (timezone.now() - timedelta(minutes=15), None)
+ self.mocks["rows_synced"].return_value = (500, 500)
+ self.mocks["sources_map"].return_value = {
+ "src-uuid-1": {"campaign": "name", "source": "src", "cost": "spend", "date": "day"}
+ }
+
+ response = await get_data_source_health(self.team)
+
+ google = next(e for e in response.integrations if e.source_type == "GoogleAds")
+ assert google.connected is True
+ assert google.last_sync_status == "ok"
+ assert google.rows_last_24h == 500
+ assert google.schema_columns_required_missing == []
+ assert response.has_any_data is True
+
+ @pytest.mark.asyncio
+ async def test_failed_job_text_surfaces_as_error_status(self):
+ self.mocks["sources_by_type"].return_value = {"BingAds": _FakeSource(source_type="BingAds")}
+ self.mocks["last_job_state"].return_value = (None, "auth failed")
+
+ response = await get_data_source_health(self.team, source_type="BingAds")
+
+ assert len(response.integrations) == 1
+ assert response.integrations[0].last_sync_status == "error"
+ assert response.integrations[0].last_error == "auth failed"
+
+ @pytest.mark.asyncio
+ async def test_stale_completed_is_marked_stale(self):
+ self.mocks["sources_by_type"].return_value = {"MetaAds": _FakeSource(source_type="MetaAds")}
+ self.mocks["last_job_state"].return_value = (timezone.now() - STALE_THRESHOLD - timedelta(hours=1), None)
+
+ response = await get_data_source_health(self.team, source_type="MetaAds")
+
+ assert response.integrations[0].last_sync_status == "stale"
+
+ @pytest.mark.asyncio
+ async def test_filter_by_source_type_returns_only_that_one(self):
+ self.mocks["sources_by_type"].return_value = {"GoogleAds": _FakeSource()}
+
+ response = await get_data_source_health(self.team, source_type="GoogleAds")
+
+ assert len(response.integrations) == 1
+ assert response.integrations[0].source_type == "GoogleAds"
+
+ @pytest.mark.asyncio
+ async def test_unknown_source_type_filter_returns_empty(self):
+ response = await get_data_source_health(self.team, source_type="DefinitelyNotASource")
+ assert response.integrations == []
+
+ @pytest.mark.asyncio
+ async def test_native_sources_never_report_missing_columns(self):
+ # Native sources (Google Ads, Meta, etc.) don't require column mapping —
+ # the column → field map is implicit in the platform's API. Only self-managed
+ # sources (BigQuery, S3) need explicit column mapping. So for a native source,
+ # `schema_columns_required_missing` must always be empty regardless of
+ # `sources_map` content.
+ self.mocks["sources_by_type"].return_value = {"GoogleAds": _FakeSource()}
+ self.mocks["last_job_state"].return_value = (timezone.now() - timedelta(minutes=5), None)
+ self.mocks["sources_map"].return_value = {"src-uuid-1": {"campaign": "name"}}
+
+ response = await get_data_source_health(self.team, source_type="GoogleAds")
+
+ entry = response.integrations[0]
+ assert entry.schema_columns_required_missing == []
diff --git a/products/marketing_analytics/backend/services/test_event_suggestions.py b/products/marketing_analytics/backend/services/test_event_suggestions.py
new file mode 100644
index 000000000000..a31bf36ea38a
--- /dev/null
+++ b/products/marketing_analytics/backend/services/test_event_suggestions.py
@@ -0,0 +1,361 @@
+from datetime import timedelta
+
+import pytest
+from posthog.test.base import APIBaseTest, BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
+from unittest.mock import AsyncMock, patch
+
+from django.utils import timezone
+
+from products.marketing_analytics.backend.services.event_suggestions import (
+ DEFAULT_EXCLUDED_EVENTS,
+ _build_reason,
+ _compute_score,
+ suggest_conversion_goals,
+)
+
+
+class TestComputeScore:
+ def test_high_volume_high_utm_not_goal_scores_near_one(self):
+ score = _compute_score(count=1000, max_volume=1000, pct_utm_source=100, is_already_a_goal=False)
+ assert 0.99 <= score <= 1.0
+
+ def test_already_a_goal_loses_score_bonus(self):
+ not_goal = _compute_score(count=500, max_volume=1000, pct_utm_source=80, is_already_a_goal=False)
+ already = _compute_score(count=500, max_volume=1000, pct_utm_source=80, is_already_a_goal=True)
+ assert not_goal > already
+
+ def test_zero_volume_safe(self):
+ score = _compute_score(count=0, max_volume=0, pct_utm_source=0, is_already_a_goal=False)
+ assert 0 <= score <= 1
+
+
+class TestBuildReason:
+ def test_high_volume_phrasing(self):
+ reason = _build_reason(count=5000, pct_utm_source=80, is_already_a_goal=False)
+ assert "high volume" in reason
+ assert "5,000" in reason
+ assert "strong UTM" in reason
+ assert "not yet a goal" in reason
+
+ def test_low_utm_phrasing(self):
+ reason = _build_reason(count=200, pct_utm_source=5, is_already_a_goal=False)
+ assert "low UTM coverage" in reason
+
+ def test_already_goal_marked(self):
+ reason = _build_reason(count=200, pct_utm_source=50, is_already_a_goal=True)
+ assert "already configured as a goal" in reason
+
+
+class TestSuggestConversionGoals(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ fetch_patcher = patch(
+ "products.marketing_analytics.backend.services.event_suggestions._fetch_candidate_rows",
+ new_callable=AsyncMock,
+ )
+ goals_patcher = patch(
+ "products.marketing_analytics.backend.services.event_suggestions._read_existing_goal_event_names",
+ new_callable=AsyncMock,
+ )
+ self.mock_fetch = fetch_patcher.start()
+ self.mock_goals = goals_patcher.start()
+ self.addCleanup(fetch_patcher.stop)
+ self.addCleanup(goals_patcher.stop)
+
+ self.mock_fetch.return_value = []
+ self.mock_goals.return_value = set()
+
+ @pytest.mark.asyncio
+ async def test_no_events_returns_empty(self):
+ response = await suggest_conversion_goals(self.team)
+ assert response.candidates == []
+
+ @pytest.mark.asyncio
+ async def test_excludes_default_system_events(self):
+ self.mock_fetch.return_value = [
+ {
+ "event_name": "$pageview",
+ "count": 10000,
+ "users": 500,
+ "with_utm_source": 8000,
+ "with_utm_campaign": 5000,
+ "top_utm_sources": [],
+ },
+ {
+ "event_name": "purchase",
+ "count": 1000,
+ "users": 100,
+ "with_utm_source": 800,
+ "with_utm_campaign": 600,
+ "top_utm_sources": [],
+ },
+ ]
+ response = await suggest_conversion_goals(self.team)
+ assert len(response.candidates) == 1
+ assert response.candidates[0].event_name == "purchase"
+
+ @pytest.mark.asyncio
+ async def test_disabling_exclusion_includes_autocapture(self):
+ self.mock_fetch.return_value = [
+ {
+ "event_name": "$autocapture",
+ "count": 10000,
+ "users": 500,
+ "with_utm_source": 0,
+ "with_utm_campaign": 0,
+ "top_utm_sources": [],
+ },
+ ]
+ response = await suggest_conversion_goals(self.team, exclude_autocapture=False)
+ assert len(response.candidates) == 1
+ assert response.candidates[0].event_name == "$autocapture"
+
+ @pytest.mark.asyncio
+ async def test_already_a_goal_flag_set(self):
+ self.mock_fetch.return_value = [
+ {
+ "event_name": "purchase",
+ "count": 1000,
+ "users": 100,
+ "with_utm_source": 700,
+ "with_utm_campaign": 500,
+ "top_utm_sources": [],
+ },
+ {
+ "event_name": "signup",
+ "count": 500,
+ "users": 80,
+ "with_utm_source": 250,
+ "with_utm_campaign": 100,
+ "top_utm_sources": [],
+ },
+ ]
+ self.mock_goals.return_value = {"purchase"}
+ response = await suggest_conversion_goals(self.team)
+ purchase = next(c for c in response.candidates if c.event_name == "purchase")
+ signup = next(c for c in response.candidates if c.event_name == "signup")
+ assert purchase.is_already_a_goal is True
+ assert signup.is_already_a_goal is False
+ # The not-a-goal bonus is surfaced in the reason text for each candidate.
+ assert "already configured as a goal" in purchase.suggestion_reason
+ assert "not yet a goal" in signup.suggestion_reason
+
+ @pytest.mark.asyncio
+ async def test_top_n_caps_results(self):
+ self.mock_fetch.return_value = [
+ {
+ "event_name": f"event_{i}",
+ "count": 1000 - i,
+ "users": 50,
+ "with_utm_source": 500,
+ "with_utm_campaign": 200,
+ "top_utm_sources": [],
+ }
+ for i in range(20)
+ ]
+ response = await suggest_conversion_goals(self.team, top_n=5)
+ assert len(response.candidates) == 5
+
+ @pytest.mark.asyncio
+ async def test_candidates_sorted_by_score_descending(self):
+ self.mock_fetch.return_value = [
+ {
+ "event_name": "low_volume",
+ "count": 100,
+ "users": 20,
+ "with_utm_source": 80,
+ "with_utm_campaign": 60,
+ "top_utm_sources": [],
+ },
+ {
+ "event_name": "high_volume",
+ "count": 5000,
+ "users": 500,
+ "with_utm_source": 4500,
+ "with_utm_campaign": 3000,
+ "top_utm_sources": [],
+ },
+ {
+ "event_name": "no_utm",
+ "count": 3000,
+ "users": 300,
+ "with_utm_source": 0,
+ "with_utm_campaign": 0,
+ "top_utm_sources": [],
+ },
+ ]
+ response = await suggest_conversion_goals(self.team)
+ scores = [c.suggestion_score for c in response.candidates]
+ assert scores == sorted(scores, reverse=True)
+ assert response.candidates[0].event_name == "high_volume"
+
+ @pytest.mark.asyncio
+ async def test_pct_with_utm_clamped_to_count(self):
+ self.mock_fetch.return_value = [
+ {
+ "event_name": "purchase",
+ "count": 1000,
+ "users": 100,
+ "with_utm_source": 1000,
+ "with_utm_campaign": 500,
+ "top_utm_sources": [],
+ },
+ ]
+ response = await suggest_conversion_goals(self.team)
+ assert response.candidates[0].pct_with_utm_source == 100.0
+ assert response.candidates[0].pct_with_utm_campaign == 50.0
+
+ def test_default_excluded_events_includes_known_system_events(self):
+ assert "$pageview" in DEFAULT_EXCLUDED_EVENTS
+ assert "$autocapture" in DEFAULT_EXCLUDED_EVENTS
+ assert "$identify" in DEFAULT_EXCLUDED_EVENTS
+
+
+def _seed_n_events(
+ event_name: str,
+ team: object,
+ count: int,
+ utm_source: str | None = None,
+ utm_campaign: str | None = None,
+) -> None:
+ props: dict = {}
+ if utm_source is not None:
+ props["utm_source"] = utm_source
+ if utm_campaign is not None:
+ props["utm_campaign"] = utm_campaign
+ for i in range(count):
+ _create_event(
+ distinct_id=f"user_{event_name}_{i}",
+ event=event_name,
+ team=team,
+ properties=props,
+ timestamp=timezone.now() - timedelta(hours=1),
+ )
+
+
+class TestSuggestConversionGoalsClickhouseTopkAndCount(ClickhouseTestMixin, BaseTest):
+ CLASS_DATA_LEVEL_SETUP = False
+
+ def setUp(self) -> None:
+ super().setUp()
+ _seed_n_events("signup", self.team, count=100, utm_source="google", utm_campaign="spring")
+ _seed_n_events("purchase", self.team, count=100, utm_source="facebook")
+ flush_persons_and_events()
+
+ def tearDown(self) -> None:
+ flush_persons_and_events()
+ super().tearDown()
+
+ @pytest.mark.asyncio
+ async def test_topk_hogql_runs_and_custom_events_appear_as_candidates(self) -> None:
+ response = await suggest_conversion_goals(self.team, min_count=50, lookback_days=30)
+
+ event_names = [c.event_name for c in response.candidates]
+ assert "signup" in event_names
+ assert "purchase" in event_names
+
+ @pytest.mark.asyncio
+ async def test_top_utm_sources_populated_by_topk(self) -> None:
+ response = await suggest_conversion_goals(self.team, min_count=50, lookback_days=30)
+
+ signup = next((c for c in response.candidates if c.event_name == "signup"), None)
+ assert signup is not None
+ assert len(signup.top_utm_sources) >= 1
+ top_sources = [src for src, _ in signup.top_utm_sources]
+ assert "google" in top_sources
+
+
+class TestSuggestConversionGoalsClickhouseSorting(ClickhouseTestMixin, BaseTest):
+ CLASS_DATA_LEVEL_SETUP = False
+
+ def setUp(self) -> None:
+ super().setUp()
+ _seed_n_events("high_vol_with_utm", self.team, count=200, utm_source="google")
+ _seed_n_events("low_vol_no_utm", self.team, count=60)
+ flush_persons_and_events()
+
+ def tearDown(self) -> None:
+ flush_persons_and_events()
+ super().tearDown()
+
+ @pytest.mark.asyncio
+ async def test_candidates_sorted_by_score_descending_real_data(self) -> None:
+ response = await suggest_conversion_goals(self.team, min_count=50, lookback_days=30)
+
+ scores = [c.suggestion_score for c in response.candidates]
+ assert scores == sorted(scores, reverse=True)
+ assert response.candidates[0].event_name == "high_vol_with_utm"
+
+
+class TestSuggestConversionGoalsClickhouseFiltering(ClickhouseTestMixin, BaseTest):
+ CLASS_DATA_LEVEL_SETUP = False
+
+ def setUp(self) -> None:
+ super().setUp()
+ _seed_n_events("rare_event", self.team, count=10, utm_source="google")
+ _seed_n_events("common_event", self.team, count=100, utm_source="google")
+ _seed_n_events("$pageview", self.team, count=500, utm_source="google")
+ flush_persons_and_events()
+
+ def tearDown(self) -> None:
+ flush_persons_and_events()
+ super().tearDown()
+
+ @pytest.mark.asyncio
+ async def test_events_below_min_count_excluded(self) -> None:
+ response = await suggest_conversion_goals(self.team, min_count=50, lookback_days=30)
+
+ event_names = [c.event_name for c in response.candidates]
+ assert "rare_event" not in event_names
+ assert "common_event" in event_names
+
+ @pytest.mark.asyncio
+ async def test_system_events_excluded_from_candidates(self) -> None:
+ response = await suggest_conversion_goals(self.team, min_count=50, lookback_days=30)
+
+ event_names = [c.event_name for c in response.candidates]
+ assert "$pageview" not in event_names
+ assert "common_event" in event_names
+
+
+class TestSuggestConversionGoalsClickhouseCountIf(ClickhouseTestMixin, BaseTest):
+ CLASS_DATA_LEVEL_SETUP = False
+
+ def setUp(self) -> None:
+ super().setUp()
+ _seed_n_events("purchase", self.team, count=60, utm_source="google")
+ _seed_n_events("purchase", self.team, count=40)
+ flush_persons_and_events()
+
+ def tearDown(self) -> None:
+ flush_persons_and_events()
+ super().tearDown()
+
+ @pytest.mark.asyncio
+ async def test_countif_hogql_computes_utm_coverage_correctly(self) -> None:
+ response = await suggest_conversion_goals(self.team, min_count=50, lookback_days=30)
+
+ purchase = next((c for c in response.candidates if c.event_name == "purchase"), None)
+ assert purchase is not None
+ assert purchase.last_30d_count == 100
+ assert purchase.pct_with_utm_source == pytest.approx(60.0, abs=1.0)
+
+
+class TestSuggestConversionGoalsClickhouseTopN(ClickhouseTestMixin, BaseTest):
+ CLASS_DATA_LEVEL_SETUP = False
+
+ def setUp(self) -> None:
+ super().setUp()
+ for i in range(10):
+ _seed_n_events(f"event_{i}", self.team, count=100, utm_source="google")
+ flush_persons_and_events()
+
+ def tearDown(self) -> None:
+ flush_persons_and_events()
+ super().tearDown()
+
+ @pytest.mark.asyncio
+ async def test_top_n_limits_returned_candidates(self) -> None:
+ response = await suggest_conversion_goals(self.team, top_n=3, min_count=50, lookback_days=30)
+
+ assert len(response.candidates) <= 3
diff --git a/products/marketing_analytics/backend/services/test_mapping_suggester.py b/products/marketing_analytics/backend/services/test_mapping_suggester.py
new file mode 100644
index 000000000000..132a818ea723
--- /dev/null
+++ b/products/marketing_analytics/backend/services/test_mapping_suggester.py
@@ -0,0 +1,160 @@
+import pytest
+from posthog.test.base import APIBaseTest
+from unittest.mock import AsyncMock, patch
+
+from products.marketing_analytics.backend.services.attribution_health import (
+ AttributionHealthEntry,
+ AttributionHealthResponse,
+ UnmatchedUtmSample,
+)
+from products.marketing_analytics.backend.services.mapping_suggester import suggest_utm_mappings
+from products.marketing_analytics.backend.services.native_integrations import NativeIntegration
+
+
+def _sample(raw_value: str, event_count: int, suggested_integration: NativeIntegration | None) -> UnmatchedUtmSample:
+ return UnmatchedUtmSample(raw_value=raw_value, event_count=event_count, suggested_integration=suggested_integration)
+
+
+def _entry_with_samples(
+ integration_key: NativeIntegration, samples: list[UnmatchedUtmSample]
+) -> AttributionHealthEntry:
+ return AttributionHealthEntry(
+ integration_key=integration_key,
+ display_name=integration_key,
+ events_with_utm_last_7d=0,
+ events_matched_last_7d=0,
+ events_unmatched_likely_yours_last_7d=sum(s.event_count for s in samples),
+ last_event_with_matching_utm_at=None,
+ matched_pct=0.0,
+ sample_unmatched_utm_sources=samples,
+ )
+
+
+class TestSuggestUtmMappings(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ attribution_patcher = patch(
+ "products.marketing_analytics.backend.services.mapping_suggester.get_attribution_health",
+ new_callable=AsyncMock,
+ )
+ custom_patcher = patch(
+ "products.marketing_analytics.backend.services.mapping_suggester._read_team_custom_mappings",
+ new_callable=AsyncMock,
+ )
+ self.mock_attribution = attribution_patcher.start()
+ self.mock_custom = custom_patcher.start()
+ self.addCleanup(attribution_patcher.stop)
+ self.addCleanup(custom_patcher.stop)
+
+ self.mock_attribution.return_value = AttributionHealthResponse(
+ lookback_days=30,
+ integrations=[],
+ total_events_with_utm=0,
+ total_events_matched_to_any_integration=0,
+ total_events_unmatched=0,
+ sample_globally_unmatched=[],
+ )
+ self.mock_custom.return_value = {}
+
+ @pytest.mark.asyncio
+ async def test_no_unmatched_returns_empty_suggestions(self):
+ response = await suggest_utm_mappings(self.team)
+ assert response.source_suggestions == []
+ assert response.total_unmatched_events_in_window == 0
+
+ @pytest.mark.asyncio
+ async def test_token_matched_sample_becomes_suggestion(self):
+ sample = _sample("facebook_paid", 120, "meta_ads")
+ self.mock_attribution.return_value = AttributionHealthResponse(
+ lookback_days=30,
+ integrations=[_entry_with_samples("meta_ads", [sample])],
+ total_events_with_utm=120,
+ total_events_matched_to_any_integration=0,
+ total_events_unmatched=120,
+ sample_globally_unmatched=[sample],
+ )
+
+ response = await suggest_utm_mappings(self.team)
+
+ assert len(response.source_suggestions) == 1
+ suggestion = response.source_suggestions[0]
+ assert suggestion.raw_utm_source == "facebook_paid"
+ assert suggestion.suggested_target == "meta_ads"
+ assert suggestion.suggested_target_display_name == "Meta Ads"
+ assert suggestion.event_count_30d == 120
+
+ @pytest.mark.asyncio
+ async def test_sample_without_alias_token_is_not_suggested(self):
+ sample = _sample("organic", 200, None)
+ self.mock_attribution.return_value = AttributionHealthResponse(
+ lookback_days=30,
+ integrations=[_entry_with_samples("meta_ads", [sample])],
+ total_events_with_utm=200,
+ total_events_matched_to_any_integration=0,
+ total_events_unmatched=200,
+ sample_globally_unmatched=[sample],
+ )
+
+ response = await suggest_utm_mappings(self.team)
+ assert response.source_suggestions == []
+ assert any("alias" in n for n in response.notes)
+
+ @pytest.mark.asyncio
+ async def test_below_min_event_count_filtered_out(self):
+ sample = _sample("facebook_paid", 3, "meta_ads")
+ self.mock_attribution.return_value = AttributionHealthResponse(
+ lookback_days=30,
+ integrations=[_entry_with_samples("meta_ads", [sample])],
+ total_events_with_utm=3,
+ total_events_matched_to_any_integration=0,
+ total_events_unmatched=3,
+ sample_globally_unmatched=[sample],
+ )
+
+ response = await suggest_utm_mappings(self.team, min_event_count=10)
+ assert response.source_suggestions == []
+
+ @pytest.mark.asyncio
+ async def test_max_per_integration_caps_output(self):
+ samples = [_sample(f"facebook_{i}", 100 - i, "meta_ads") for i in range(15)]
+ self.mock_attribution.return_value = AttributionHealthResponse(
+ lookback_days=30,
+ integrations=[_entry_with_samples("meta_ads", samples)],
+ total_events_with_utm=2000,
+ total_events_matched_to_any_integration=0,
+ total_events_unmatched=2000,
+ sample_globally_unmatched=samples,
+ )
+
+ response = await suggest_utm_mappings(self.team, max_per_integration=3)
+ meta_count = sum(1 for s in response.source_suggestions if s.suggested_target == "meta_ads")
+ assert meta_count == 3
+ assert any("Meta Ads" in n and "showing top 3" in n for n in response.notes)
+
+ @pytest.mark.asyncio
+ async def test_v1_does_not_emit_campaign_suggestions(self):
+ response = await suggest_utm_mappings(self.team)
+ assert response.campaign_suggestions == []
+ assert any("Campaign clustering" in n for n in response.notes)
+
+ @pytest.mark.asyncio
+ async def test_dedupe_when_same_raw_value_appears_in_multiple_integrations(self):
+ sample_meta = _sample("paidsocial", 80, "meta_ads")
+ sample_linkedin = _sample("paidsocial", 80, "linkedin_ads")
+ self.mock_attribution.return_value = AttributionHealthResponse(
+ lookback_days=30,
+ integrations=[
+ _entry_with_samples("meta_ads", [sample_meta]),
+ _entry_with_samples("linkedin_ads", [sample_linkedin]),
+ ],
+ total_events_with_utm=80,
+ total_events_matched_to_any_integration=0,
+ total_events_unmatched=80,
+ sample_globally_unmatched=[sample_meta, sample_linkedin],
+ )
+
+ response = await suggest_utm_mappings(self.team)
+ # The same raw value is suggested only once — the first occurrence wins.
+ raw_values = [s.raw_utm_source for s in response.source_suggestions]
+ assert raw_values.count("paidsocial") == 1
+ assert response.source_suggestions[0].suggested_target == "meta_ads"
diff --git a/products/marketing_analytics/backend/services/test_marketing_diagnostic.py b/products/marketing_analytics/backend/services/test_marketing_diagnostic.py
new file mode 100644
index 000000000000..82263f7474b2
--- /dev/null
+++ b/products/marketing_analytics/backend/services/test_marketing_diagnostic.py
@@ -0,0 +1,247 @@
+from typing import Any, cast
+
+import pytest
+from posthog.test.base import APIBaseTest
+from unittest.mock import AsyncMock, patch
+
+from parameterized import parameterized
+
+from products.marketing_analytics.backend.services.attribution_health import (
+ AttributionHealthEntry,
+ AttributionHealthResponse,
+)
+from products.marketing_analytics.backend.services.conversion_goals_inspector import (
+ ConversionGoalsListResponse,
+ ConversionGoalSummary,
+)
+from products.marketing_analytics.backend.services.data_source_health import (
+ DataSourceHealthEntry,
+ DataSourceHealthResponse,
+)
+from products.marketing_analytics.backend.services.marketing_diagnostic import (
+ _compute_overall_status,
+ _diagnose_one,
+ get_marketing_diagnostic,
+)
+
+
+def _ds_entry(**kwargs: Any) -> DataSourceHealthEntry:
+ defaults: dict[str, Any] = {
+ "source_type": "GoogleAds",
+ "is_native": True,
+ "display_name": "Google Ads",
+ "connected": True,
+ "last_sync_at": None,
+ "last_sync_status": "ok",
+ "last_error": None,
+ "rows_last_24h": 100,
+ "rows_last_7d": 500,
+ "sources_map_present": True,
+ "schema_columns_mapped": ["campaign", "source", "cost", "date"],
+ "schema_columns_required_missing": [],
+ "required_tables": [],
+ "settings_url": "/settings/environment-marketing-analytics#marketing-settings",
+ "schemas_url": "/data-management/sources/managed-fake/schemas",
+ "diagnosis": "Google Ads is healthy.",
+ "fix_suggestion": None,
+ }
+ defaults.update(kwargs)
+ return DataSourceHealthEntry(**defaults)
+
+
+def _attr_entry(**kwargs: Any) -> AttributionHealthEntry:
+ defaults: dict[str, Any] = {
+ "integration_key": "google_ads",
+ "display_name": "Google Ads",
+ "events_with_utm_last_7d": 1000,
+ "events_matched_last_7d": 500,
+ "events_unmatched_likely_yours_last_7d": 0,
+ "last_event_with_matching_utm_at": None,
+ "matched_pct": 50.0,
+ "sample_unmatched_utm_sources": [],
+ }
+ defaults.update(kwargs)
+ return AttributionHealthEntry(**defaults)
+
+
+_DIAGNOSE_ONE_CASES: list[tuple[str, dict | None, dict | None, str, str | None]] = [
+ # name, ds_kwargs (None → no source), attr_kwargs (None → no attribution),
+ # expected_status, expected_action_target_tool (None when no specific tool action)
+ ("not_connected_no_signals", None, None, "not_connected", None),
+ ("events_only_when_matched_no_source", None, {"events_matched_last_7d": 200}, "events_only", None),
+ (
+ "sync_broken_on_error",
+ {"last_sync_status": "error", "last_error": "auth", "diagnosis": "Google Ads last sync failed."},
+ {},
+ "sync_broken",
+ None,
+ ),
+ ("sync_broken_on_stale", {"last_sync_status": "stale"}, {}, "sync_broken", None),
+ ("schema_misconfigured", {"schema_columns_required_missing": ["cost"]}, {}, "schema_misconfigured", None),
+ (
+ "events_unmatched_with_likely_yours",
+ {},
+ {"events_matched_last_7d": 0, "events_unmatched_likely_yours_last_7d": 300},
+ "events_unmatched",
+ "marketing_suggest_utm_mappings",
+ ),
+ (
+ "events_broken_when_sync_ok_no_events",
+ {},
+ {"events_matched_last_7d": 0, "events_unmatched_likely_yours_last_7d": 0},
+ "events_broken",
+ "marketing_audit_utm",
+ ),
+ ("healthy_when_sync_ok_and_matched", {}, {"events_matched_last_7d": 500}, "healthy", None),
+]
+
+
+class TestDiagnoseOne:
+ @parameterized.expand([(case[0], *case[1:]) for case in _DIAGNOSE_ONE_CASES])
+ def test_diagnose_one(self, _name, ds_kwargs, attr_kwargs, expected_status, expected_target_tool):
+ ds = _ds_entry(**ds_kwargs) if ds_kwargs is not None else None
+ attr = _attr_entry(**attr_kwargs) if attr_kwargs is not None else None
+ result = _diagnose_one("GoogleAds", "google_ads", ds=ds, attr=attr)
+ assert result.overall_status == expected_status
+ if expected_target_tool is None:
+ return
+ assert any(a.target_tool == expected_target_tool for a in result.recommended_actions)
+
+
+def _make_diag(status: str):
+ from products.marketing_analytics.backend.services.marketing_diagnostic import (
+ IntegrationDiagnostic,
+ IntegrationStatus,
+ )
+
+ return IntegrationDiagnostic(
+ integration_key="google_ads",
+ source_type="GoogleAds",
+ display_name="Google Ads",
+ overall_status=cast(IntegrationStatus, status),
+ diagnosis="",
+ data_source=None,
+ attribution=None,
+ )
+
+
+class TestComputeOverallStatus:
+ @parameterized.expand(
+ [
+ ("only_not_connected_is_no_sources", ["not_connected", "not_connected"], "no_sources"),
+ ("all_healthy_is_healthy", ["healthy", "healthy"], "healthy"),
+ ("mixed_healthy_and_problems_is_degraded", ["healthy", "events_unmatched"], "degraded"),
+ ("only_sync_broken_is_broken", ["sync_broken", "schema_misconfigured"], "broken"),
+ ("events_unmatched_alone_is_degraded_not_broken", ["events_unmatched"], "degraded"),
+ ]
+ )
+ def test_compute_overall_status(self, _name, statuses, expected):
+ diags = [_make_diag(s) for s in statuses]
+ assert _compute_overall_status(diags) == expected
+
+
+class TestGetMarketingDiagnostic(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ ds_patcher = patch(
+ "products.marketing_analytics.backend.services.marketing_diagnostic.get_data_source_health",
+ new_callable=AsyncMock,
+ )
+ attr_patcher = patch(
+ "products.marketing_analytics.backend.services.marketing_diagnostic.get_attribution_health",
+ new_callable=AsyncMock,
+ )
+ goals_patcher = patch(
+ "products.marketing_analytics.backend.services.marketing_diagnostic.list_conversion_goals",
+ new_callable=AsyncMock,
+ )
+ config_patcher = patch(
+ "products.marketing_analytics.backend.services.marketing_diagnostic._load_marketing_config_snapshot",
+ new_callable=AsyncMock,
+ )
+ self.mock_ds = ds_patcher.start()
+ self.mock_attr = attr_patcher.start()
+ self.mock_goals = goals_patcher.start()
+ self.mock_config = config_patcher.start()
+ self.addCleanup(ds_patcher.stop)
+ self.addCleanup(attr_patcher.stop)
+ self.addCleanup(goals_patcher.stop)
+ self.addCleanup(config_patcher.stop)
+
+ self.mock_ds.return_value = DataSourceHealthResponse(
+ integrations=[], has_any_data=False, overall_status="no_sources"
+ )
+ self.mock_attr.return_value = AttributionHealthResponse(lookback_days=7)
+ self.mock_goals.return_value = ConversionGoalsListResponse()
+ self.mock_config.return_value = ({}, {})
+
+ @pytest.mark.asyncio
+ async def test_no_sources_no_events_no_goals(self):
+ response = await get_marketing_diagnostic(self.team)
+ assert response.overall_status == "no_sources"
+ assert "No marketing integrations" in response.summary
+ # Encourages configuring goals when none exist.
+ assert any(a.target_tool == "marketing_suggest_conversion_goals" for a in response.recommended_actions)
+
+ @pytest.mark.asyncio
+ async def test_events_only_corner_case_surfaced(self):
+ self.mock_attr.return_value = AttributionHealthResponse(
+ lookback_days=7,
+ integrations=[_attr_entry(events_matched_last_7d=100)],
+ )
+
+ response = await get_marketing_diagnostic(self.team)
+ google = next(i for i in response.integrations if i.integration_key == "google_ads")
+ assert google.overall_status == "events_only"
+
+ @pytest.mark.asyncio
+ async def test_sync_broken_propagates_to_overall(self):
+ self.mock_ds.return_value = DataSourceHealthResponse(
+ integrations=[_ds_entry(last_sync_status="error", last_error="x")],
+ has_any_data=False,
+ overall_status="broken",
+ )
+ response = await get_marketing_diagnostic(self.team)
+ assert response.overall_status == "broken"
+
+ @pytest.mark.asyncio
+ async def test_misconfigured_goals_surface_in_global_actions(self):
+ goal = ConversionGoalSummary(
+ id="999",
+ name="Sign up",
+ kind="ActionsNode",
+ target_label="Action #999",
+ last_30d_count=0,
+ integrated_count=None,
+ events_without_utm_source=None,
+ events_with_unmatched_utm_source=None,
+ non_integrated_count=None,
+ integrated_pct=None,
+ is_misconfigured=True,
+ misconfig_reason="Action 999 does not exist",
+ )
+ self.mock_goals.return_value = ConversionGoalsListResponse(
+ goals=[goal], attribution_window_days=90, attribution_mode="last_touch", has_misconfigured=True
+ )
+ response = await get_marketing_diagnostic(self.team)
+ assert any("misconfigured conversion goal" in a.title for a in response.recommended_actions)
+
+ @pytest.mark.asyncio
+ async def test_summary_mentions_healthy_count(self):
+ self.mock_ds.return_value = DataSourceHealthResponse(
+ integrations=[_ds_entry()],
+ has_any_data=True,
+ overall_status="healthy",
+ )
+ self.mock_attr.return_value = AttributionHealthResponse(
+ lookback_days=7,
+ integrations=[_attr_entry(events_matched_last_7d=500)],
+ )
+ response = await get_marketing_diagnostic(self.team)
+ assert response.overall_status == "healthy"
+ assert "healthy" in response.summary
+
+ @pytest.mark.asyncio
+ async def test_include_conversion_goals_false_skips_goals_call(self):
+ await get_marketing_diagnostic(self.team, include_conversion_goals=False)
+ self.mock_goals.assert_not_awaited()
diff --git a/products/marketing_analytics/backend/services/test_native_integrations.py b/products/marketing_analytics/backend/services/test_native_integrations.py
new file mode 100644
index 000000000000..361cd332d30b
--- /dev/null
+++ b/products/marketing_analytics/backend/services/test_native_integrations.py
@@ -0,0 +1,129 @@
+from parameterized import parameterized
+
+from products.marketing_analytics.backend.services.native_integrations import (
+ DISPLAY_NAMES,
+ EXTERNAL_SOURCE_TYPE_TO_NATIVE,
+ KEY_TO_NATIVE,
+ NATIVE_TO_KEY,
+ aliases_for,
+ canonical_source_aliases,
+ display_name_for_key,
+ lookup_alias,
+ normalize,
+)
+
+
+class TestNormalize:
+ @parameterized.expand(
+ [
+ ("Facebook", "facebook"),
+ ("FACEBOOK-ADS", "facebookads"),
+ ("Meta_Ads", "metaads"),
+ (" fb ", "fb"),
+ ("Google AdWords", "googleadwords"),
+ ("", ""),
+ ("---!!!", ""),
+ ]
+ )
+ def test_normalize(self, raw, expected):
+ assert normalize(raw) == expected
+
+
+class TestLookupAlias:
+ # Every value here MUST appear in one of the `*DefaultSources` enums in
+ # `posthog/schema.py` (the platform-documented source list). Ad-hoc
+ # variants like `fbads`, `googleads`, `tt` are NOT default-aliased — teams
+ # configure those via `custom_source_mappings` per project.
+ @parameterized.expand(
+ [
+ ("FB", "meta_ads"),
+ ("facebook", "meta_ads"),
+ ("Instagram", "meta_ads"),
+ ("Meta", "meta_ads"),
+ ("AdWords", "google_ads"),
+ ("YouTube", "google_ads"),
+ ("LinkedIn", "linkedin_ads"),
+ ("Bing", "bing_ads"),
+ ("Microsoft", "bing_ads"),
+ ("Snapchat", "snapchat_ads"),
+ ("TikTok", "tiktok_ads"),
+ ]
+ )
+ def test_known_aliases_resolve(self, raw, expected):
+ assert lookup_alias(raw) == expected
+
+ @parameterized.expand(
+ [
+ ("unknown_source",),
+ ("xyz",),
+ ("",),
+ ("organic",),
+ ("direct",),
+ ("newsletter",),
+ ]
+ )
+ def test_unknown_aliases_return_none(self, raw):
+ assert lookup_alias(raw) is None
+
+
+class TestAliasesFor:
+ def test_meta_ads_aliases_include_known_variants(self):
+ meta = aliases_for("meta_ads")
+ # All values come from MetaAdsDefaultSources in posthog/schema.py.
+ assert "fb" in meta
+ assert "facebook" in meta
+ assert "instagram" in meta
+ assert "meta" in meta
+
+ def test_aliases_are_disjoint_per_integration(self):
+ all_aliases: dict[str, str] = {}
+ for alias, target in canonical_source_aliases().items():
+ assert alias not in all_aliases, f"alias '{alias}' is mapped twice"
+ all_aliases[alias] = target
+
+ def test_youtube_resolves_to_google_ads(self):
+ # `youtube` is in GoogleAdsDefaultSources — confirms canonical aliases are
+ # derived from the official `*DefaultSources` enums (not a hardcoded list).
+ assert lookup_alias("youtube") == "google_ads"
+
+ def test_threads_resolves_to_meta_ads(self):
+ # `threads` is in MetaAdsDefaultSources.
+ assert lookup_alias("threads") == "meta_ads"
+
+ def test_whatsapp_resolves_to_meta_ads(self):
+ assert lookup_alias("whatsapp") == "meta_ads"
+
+ def test_each_native_has_at_least_one_alias(self):
+ for key in NATIVE_TO_KEY.values():
+ assert len(aliases_for(key)) > 0, f"no aliases configured for {key}"
+
+
+class TestDisplayNames:
+ @parameterized.expand(
+ [
+ ("google_ads", "Google Ads"),
+ ("meta_ads", "Meta Ads"),
+ ("bing_ads", "Bing Ads"),
+ ("linkedin_ads", "LinkedIn Ads"),
+ ("reddit_ads", "Reddit Ads"),
+ ("pinterest_ads", "Pinterest Ads"),
+ ("snapchat_ads", "Snapchat Ads"),
+ ("tiktok_ads", "TikTok Ads"),
+ ]
+ )
+ def test_display_name_for_key(self, key, expected):
+ assert display_name_for_key(key) == expected
+
+
+class TestStructuralInvariants:
+ def test_native_to_key_is_bijection_with_key_to_native(self):
+ assert {v: k for k, v in NATIVE_TO_KEY.items()} == KEY_TO_NATIVE
+
+ def test_display_names_cover_all_natives(self):
+ for native in NATIVE_TO_KEY.keys():
+ assert native in DISPLAY_NAMES
+
+ def test_external_source_type_resolves_to_native(self):
+ for source_type, native in EXTERNAL_SOURCE_TYPE_TO_NATIVE.items():
+ assert native in NATIVE_TO_KEY
+ assert isinstance(source_type, str)
diff --git a/products/marketing_analytics/backend/services/utm_audit.py b/products/marketing_analytics/backend/services/utm_audit.py
index a0df25953840..7d6db6167023 100644
--- a/products/marketing_analytics/backend/services/utm_audit.py
+++ b/products/marketing_analytics/backend/services/utm_audit.py
@@ -1,11 +1,15 @@
from dataclasses import dataclass
-from datetime import datetime
+
+from django.utils import timezone
+
+import structlog
from posthog.schema import DateRange, NativeMarketingSource
from posthog.hogql import ast
from posthog.hogql.query import execute_hogql_query
+from posthog.clickhouse.query_tagging import Feature, Product, tags_context
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
from posthog.models.team.team import DEFAULT_CURRENCY, Team
@@ -15,6 +19,7 @@ from products.marketing_analytics.backend.hogql_queries.constants import (
INTEGRATION_DEFAULT_SOURCES,
INTEGRATION_PRIMARY_SOURCE,
)
+from products.marketing_analytics.backend.services.native_integrations import KEY_TO_NATIVE, iter_custom_source_mappings
from products.marketing_analytics.backend.services.types import (
AlternativeSource,
Campaign,
@@ -29,6 +34,8 @@ from products.marketing_analytics.backend.services.types import (
UtmIssueSeverity,
)
+logger = structlog.get_logger(__name__)
+
def _load_team_mappings(team: Team) -> TeamMappings:
"""Load custom source mappings and campaign name mappings from team config."""
@@ -36,24 +43,27 @@ def _load_team_mappings(team: Team) -> TeamMappings:
if config is None:
return TeamMappings(source_to_integration={}, campaign_aliases={}, field_preferences={})
- # Build source mapping: custom utm_source values -> the integration's primary source
- # e.g. custom_source_mappings = {"GoogleAds": ["partner_blog", "affiliate"]}
- # The adapter for GoogleAds uses "google" as source_name, so "partner_blog" should match "google"
+ # Build source mapping: custom utm_source values -> the integration's primary source.
+ # e.g. custom_source_mappings = {"GoogleAds": ["partner_blog", "affiliate"]} →
+ # {"partner_blog": "google", "affiliate": "google"} because the GoogleAds adapter
+ # uses "google" as `source_name`. The (target_key, raw_value) pairs come from
+ # `iter_custom_source_mappings` so the enum-resolution rules stay shared with
+ # `native_integrations.build_combined_alias_map`.
source_to_integration: dict[str, str] = {}
-
- custom_source_mappings = config.custom_source_mappings or {}
- for integration_type, custom_sources in custom_source_mappings.items():
- try:
- native_source = NativeMarketingSource(integration_type)
- except ValueError:
- native_source = None
- primary_source = (
- INTEGRATION_PRIMARY_SOURCE.get(native_source, integration_type.lower())
- if native_source
- else integration_type.lower()
- )
- for custom_source in custom_sources:
- source_to_integration[custom_source.lower().strip()] = primary_source.lower().strip()
+ for target_key, raw_value in iter_custom_source_mappings(config.custom_source_mappings):
+ native = KEY_TO_NATIVE[target_key]
+ primary = INTEGRATION_PRIMARY_SOURCE.get(native)
+ if not primary:
+ # Integration without a registered primary source (e.g. shipped before
+ # INTEGRATION_PRIMARY_SOURCE was updated). Drop it, but log the gap.
+ logger.warning(
+ "utm_audit_dropping_custom_mapping_no_primary_source",
+ team_id=team.id,
+ integration=native.value,
+ raw_value=raw_value,
+ )
+ continue
+ source_to_integration[raw_value.lower().strip()] = str(primary).lower().strip()
# Build campaign aliases: clean_campaign_name -> set of raw utm values
# e.g. campaign_name_mappings = {"GoogleAds": {"brand_campaign": ["partner_q1", "brand_q1"]}}
@@ -121,7 +131,7 @@ def run_utm_audit(team: Team, date_from: str = "-30d", date_to: str | None = Non
date_range=DateRange(date_from=date_from, date_to=date_to),
team=team,
interval=None,
- now=datetime.now(),
+ now=timezone.now(),
)
mappings = _load_team_mappings(team)
@@ -205,7 +215,8 @@ def _get_campaigns_with_spend(team: Team, date_range: QueryDateRange) -> list[Ca
limit=ast.Constant(value=500),
)
- result = execute_hogql_query(query, team)
+ with tags_context(product=Product.MARKETING_ANALYTICS, feature=Feature.HEALTH_CHECK, team_id=team.pk):
+ result = execute_hogql_query(query, team)
campaigns = []
for row in result.results or []:
campaigns.append(
@@ -243,14 +254,15 @@ def _get_utm_events(team: Team, date_range: QueryDateRange) -> dict[tuple[str, s
LIMIT 5000
"""
- result = execute_hogql_query(
- hogql,
- team,
- placeholders={
- "date_from": date_range.date_from_as_hogql(),
- "date_to": date_range.date_to_as_hogql(),
- },
- )
+ with tags_context(product=Product.MARKETING_ANALYTICS, feature=Feature.HEALTH_CHECK, team_id=team.pk):
+ result = execute_hogql_query(
+ hogql,
+ team,
+ placeholders={
+ "date_from": date_range.date_from_as_hogql(),
+ "date_to": date_range.date_to_as_hogql(),
+ },
+ )
utm_map: dict[tuple[str, str], int] = {}
for row in result.results or []:
campaign = (row[0] or "").lower().strip()
diff --git a/products/marketing_analytics/backend/test_max_tools.py b/products/marketing_analytics/backend/test_max_tools.py
new file mode 100644
index 000000000000..ea807cfe9ab6
--- /dev/null
+++ b/products/marketing_analytics/backend/test_max_tools.py
@@ -0,0 +1,1156 @@
+import os
+from datetime import UTC, datetime, timedelta
+
+import pytest
+from freezegun import freeze_time
+from posthog.test.base import BaseTest
+from unittest.mock import AsyncMock, patch
+
+from langchain_core.runnables import RunnableConfig
+from parameterized import parameterized
+
+from posthog.schema import DateRange
+
+from products.marketing_analytics.backend.max_tools import (
+ MAX_LOOKBACK_DAYS,
+ MarketingAuditUtmTool,
+ MarketingDiagnoseSetupTool,
+ MarketingExplainConversionGoalTool,
+ MarketingListConversionGoalsTool,
+ MarketingListDataSourcesTool,
+ MarketingSuggestConversionGoalsTool,
+ MarketingSuggestUtmMappingsTool,
+ _format_audit_utm_for_llm,
+ _format_conversion_goals_for_llm,
+ _format_data_sources_for_llm,
+ _format_diagnostic_for_llm,
+ _format_event_suggestions_for_llm,
+ _format_explain_goal_for_llm,
+ _format_goal_line,
+ _format_timestamp_for_llm,
+ _format_utm_mapping_suggestions_for_llm,
+ _lookback_days_from_date_range,
+ _resolve_lookback_days,
+ _sanitize_for_prompt,
+)
+from products.marketing_analytics.backend.services.conversion_goals_inspector import (
+ ConversionGoalsListResponse,
+ ConversionGoalSummary,
+ GoalEventSample,
+ GoalExplanation,
+)
+from products.marketing_analytics.backend.services.data_source_health import (
+ DataSourceHealthEntry,
+ DataSourceHealthResponse,
+ RequiredTableStatus,
+)
+from products.marketing_analytics.backend.services.event_suggestions import CandidateEvent, EventSuggestionsResponse
+from products.marketing_analytics.backend.services.mapping_suggester import (
+ CatalogueEntry,
+ CurrentMapping,
+ RawUnmatchedSample,
+ SourceMappingSuggestion,
+ UtmMappingSuggestionsResponse,
+)
+from products.marketing_analytics.backend.services.marketing_diagnostic import (
+ IntegrationDiagnostic,
+ MarketingDiagnosticResponse,
+ RecommendedAction,
+)
+from products.marketing_analytics.backend.services.types import (
+ CampaignAuditResult,
+ UtmAuditResponse,
+ UtmEvent,
+ UtmIssue,
+ UtmIssueKind,
+ UtmIssueSeverity,
+)
+
+
+def _make_config(team, user, contextual_tools=None):
+ configurable = {"team": team, "user": user}
+ if contextual_tools is not None:
+ configurable["contextual_tools"] = contextual_tools
+ return RunnableConfig(configurable=configurable)
+
+
+def _make_tool(cls, team, user, contextual_tools=None):
+ return cls(team=team, user=user, config=_make_config(team, user, contextual_tools))
+
+
+def _make_data_source_entry(
+ *,
+ source_type="GoogleAds",
+ display_name="Google Ads",
+ connected=True,
+ last_sync_at=None,
+ last_sync_status="ok",
+ last_error=None,
+ rows_last_24h=100,
+ rows_last_7d=700,
+ schema_columns_required_missing=None,
+ required_tables=None,
+ settings_url="/settings/environment-marketing-analytics#marketing-settings",
+ schemas_url=None,
+ diagnosis="All good",
+ fix_suggestion=None,
+):
+ return DataSourceHealthEntry(
+ source_type=source_type,
+ is_native=True,
+ display_name=display_name,
+ connected=connected,
+ last_sync_at=last_sync_at,
+ last_sync_status=last_sync_status,
+ last_error=last_error,
+ rows_last_24h=rows_last_24h,
+ rows_last_7d=rows_last_7d,
+ sources_map_present=True,
+ schema_columns_mapped=[],
+ schema_columns_required_missing=schema_columns_required_missing or [],
+ required_tables=required_tables or [],
+ settings_url=settings_url,
+ schemas_url=schemas_url,
+ diagnosis=diagnosis,
+ fix_suggestion=fix_suggestion,
+ )
+
+
+def _make_goal_summary(
+ *,
+ id="goal-1",
+ name="Purchase",
+ kind="EventsNode",
+ target_label="purchase",
+ last_30d_count=150,
+ integrated_count=100,
+ events_without_utm_source=30,
+ events_with_unmatched_utm_source=20,
+ non_integrated_count=50,
+ integrated_pct=66.7,
+ is_misconfigured=False,
+ misconfig_reason=None,
+):
+ return ConversionGoalSummary(
+ id=id,
+ name=name,
+ kind=kind,
+ target_label=target_label,
+ last_30d_count=last_30d_count,
+ integrated_count=integrated_count,
+ events_without_utm_source=events_without_utm_source,
+ events_with_unmatched_utm_source=events_with_unmatched_utm_source,
+ non_integrated_count=non_integrated_count,
+ integrated_pct=integrated_pct,
+ is_misconfigured=is_misconfigured,
+ misconfig_reason=misconfig_reason,
+ )
+
+
+class TestSanitizeForPrompt(BaseTest):
+ @parameterized.expand(
+ [
+ ("newline_to_space", "google\nads", "google ads"),
+ ("carriage_return_to_space", "google\rads", "google ads"),
+ ("tab_to_space", "google\tads", "google ads"),
+ ("null_byte_removed", "google\x00ads", "googleads"),
+ ("del_char_removed", "google\x7fads", "googleads"),
+ ("mixed_whitespace_collapsed", "a\nb\tc\rd", "a b c d"),
+ ("clean_value_passthrough", "GoogleAds", "GoogleAds"),
+ ("system_marker_stripped", "<system>foo</system>", "foo"),
+ ("nested_marker_stripped", "<<system>system>foo", "foo"),
+ ("html_tag_stripped", "<script>alert(1)</script>", "alert(1)"),
+ ("whitespace_run_collapsed", "spaces here", "spaces here"),
+ ]
+ )
+ def test_sanitizes(self, _name, value, expected):
+ assert _sanitize_for_prompt(value) == expected
+
+ def test_truncates_long_value_with_ellipsis_marker(self):
+ result = _sanitize_for_prompt("a" * 1000)
+ assert result == "a" * 200 + "…"
+
+ def test_short_value_not_truncated(self):
+ result = _sanitize_for_prompt("short", max_len=100)
+ assert result == "short"
+ assert "…" not in result
+
+ def test_custom_max_len_honoured(self):
+ result = _sanitize_for_prompt("a" * 20, max_len=10)
+ assert result == "a" * 10 + "…"
+
+ def test_none_returns_placeholder(self):
+ assert _sanitize_for_prompt(None) == "<none>"
+
+ def test_empty_string_returns_placeholder(self):
+ assert _sanitize_for_prompt("") == "<none>"
+ assert _sanitize_for_prompt(" ") == "<none>"
+
+ def test_value_that_becomes_empty_after_stripping_returns_placeholder(self):
+ assert _sanitize_for_prompt("<system></system>") == "<none>"
+
+ def test_non_string_value_coerced(self):
+ assert _sanitize_for_prompt(42) == "42"
+ assert _sanitize_for_prompt(3.14) == "3.14"
+
+ def test_unicode_visible_chars_preserved(self):
+ assert _sanitize_for_prompt("café 🚀") == "café 🚀"
+
+ def test_invisible_unicode_stripped(self):
+ # Zero-width joiner + variation selector — common smuggling vectors.
+ result = _sanitize_for_prompt("a​b️c")
+ assert result == "abc"
+
+
+@freeze_time("2025-06-15")
+class TestFormatTimestampForLlm(BaseTest):
+ @parameterized.expand(
+ [
+ ("none_returns_never", None, "never"),
+ ("future_date_mentions_future", datetime(2099, 1, 1, tzinfo=UTC), "future"),
+ ]
+ )
+ def test_timestamp_variants(self, _name, dt, expected_substring):
+ result = _format_timestamp_for_llm(dt)
+ assert expected_substring in result
+
+ def test_past_date_contains_days_ago(self):
+ past = datetime.now(tz=UTC) - timedelta(days=5)
+ result = _format_timestamp_for_llm(past)
+ assert "days ago" in result
+ assert past.strftime("%Y-%m-%d") in result
+
+ def test_today_contains_today(self):
+ from django.utils import timezone
+
+ today = timezone.now()
+ result = _format_timestamp_for_llm(today)
+ assert "today" in result
+
+
+class TestLookbackDaysFromDateRange(BaseTest):
+ def test_none_date_range_returns_none(self):
+ result = _lookback_days_from_date_range(self.team, None)
+ assert result is None
+
+ def test_non_dict_date_range_returns_none(self):
+ result = _lookback_days_from_date_range(self.team, "not_a_dict") # type: ignore[arg-type]
+ assert result is None
+
+ def test_empty_dict_returns_none(self):
+ result = _lookback_days_from_date_range(self.team, {})
+ assert result is None
+
+ def test_invalid_date_string_returns_none(self):
+ result = _lookback_days_from_date_range(self.team, {"date_from": "not-a-date"})
+ assert result is None
+
+ def test_relative_range_returns_positive_integer(self):
+ result = _lookback_days_from_date_range(self.team, {"date_from": "-30d"})
+ assert result is not None
+ assert result > 0
+
+ @parameterized.expand(
+ [
+ ("30d_relative", {"date_from": "-30d"}, 29, 31),
+ ("7d_relative", {"date_from": "-7d"}, 6, 8),
+ ]
+ )
+ def test_relative_range_approximate_days(self, _name, date_range, min_days, max_days):
+ result = _lookback_days_from_date_range(self.team, date_range)
+ assert result is not None
+ assert min_days <= result <= max_days
+
+
+class TestResolveLookbackDays(BaseTest):
+ def test_explicit_value_takes_precedence(self):
+ result = _resolve_lookback_days(self.team, {"current_date_range": {"date_from": "-30d"}}, 15, 7)
+ assert result == 15
+
+ def test_inferred_from_context_used_when_no_explicit(self):
+ result = _resolve_lookback_days(self.team, {"current_date_range": {"date_from": "-30d"}}, None, 7)
+ assert result > 7
+
+ def test_fallback_used_when_no_explicit_or_context(self):
+ result = _resolve_lookback_days(self.team, {}, None, 90)
+ assert result == 90
+
+ @parameterized.expand(
+ [
+ ("explicit_over_limit", 500, {}, 7),
+ ("fallback_over_limit", None, {}, 500),
+ ("inferred_over_limit_via_very_long_range", None, {"current_date_range": {"date_from": "-2000d"}}, 7),
+ ]
+ )
+ def test_result_always_clamped_to_max_lookback(self, _name, requested, context, fallback):
+ result = _resolve_lookback_days(self.team, context, requested, fallback)
+ assert result <= MAX_LOOKBACK_DAYS
+
+ def test_zero_requested_falls_through_to_context(self):
+ result = _resolve_lookback_days(self.team, {}, 0, 90)
+ assert result == 90
+
+ def test_negative_requested_falls_through_to_context(self):
+ result = _resolve_lookback_days(self.team, {}, -5, 90)
+ assert result == 90
+
+
+@freeze_time("2025-06-15")
+class TestFormatDiagnosticForLlm(BaseTest):
+ def _make_minimal_response(self, *, overall_status="healthy", summary="All good"):
+ return MarketingDiagnosticResponse(
+ integrations=[],
+ overall_status=overall_status,
+ summary=summary,
+ conversion_goals=None,
+ recommended_actions=[],
+ )
+
+ def test_contains_overall_status_and_summary(self):
+ response = self._make_minimal_response(overall_status="degraded", summary="One integration has problems.")
+ result = _format_diagnostic_for_llm(response)
+ assert "degraded" in result
+ assert "One integration has problems." in result
+
+ def test_does_not_emit_bare_matched_pct_percentage(self):
+ from products.marketing_analytics.backend.services.attribution_health import AttributionHealthEntry
+
+ attr = AttributionHealthEntry(
+ integration_key="google_ads",
+ display_name="Google Ads",
+ events_with_utm_last_7d=1000,
+ events_matched_last_7d=750,
+ events_unmatched_likely_yours_last_7d=0,
+ last_event_with_matching_utm_at=None,
+ matched_pct=75.0,
+ sample_unmatched_utm_sources=[],
+ )
+ integration = IntegrationDiagnostic(
+ integration_key="google_ads",
+ source_type="GoogleAds",
+ display_name="Google Ads",
+ overall_status="healthy",
+ diagnosis="All good",
+ data_source=None,
+ attribution=attr,
+ recommended_actions=[],
+ )
+ response = MarketingDiagnosticResponse(
+ integrations=[integration],
+ overall_status="healthy",
+ summary="Healthy",
+ conversion_goals=None,
+ recommended_actions=[],
+ )
+ result = _format_diagnostic_for_llm(response)
+ # Must contain denominator phrasing — "matched N of M team events-with-utm_source"
+ assert "matched 750 of 1000 team events-with-utm_source" in result
+ # Must NOT emit a bare "matched_pct=75%"-only string without the denominator context
+ assert "matched_pct=75.0%" not in result or "of" in result
+
+ def test_timestamp_displayed_as_formatted_string_not_raw_datetime(self):
+ from django.utils import timezone
+
+ sync_time = timezone.now() - timedelta(days=2)
+ ds = _make_data_source_entry(last_sync_at=sync_time)
+ integration = IntegrationDiagnostic(
+ integration_key="google_ads",
+ source_type="GoogleAds",
+ display_name="Google Ads",
+ overall_status="healthy",
+ diagnosis="All good",
+ data_source=ds,
+ attribution=None,
+ recommended_actions=[],
+ )
+ response = MarketingDiagnosticResponse(
+ integrations=[integration],
+ overall_status="healthy",
+ summary="Healthy",
+ conversion_goals=None,
+ recommended_actions=[],
+ )
+ result = _format_diagnostic_for_llm(response)
+ assert "days ago" in result
+
+ def test_recommended_actions_included(self):
+ response = self._make_minimal_response()
+ response.recommended_actions = [
+ RecommendedAction(title="Fix sync", detail="Reconnect.", severity="error", target_tool=None)
+ ]
+ result = _format_diagnostic_for_llm(response)
+ assert "Fix sync" in result
+
+ def test_conversion_goals_section_present_when_provided(self):
+ goals_resp = ConversionGoalsListResponse(
+ goals=[_make_goal_summary()],
+ attribution_window_days=30,
+ attribution_mode="last_touch",
+ has_misconfigured=False,
+ )
+ response = self._make_minimal_response()
+ response.conversion_goals = goals_resp
+ result = _format_diagnostic_for_llm(response)
+ assert "Conversion goals" in result
+ assert "Purchase" in result
+
+
+class TestFormatConversionGoalsForLlm(BaseTest):
+ def test_empty_goals_returns_no_goals_message(self):
+ response = ConversionGoalsListResponse(
+ goals=[],
+ attribution_window_days=30,
+ attribution_mode="last_touch",
+ has_misconfigured=False,
+ )
+ result = _format_conversion_goals_for_llm(response)
+ assert result == "No conversion goals are configured for this project."
+
+ def test_populated_goals_includes_goal_names(self):
+ response = ConversionGoalsListResponse(
+ goals=[_make_goal_summary(name="Signup"), _make_goal_summary(id="goal-2", name="Purchase")],
+ attribution_window_days=30,
+ attribution_mode="last_touch",
+ has_misconfigured=False,
+ )
+ result = _format_conversion_goals_for_llm(response)
+ assert "Signup" in result
+ assert "Purchase" in result
+
+ def test_populated_goals_includes_non_integrated_split_instructions(self):
+ response = ConversionGoalsListResponse(
+ goals=[_make_goal_summary()],
+ attribution_window_days=30,
+ attribution_mode="last_touch",
+ has_misconfigured=False,
+ )
+ result = _format_conversion_goals_for_llm(response)
+ assert "non_integrated_count" in result
+ assert "events_without_utm_source" in result
+ assert "events_with_unmatched_utm_source" in result
+
+ def test_includes_attribution_mode_and_window(self):
+ response = ConversionGoalsListResponse(
+ goals=[_make_goal_summary()],
+ attribution_window_days=14,
+ attribution_mode="first_touch",
+ has_misconfigured=False,
+ )
+ result = _format_conversion_goals_for_llm(response)
+ assert "first_touch" in result
+ assert "14" in result
+
+
+class TestFormatGoalLine(BaseTest):
+ def test_includes_goal_name_and_kind(self):
+ goal = _make_goal_summary(name="Signup", kind="EventsNode")
+ result = _format_goal_line(goal)
+ assert "Signup" in result
+ assert "EventsNode" in result
+
+ def test_include_id_prepends_id(self):
+ goal = _make_goal_summary(id="abc-123")
+ result = _format_goal_line(goal, include_id=True)
+ assert "abc-123" in result
+
+ def test_misconfigured_flag_shown(self):
+ goal = _make_goal_summary(is_misconfigured=True, misconfig_reason="Action not found")
+ result = _format_goal_line(goal)
+ assert "MISCONFIGURED" in result
+ assert "Action not found" in result
+
+ def test_integrated_split_shown(self):
+ goal = _make_goal_summary(integrated_count=100, non_integrated_count=50)
+ result = _format_goal_line(goal)
+ assert "integrated=100" in result
+ assert "non_integrated=50" in result
+
+
+@freeze_time("2025-06-15")
+class TestFormatDataSourcesForLlm(BaseTest):
+ def test_not_connected_shows_in_output(self):
+ entry = _make_data_source_entry(
+ display_name="Meta Ads",
+ connected=False,
+ last_sync_status="not_connected",
+ )
+ response = DataSourceHealthResponse(
+ integrations=[entry],
+ has_any_data=False,
+ overall_status="no_sources",
+ issues_summary=[],
+ )
+ result = _format_data_sources_for_llm(response)
+ assert "Meta Ads" in result
+ assert "not connected" in result
+
+ def test_connected_entry_shows_sync_status_and_timestamp(self):
+ from django.utils import timezone
+
+ sync_at = timezone.now() - timedelta(days=1)
+ entry = _make_data_source_entry(
+ display_name="Google Ads",
+ connected=True,
+ last_sync_at=sync_at,
+ last_sync_status="ok",
+ )
+ response = DataSourceHealthResponse(
+ integrations=[entry],
+ has_any_data=True,
+ overall_status="healthy",
+ issues_summary=[],
+ )
+ result = _format_data_sources_for_llm(response)
+ assert "Google Ads" in result
+ assert "ok" in result
+ assert "1 day ago" in result
+
+ def test_required_tables_shown(self):
+ table = RequiredTableStatus(
+ table_name="ads_report",
+ present=True,
+ should_sync=True,
+ status="Completed",
+ last_synced_at=None,
+ )
+ entry = _make_data_source_entry(required_tables=[table])
+ response = DataSourceHealthResponse(
+ integrations=[entry],
+ has_any_data=True,
+ overall_status="healthy",
+ issues_summary=[],
+ )
+ result = _format_data_sources_for_llm(response)
+ assert "ads_report" in result
+
+ def test_issues_summary_appended(self):
+ entry = _make_data_source_entry()
+ response = DataSourceHealthResponse(
+ integrations=[entry],
+ has_any_data=True,
+ overall_status="degraded",
+ issues_summary=["Google Ads schema is missing cost_micros column."],
+ )
+ result = _format_data_sources_for_llm(response)
+ assert "cost_micros" in result
+
+
+class TestFormatExplainGoalForLlm(BaseTest):
+ def _make_explanation(self, *, kind="EventsNode", total_count=200):
+ return GoalExplanation(
+ goal_id="goal-1",
+ goal_name="Signup",
+ kind=kind,
+ period=DateRange(date_from="2025-04-01", date_to="2025-05-01"),
+ total_count=total_count,
+ integrated_count=150,
+ events_without_utm_source=30,
+ events_with_unmatched_utm_source=20,
+ non_integrated_count=50,
+ by_event=[("user signed up", 200)],
+ by_utm_source=[("google", 150)],
+ by_matched_integration=[("GoogleAds", 150)],
+ samples=[
+ GoalEventSample(
+ event_uuid="uuid-1",
+ timestamp=datetime(2025, 4, 15, tzinfo=UTC),
+ distinct_id="user-1",
+ utm_source="google",
+ utm_campaign="brand",
+ matched_integration="GoogleAds",
+ )
+ ],
+ notes=["This is a flat breakdown."],
+ )
+
+ def test_contains_goal_name_and_total(self):
+ result = _format_explain_goal_for_llm(self._make_explanation())
+ assert "Signup" in result
+ assert "200" in result
+
+ def test_utm_source_breakdown_present(self):
+ result = _format_explain_goal_for_llm(self._make_explanation())
+ assert "google" in result
+
+ def test_integration_split_present(self):
+ result = _format_explain_goal_for_llm(self._make_explanation())
+ assert "GoogleAds" in result
+
+ def test_non_integrated_split_instructions_included_when_split_available(self):
+ result = _format_explain_goal_for_llm(self._make_explanation())
+ assert "non_integrated_count" in result
+
+ def test_notes_included(self):
+ result = _format_explain_goal_for_llm(self._make_explanation())
+ assert "flat breakdown" in result
+
+
+class TestFormatAuditUtmForLlm(BaseTest):
+ def _make_response(self, *, campaigns_with_issues=0, results=None, all_utm_events=None):
+ return UtmAuditResponse(
+ total_campaigns=5,
+ campaigns_with_issues=campaigns_with_issues,
+ campaigns_without_issues=5 - campaigns_with_issues,
+ total_spend_at_risk=0.0,
+ results=results or [],
+ all_utm_events=all_utm_events or [],
+ )
+
+ def test_summary_line_present(self):
+ response = self._make_response(campaigns_with_issues=2)
+ result = _format_audit_utm_for_llm(response)
+ assert "2 of 5 campaigns have issues" in result
+
+ def test_campaigns_with_issues_shown(self):
+ issue = UtmIssue(
+ field="utm_source",
+ severity=UtmIssueSeverity.ERROR,
+ kind=UtmIssueKind.NOT_LINKED,
+ message="Campaign not linked",
+ )
+ campaign = CampaignAuditResult(
+ campaign_name="brand_campaign",
+ campaign_id="camp-1",
+ source_name="google",
+ spend=100.0,
+ clicks=50,
+ impressions=500,
+ has_utm_events=False,
+ event_count=0,
+ issues=[issue],
+ )
+ response = self._make_response(campaigns_with_issues=1, results=[campaign])
+ result = _format_audit_utm_for_llm(response)
+ assert "brand_campaign" in result
+ assert "Campaign not linked" in result
+
+ def test_unmatched_utm_events_shown(self):
+ event = UtmEvent(
+ utm_campaign="summer_sale",
+ utm_source="unknown_source",
+ event_count=10,
+ campaign_match="none",
+ source_match="none",
+ matched_campaign=None,
+ )
+ response = self._make_response(all_utm_events=[event])
+ result = _format_audit_utm_for_llm(response)
+ assert "unknown_source" in result
+
+
+class TestFormatEventSuggestionsForLlm(BaseTest):
+ def test_empty_candidates_returns_no_candidates_message(self):
+ response = EventSuggestionsResponse(candidates=[], lookback_days=30)
+ result = _format_event_suggestions_for_llm(response)
+ assert "No suitable candidate events found" in result
+
+ def test_populated_candidates_shows_event_names(self):
+ candidate = CandidateEvent(
+ event_name="user_signed_up",
+ last_30d_count=500,
+ distinct_users_30d=480,
+ pct_with_utm_source=60.0,
+ pct_with_utm_campaign=55.0,
+ top_utm_sources=[("google", 300), ("facebook", 100)],
+ is_already_a_goal=False,
+ suggestion_score=0.88,
+ suggestion_reason="High volume with good UTM coverage.",
+ )
+ response = EventSuggestionsResponse(candidates=[candidate], lookback_days=30)
+ result = _format_event_suggestions_for_llm(response)
+ assert "user_signed_up" in result
+ assert "500" in result
+ assert "High volume with good UTM coverage." in result
+
+ def test_already_a_goal_flag_shown(self):
+ candidate = CandidateEvent(
+ event_name="purchase",
+ last_30d_count=100,
+ distinct_users_30d=90,
+ pct_with_utm_source=50.0,
+ pct_with_utm_campaign=40.0,
+ top_utm_sources=[],
+ is_already_a_goal=True,
+ suggestion_score=0.5,
+ suggestion_reason="Already configured.",
+ )
+ response = EventSuggestionsResponse(candidates=[candidate], lookback_days=30)
+ result = _format_event_suggestions_for_llm(response)
+ assert "already a goal" in result
+
+
+class TestFormatUtmMappingSuggestionsForLlm(BaseTest):
+ def _make_empty_response(self):
+ return UtmMappingSuggestionsResponse(
+ lookback_days_used=90,
+ total_events_with_utm_in_window=0,
+ total_unmatched_events_in_window=0,
+ )
+
+ def test_lookback_window_in_output(self):
+ result = _format_utm_mapping_suggestions_for_llm(self._make_empty_response())
+ assert "90" in result
+
+ def test_full_catalogue_shown(self):
+ entry = CatalogueEntry(
+ raw_utm_source="google",
+ event_count=500,
+ matched_integration="google_ads",
+ matched_integration_display_name="Google Ads",
+ suggested_integration=None,
+ )
+ response = self._make_empty_response()
+ response.full_utm_source_catalogue = [entry]
+ result = _format_utm_mapping_suggestions_for_llm(response)
+ assert "google" in result
+ assert "Google Ads" in result
+
+ def test_suggestions_shown(self):
+ suggestion = SourceMappingSuggestion(
+ raw_utm_source="facebook_paid",
+ suggested_target="meta_ads",
+ suggested_target_display_name="Meta Ads",
+ reason="'facebook_paid' contains a known alias of Meta Ads.",
+ event_count_30d=200,
+ )
+ response = self._make_empty_response()
+ response.source_suggestions = [suggestion]
+ result = _format_utm_mapping_suggestions_for_llm(response)
+ assert "facebook_paid" in result
+ assert "Meta Ads" in result
+
+ def test_no_suggestions_shows_none(self):
+ result = _format_utm_mapping_suggestions_for_llm(self._make_empty_response())
+ assert "none" in result.lower()
+
+ def test_raw_unmatched_samples_shown(self):
+ sample = RawUnmatchedSample(
+ raw_utm_source="organic",
+ event_count=50,
+ suggested_integration=None,
+ )
+ response = self._make_empty_response()
+ response.raw_unmatched_samples = [sample]
+ result = _format_utm_mapping_suggestions_for_llm(response)
+ assert "organic" in result
+
+ def test_current_mappings_shown_grouped_by_target(self):
+ mapping = CurrentMapping(
+ raw_utm_source="cpc",
+ target="google_ads",
+ target_display_name="Google Ads",
+ source="canonical",
+ )
+ response = self._make_empty_response()
+ response.current_mappings = [mapping]
+ result = _format_utm_mapping_suggestions_for_llm(response)
+ assert "cpc" in result
+ assert "Google Ads" in result
+
+ def test_team_custom_mappings_section_present(self):
+ mapping = CurrentMapping(
+ raw_utm_source="partner_blog",
+ target="google_ads",
+ target_display_name="Google Ads",
+ source="team_custom",
+ )
+ response = self._make_empty_response()
+ response.current_mappings = [mapping]
+ result = _format_utm_mapping_suggestions_for_llm(response)
+ assert "Team-custom mappings" in result
+ assert "partner_blog" in result
+
+
+class TestMarketingDiagnoseSetupTool(BaseTest):
+ def setUp(self):
+ super().setUp()
+ os.environ["OPENAI_API_KEY"] = "test-api-key"
+
+ def tearDown(self):
+ super().tearDown()
+ os.environ.pop("OPENAI_API_KEY", None)
+
+ def _setup_tool(self):
+ return _make_tool(MarketingDiagnoseSetupTool, self.team, self.user)
+
+ @pytest.mark.django_db
+ @pytest.mark.asyncio
+ async def test_arun_impl_returns_string_and_dict(self):
+ tool = self._setup_tool()
+ mock_response = MarketingDiagnosticResponse(
+ integrations=[],
+ overall_status="no_sources",
+ summary="No sources configured.",
+ conversion_goals=None,
+ recommended_actions=[],
+ )
+ with patch(
+ "products.marketing_analytics.backend.max_tools.get_marketing_diagnostic",
+ new=AsyncMock(return_value=mock_response),
+ ):
+ content, artifact = await tool._arun_impl()
+
+ assert isinstance(content, str)
+ assert isinstance(artifact, dict)
+ assert "No sources" in content or "no_sources" in content
+
+ @pytest.mark.django_db
+ @pytest.mark.asyncio
+ async def test_arun_impl_passes_resolved_lookback_to_service(self):
+ tool = self._setup_tool()
+ mock_response = MarketingDiagnosticResponse(
+ integrations=[],
+ overall_status="no_sources",
+ summary="",
+ conversion_goals=None,
+ recommended_actions=[],
+ )
+ with patch(
+ "products.marketing_analytics.backend.max_tools.get_marketing_diagnostic",
+ new=AsyncMock(return_value=mock_response),
+ ) as mock_svc:
+ await tool._arun_impl(attribution_lookback_days=30)
+
+ mock_svc.assert_called_once()
+ _args, kwargs = mock_svc.call_args
+ assert kwargs["attribution_lookback_days"] == 30
+
+ @pytest.mark.django_db
+ @pytest.mark.asyncio
+ async def test_explicit_lookback_clamped_to_max(self):
+ tool = self._setup_tool()
+ mock_response = MarketingDiagnosticResponse(
+ integrations=[],
+ overall_status="no_sources",
+ summary="",
+ conversion_goals=None,
+ recommended_actions=[],
+ )
+ with patch(
+ "products.marketing_analytics.backend.max_tools.get_marketing_diagnostic",
+ new=AsyncMock(return_value=mock_response),
+ ) as mock_svc:
+ await tool._arun_impl(attribution_lookback_days=1000)
+
+ _args, kwargs = mock_svc.call_args
+ assert kwargs["attribution_lookback_days"] <= MAX_LOOKBACK_DAYS
+
+
+class TestMarketingExplainConversionGoalTool(BaseTest):
+ def setUp(self):
+ super().setUp()
+ os.environ["OPENAI_API_KEY"] = "test-api-key"
+
+ def tearDown(self):
+ super().tearDown()
+ os.environ.pop("OPENAI_API_KEY", None)
+
+ def _setup_tool(self):
+ return _make_tool(MarketingExplainConversionGoalTool, self.team, self.user)
+
+ @pytest.mark.django_db
+ @pytest.mark.asyncio
+ async def test_arun_impl_success(self):
+ tool = self._setup_tool()
+ explanation = GoalExplanation(
+ goal_id="goal-1",
+ goal_name="Signup",
+ kind="EventsNode",
+ period=DateRange(date_from="2025-04-01", date_to="2025-05-01"),
+ total_count=100,
+ integrated_count=80,
+ events_without_utm_source=10,
+ events_with_unmatched_utm_source=10,
+ non_integrated_count=20,
+ by_event=[("user signed up", 100)],
+ by_utm_source=[("google", 80)],
+ by_matched_integration=[("GoogleAds", 80)],
+ samples=[],
+ notes=[],
+ )
+ with patch(
+ "products.marketing_analytics.backend.max_tools.explain_conversion_goal",
+ new=AsyncMock(return_value=explanation),
+ ):
+ content, artifact = await tool._arun_impl(goal_id="goal-1")
+
+ assert isinstance(content, str)
+ assert isinstance(artifact, dict)
+ assert "Signup" in content
+
+ @pytest.mark.django_db
+ @pytest.mark.asyncio
+ async def test_arun_impl_value_error_returns_goal_not_found(self):
+ tool = self._setup_tool()
+ with patch(
+ "products.marketing_analytics.backend.max_tools.explain_conversion_goal",
+ new=AsyncMock(side_effect=ValueError("Goal 'missing-id' not found")),
+ ):
+ content, artifact = await tool._arun_impl(goal_id="missing-id")
+
+ assert "Could not explain" in content
+ assert artifact["error"] == "goal_not_found"
+ assert artifact["goal_id"] == "missing-id"
+
+
+class TestMarketingListConversionGoalsTool(BaseTest):
+ def setUp(self):
+ super().setUp()
+ os.environ["OPENAI_API_KEY"] = "test-api-key"
+
+ def tearDown(self):
+ super().tearDown()
+ os.environ.pop("OPENAI_API_KEY", None)
+
+ def _setup_tool(self):
+ return _make_tool(MarketingListConversionGoalsTool, self.team, self.user)
+
+ @pytest.mark.django_db
+ @pytest.mark.asyncio
+ async def test_arun_impl_returns_string_and_dict(self):
+ tool = self._setup_tool()
+ mock_response = ConversionGoalsListResponse(
+ goals=[_make_goal_summary()],
+ attribution_window_days=30,
+ attribution_mode="last_touch",
+ has_misconfigured=False,
+ )
+ with patch(
+ "products.marketing_analytics.backend.max_tools.list_conversion_goals",
+ new=AsyncMock(return_value=mock_response),
+ ):
+ content, artifact = await tool._arun_impl()
+
+ assert isinstance(content, str)
+ assert isinstance(artifact, dict)
+ assert "Purchase" in content
+
+ @pytest.mark.django_db
+ @pytest.mark.asyncio
+ async def test_arun_impl_empty_goals_message(self):
+ tool = self._setup_tool()
+ mock_response = ConversionGoalsListResponse(
+ goals=[],
+ attribution_window_days=30,
+ attribution_mode="last_touch",
+ has_misconfigured=False,
+ )
+ with patch(
+ "products.marketing_analytics.backend.max_tools.list_conversion_goals",
+ new=AsyncMock(return_value=mock_response),
+ ):
+ content, artifact = await tool._arun_impl()
+
+ assert "No conversion goals" in content
+ assert isinstance(artifact, dict)
+
+
+class TestMarketingListDataSourcesTool(BaseTest):
+ def setUp(self):
+ super().setUp()
+ os.environ["OPENAI_API_KEY"] = "test-api-key"
+
+ def tearDown(self):
+ super().tearDown()
+ os.environ.pop("OPENAI_API_KEY", None)
+
+ def _setup_tool(self):
+ return _make_tool(MarketingListDataSourcesTool, self.team, self.user)
+
+ @pytest.mark.django_db
+ @pytest.mark.asyncio
+ async def test_arun_impl_returns_string_and_dict(self):
+ tool = self._setup_tool()
+ mock_response = DataSourceHealthResponse(
+ integrations=[_make_data_source_entry()],
+ has_any_data=True,
+ overall_status="healthy",
+ issues_summary=[],
+ )
+ with patch(
+ "products.marketing_analytics.backend.max_tools.get_data_source_health",
+ new=AsyncMock(return_value=mock_response),
+ ):
+ content, artifact = await tool._arun_impl()
+
+ assert isinstance(content, str)
+ assert isinstance(artifact, dict)
+
+ @pytest.mark.django_db
+ @pytest.mark.asyncio
+ async def test_arun_impl_passes_source_type_filter(self):
+ tool = self._setup_tool()
+ mock_response = DataSourceHealthResponse(
+ integrations=[],
+ has_any_data=False,
+ overall_status="no_sources",
+ issues_summary=[],
+ )
+ with patch(
+ "products.marketing_analytics.backend.max_tools.get_data_source_health",
+ new=AsyncMock(return_value=mock_response),
+ ) as mock_svc:
+ await tool._arun_impl(source_type="GoogleAds")
+
+ mock_svc.assert_called_once()
+ _args, kwargs = mock_svc.call_args
+ assert kwargs["source_type"] == "GoogleAds"
+
+
+class TestMarketingAuditUtmTool(BaseTest):
+ def setUp(self):
+ super().setUp()
+ os.environ["OPENAI_API_KEY"] = "test-api-key"
+
+ def tearDown(self):
+ super().tearDown()
+ os.environ.pop("OPENAI_API_KEY", None)
+
+ def _setup_tool(self):
+ return _make_tool(MarketingAuditUtmTool, self.team, self.user)
+
+ @pytest.mark.django_db
+ @pytest.mark.asyncio
+ async def test_arun_impl_returns_string_and_dict(self):
+ tool = self._setup_tool()
+ mock_response = UtmAuditResponse(
+ total_campaigns=3,
+ campaigns_with_issues=1,
+ campaigns_without_issues=2,
+ total_spend_at_risk=50.0,
+ results=[],
+ all_utm_events=[],
+ )
+ with patch(
+ "products.marketing_analytics.backend.max_tools.run_utm_audit",
+ return_value=mock_response,
+ ):
+ content, artifact = await tool._arun_impl()
+
+ assert isinstance(content, str)
+ assert isinstance(artifact, dict)
+ assert "1 of 3" in content
+
+
+class TestMarketingSuggestConversionGoalsTool(BaseTest):
+ def setUp(self):
+ super().setUp()
+ os.environ["OPENAI_API_KEY"] = "test-api-key"
+
+ def tearDown(self):
+ super().tearDown()
+ os.environ.pop("OPENAI_API_KEY", None)
+
+ def _setup_tool(self):
+ return _make_tool(MarketingSuggestConversionGoalsTool, self.team, self.user)
+
+ @pytest.mark.django_db
+ @pytest.mark.asyncio
+ async def test_arun_impl_returns_string_and_dict(self):
+ tool = self._setup_tool()
+ candidate = CandidateEvent(
+ event_name="checkout_completed",
+ last_30d_count=300,
+ distinct_users_30d=280,
+ pct_with_utm_source=70.0,
+ pct_with_utm_campaign=65.0,
+ top_utm_sources=[("google", 200)],
+ is_already_a_goal=False,
+ suggestion_score=0.92,
+ suggestion_reason="High volume and UTM coverage.",
+ )
+ mock_response = EventSuggestionsResponse(candidates=[candidate], lookback_days=30)
+ with patch(
+ "products.marketing_analytics.backend.max_tools.suggest_conversion_goals",
+ new=AsyncMock(return_value=mock_response),
+ ):
+ content, artifact = await tool._arun_impl(top_n=5, min_count=30)
+
+ assert isinstance(content, str)
+ assert isinstance(artifact, dict)
+ assert "checkout_completed" in content
+
+ @pytest.mark.django_db
+ @pytest.mark.asyncio
+ async def test_arun_impl_passes_top_n_and_min_count(self):
+ tool = self._setup_tool()
+ mock_response = EventSuggestionsResponse(candidates=[], lookback_days=30)
+ with patch(
+ "products.marketing_analytics.backend.max_tools.suggest_conversion_goals",
+ new=AsyncMock(return_value=mock_response),
+ ) as mock_svc:
+ await tool._arun_impl(top_n=5, min_count=20)
+
+ mock_svc.assert_called_once()
+ _args, kwargs = mock_svc.call_args
+ assert kwargs["top_n"] == 5
+ assert kwargs["min_count"] == 20
+
+
+class TestMarketingSuggestUtmMappingsTool(BaseTest):
+ def setUp(self):
+ super().setUp()
+ os.environ["OPENAI_API_KEY"] = "test-api-key"
+
+ def tearDown(self):
+ super().tearDown()
+ os.environ.pop("OPENAI_API_KEY", None)
+
+ def _setup_tool(self):
+ return _make_tool(MarketingSuggestUtmMappingsTool, self.team, self.user)
+
+ @pytest.mark.django_db
+ @pytest.mark.asyncio
+ async def test_arun_impl_returns_string_and_dict(self):
+ tool = self._setup_tool()
+ mock_response = UtmMappingSuggestionsResponse(
+ lookback_days_used=90,
+ total_events_with_utm_in_window=500,
+ total_unmatched_events_in_window=50,
+ )
+ with patch(
+ "products.marketing_analytics.backend.max_tools.suggest_utm_mappings",
+ new=AsyncMock(return_value=mock_response),
+ ):
+ content, artifact = await tool._arun_impl()
+
+ assert isinstance(content, str)
+ assert isinstance(artifact, dict)
+ assert "90" in content
+
+ @pytest.mark.django_db
+ @pytest.mark.asyncio
+ async def test_explicit_lookback_passed_to_service(self):
+ tool = self._setup_tool()
+ mock_response = UtmMappingSuggestionsResponse(
+ lookback_days_used=60,
+ total_events_with_utm_in_window=0,
+ total_unmatched_events_in_window=0,
+ )
+ with patch(
+ "products.marketing_analytics.backend.max_tools.suggest_utm_mappings",
+ new=AsyncMock(return_value=mock_response),
+ ) as mock_svc:
+ await tool._arun_impl(lookback_days=60)
+
+ mock_svc.assert_called_once()
+ _args, kwargs = mock_svc.call_args
+ assert kwargs["lookback_days"] == 60
+
+ @pytest.mark.django_db
+ @pytest.mark.asyncio
+ async def test_explicit_lookback_clamped_to_max(self):
+ tool = self._setup_tool()
+ mock_response = UtmMappingSuggestionsResponse(
+ lookback_days_used=365,
+ total_events_with_utm_in_window=0,
+ total_unmatched_events_in_window=0,
+ )
+ with patch(
+ "products.marketing_analytics.backend.max_tools.suggest_utm_mappings",
+ new=AsyncMock(return_value=mock_response),
+ ) as mock_svc:
+ await tool._arun_impl(lookback_days=2000)
+
+ _args, kwargs = mock_svc.call_args
+ assert kwargs["lookback_days"] <= MAX_LOOKBACK_DAYS
diff --git a/services/mcp/src/lib/oauth-scopes.generated.ts b/services/mcp/src/lib/oauth-scopes.generated.ts
index 327168129aae..f90a7a7d98b5 100644
--- a/services/mcp/src/lib/oauth-scopes.generated.ts
+++ b/services/mcp/src/lib/oauth-scopes.generated.ts
@@ -117,6 +117,8 @@ export const OAUTH_SCOPES_SUPPORTED = [
'llm_skill:write',
'logs:read',
'logs:write',
+ 'marketing_analytics:read',
+ 'marketing_analytics:write',
'notebook:read',
'notebook:write',
'organization:read',
diff --git a/tach.toml b/tach.toml
index db7c5d22167c..cce218e7c1b6 100644
--- a/tach.toml
+++ b/tach.toml
@@ -509,6 +509,7 @@ layer = "modules"
[[modules]]
path = "products.marketing_analytics"
depends_on = [
+ "ee",
"posthog",
"products.access_control",
"products.actions",