: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(marketing): require paid evidence for source suggestions (#108502)
Javier Bahamondes078d7820b275
diff --git a/.github/new-events-schema-targets.txt b/.github/new-events-schema-targets.txtindex e170cc8abbf9..b5d653fafcb6 100644--- a/.github/new-events-schema-targets.txt+++ b/.github/new-events-schema-targets.txt@@ -28,6 +28,7 @@ ee/clickhouseproducts/customer_analytics/backend/hogql_queriesproducts/error_tracking/backend/hogql_queriesproducts/marketing_analytics/backend/hogql_queries+products/marketing_analytics/backend/services/test_attribution_health.pyproducts/mcp_analytics/backend/tests/test_dashboard_series.pyproducts/mcp_analytics/backend/tests/test_harness_breakdown.pyproducts/mcp_analytics/backend/tests/test_missing_capabilities.pydiff --git a/docs/published/handbook/engineering/data-warehouse.md b/docs/published/handbook/engineering/data-warehouse.mdindex 2c8dac1dca81..f36cd3debb11 100644--- a/docs/published/handbook/engineering/data-warehouse.md+++ b/docs/published/handbook/engineering/data-warehouse.md@@ -93,6 +93,38 @@ The category covers new advertising connectors automatically; it does not mean MSelecting a source outside this category, such as BigQuery, records only Data warehouse intent.Supported self-managed providers keep their separate Marketing analytics intent tracking.+## Marketing source suggestions++Marketing analytics suggests connecting an ad platform only when a matching `utm_source` has events with paid attribution signals.+A source match, referral, fuzzy alias, or `utm_campaign` alone does not establish paid traffic.+For example, [ChatGPT adds `utm_source=chatgpt.com` to referral links](https://help.openai.com/en/articles/12627856-publishers-and-developers-faq), and [campaign tags also describe non-ad marketing](https://support.google.com/analytics/answer/10917952).++An explicit paid medium (`cpc`, `cpm`, `cpv`, `cpa`, `ppc`, `retargeting`, or a `paid` prefix) qualifies for any matched platform.+The following platform-specific signals also qualify, in event properties or the query string of the same event's `$current_url`:++| Platform | Additional paid signal |+| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| Google Ads | [`gclid`, `gbraid`, `wbraid`](https://developers.google.com/google-ads/api/docs/conversions/legacy_oci_guide), [`gad_source`, `gad_campaignid`](https://support.google.com/google-ads/answer/16193746) |+| OpenAI Ads | [`oppref`](https://developers.openai.com/ads/conversion-tracking) |+| Microsoft Advertising | [`msclkid`](https://learn.microsoft.com/en-us/advertising/guides/uet-conversion-api-integration?view=bingads-13) |+| LinkedIn Ads | [`li_fat_id`](https://learn.microsoft.com/en-us/linkedin/marketing/conversions/enabling-first-party-cookies?view=li-lms-2026-03) |+| Reddit Ads | [`rdt_cid`](https://ads-api.reddit.com/docs/v3/capi-click-id-persistence) |+| Snapchat Ads | [`ScCid`](https://developers.snap.com/marketing-api/Conversions-API/UsingTheAPI#sending-click-id) or `sccid`, not the `_scid` cookie |+| TikTok Ads | [`ttclid`](https://ads.tiktok.com/resources/help/article/tiktok-click-id?lang=en) |+| Rokt Ads | [`rtid`](https://docs.rokt.com/developers/integration-guides/web/advanced/rokt-id-tag/) |+| Pinterest Ads | [`pp=0`](https://help.pinterest.com/en/business/article/the-pp-query-string-parameter); `pp=1` excludes earned clicks even when paid campaign tags remain |++Meta, Amazon, and Apple rely on an explicit paid medium in this detector.+`fbclid` and `epik` alone do not qualify.+Apple app attribution requires [AdServices attribution records](https://developer.apple.com/documentation/AdServices/AAAttribution/attributionToken%28%29); an App Store campaign link does not establish an Apple Ads interaction.++Each event counts at most once for its matched platform, even if it has both a paid medium and an ad identifier.+Custom source mappings select which platform's signals apply; another platform's identifier cannot make that source paid.+This check retains the UTM source catalogue's time window and top-500 limit, so it does not discover untagged sources or verify billable clicks.+Missing signals mean insufficient evidence to recommend a connection, not proof that traffic is organic.+The medium count describes only matched events in the lookback window; zero can also mean no events matched that integration.+This changes setup recommendations and diagnostic actions, not report attribution or connected-source sync checks.+## Importing your local Postgres instance1. Head to the [new source flow](http://localhost:8010/project/pipeline/new/source) in your local app, hit the link button next to Postgresdiff --git a/products/marketing_analytics/backend/api.py b/products/marketing_analytics/backend/api.pyindex 8b9a3f55c675..74bb0dd0c65d 100644--- a/products/marketing_analytics/backend/api.py+++ b/products/marketing_analytics/backend/api.py@@ -731,14 +731,17 @@ class AttributionHealthEntrySerializer(serializers.Serializer):)events_matched_paid_last_7d = serializers.IntegerField(help_text=(- "Of the matched events, how many look paid: a cost-bearing utm_medium (cpc, cpm, cpv, cpa, ppc, "- "retargeting, or anything starting with 'paid') or a gclid/gad_source click id."+ "Of the matched events, how many show paid evidence for this integration: a cost-bearing utm_medium "+ "(cpc, cpm, cpv, cpa, ppc, retargeting, or anything starting with 'paid') or one of this integration's "+ "own ad click parameters in the event properties or the current URL (for example gclid for Google Ads "+ "or msclkid for Microsoft Ads). Pinterest clicks with pp=1 never count. Campaign names, fbclid, and "+ "epik alone do not count."))events_matched_tagged_medium_last_7d = serializers.IntegerField(help_text=(- "Of the matched events, how many carry any utm_medium. Zero paid with a non-zero count here means "- "the traffic is tagged and organic; both zero means the team doesn't tag medium, which says nothing."+ "Matched events carrying any utm_medium in the lookback window. Zero means no matched event "+ "carried a medium, including when no events matched. Missing paid signals do not prove organic traffic."))diff --git a/products/marketing_analytics/backend/services/attribution_health.py b/products/marketing_analytics/backend/services/attribution_health.pyindex 5b638de31de7..6e8058f21a34 100644--- a/products/marketing_analytics/backend/services/attribution_health.py+++ b/products/marketing_analytics/backend/services/attribution_health.py@@ -15,6 +15,7 @@ from django.utils import timezoneimport structlogfrom posthog.hogql import ast+from posthog.hogql.parser import parse_expr, parse_selectfrom posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.query_tagging import Feature, Product, tags_context@@ -75,8 +76,7 @@ class AttributionHealthEntry:matched_pct: floatsample_unmatched_utm_sources: list[UnmatchedUtmSample] = field(default_factory=list)# Of the matched events, how many look paid, and how many carry any utm_medium.- # `paid == 0 and tagged > 0` is positive evidence the traffic is organic; both- # zero only means the team doesn't tag medium, which says nothing either way.+ # Missing paid signals mean unknown intent, not necessarily organic traffic.events_matched_paid_last_7d: int = 0events_matched_tagged_medium_last_7d: int = 0@@ -175,9 +175,7 @@ async def get_attribution_health(acc = per_integration.get(matched_key)if acc is not None:acc.matched_count += count- acc.paid_count += row.paid_event_count- if matched_key == "google_ads":- acc.paid_count += row.google_click_id_count+ acc.paid_count += row.platform_paid_event_counts.get(matched_key, row.paid_event_count)acc.tagged_medium_count += row.tagged_medium_countcandidates = [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@@ -221,10 +219,8 @@ class _UtmRow:# A cost-bearing utm_medium, per PostHog's own channel-type rule# (posthog.com/docs/data/channel-type). Platform-agnostic: any source can be paid.paid_event_count: int = 0- # Counted apart from the medium, because `gclid` and `gad_source` name Google Ads- # specifically. They ride along on whatever URL carries them, so a link shared with a- # stale gclid would otherwise mark LinkedIn traffic as paid LinkedIn.- google_click_id_count: int = 0+ # Each platform count is the union of paid medium and its own ad signals.+ platform_paid_event_counts: dict[NativeIntegration, int] = field(default_factory=dict)# Events carrying any utm_medium at all. Separates "tagged, and organic" from# "not tagged", which are different answers to "is this paid?".tagged_medium_count: int = 0@@ -272,6 +268,57 @@ def _build_team_alias_map(team: Team) -> dict[str, NativeIntegration]:return build_combined_alias_map(custom)+# These identify ad interactions; fbclid and epik can also accompany unpaid visits.+_PLATFORM_AD_PARAMETERS: dict[NativeIntegration, tuple[str, ...]] = {+ "google_ads": ("gclid", "gbraid", "wbraid", "gad_source", "gad_campaignid"),+ "openai_ads": ("oppref",),+ "bing_ads": ("msclkid",),+ "linkedin_ads": ("li_fat_id",),+ "reddit_ads": ("rdt_cid",),+ "snapchat_ads": ("ScCid", "sccid"),+ "tiktok_ads": ("ttclid",),+ "rokt_ads": ("rtid",),+}+++def _event_parameter_matches(parameter: str, value: str | None = None) -> ast.Expr:+ # SDKs do not capture every platform's parameter as an event property.+ property_value = parse_expr(+ "trim(ifNull(toString({property}), ''))",+ placeholders={"property": ast.Field(chain=["properties", parameter])},+ )+ url_value = parse_expr(+ "trim(decodeURLComponent(extractURLParameter(ifNull(properties.$current_url, ''), {parameter})))",+ placeholders={"parameter": ast.Constant(value=parameter)},+ )+ return ast.Or(+ exprs=[+ parse_expr(+ "{candidate} != ''" if value is None else "{candidate} = {value}",+ placeholders={"candidate": candidate, "value": ast.Constant(value=value)},+ )+ for candidate in (property_value, url_value)+ ]+ )+++def _platform_paid_expressions(paid_medium: ast.Expr) -> dict[NativeIntegration, ast.Expr]:+ expressions: dict[NativeIntegration, ast.Expr] = {+ key: ast.Or(exprs=[paid_medium, *[_event_parameter_matches(parameter) for parameter in parameters]])+ for key, parameters in _PLATFORM_AD_PARAMETERS.items()+ }+ # Saved ads retain campaign tags, but Pinterest marks their unpaid clicks pp=1.+ expressions["pinterest_ads"] = parse_expr(+ "({paid_medium} OR {paid_click}) AND NOT {earned_click}",+ placeholders={+ "paid_medium": paid_medium,+ "paid_click": _event_parameter_matches("pp", "0"),+ "earned_click": _event_parameter_matches("pp", "1"),+ },+ )+ return expressions++@database_sync_to_asyncdef _fetch_utm_groups(team: Team, *, lookback_days: int) -> list[_UtmRow]:"""HogQL aggregation of utm_source counts and latest timestamp within the window.@@ -285,19 +332,20 @@ def _fetch_utm_groups(team: Team, *, lookback_days: int) -> list[_UtmRow]:"""now = timezone.now()since = now - timedelta(days=lookback_days)- hogql = """+ paid_medium = parse_expr(+ """+ lower(trim(properties.utm_medium)) IN ('cpc', 'cpm', 'cpv', 'cpa', 'ppc', 'retargeting')+ OR startsWith(lower(trim(properties.utm_medium)), 'paid')+ """+ )+ platform_paid = _platform_paid_expressions(paid_medium)+ query = parse_select(+ """SELECTlower(trim(properties.utm_source)) AS raw_utm_source,count() AS event_count,max(timestamp) AS last_seen_at,- countIf(- lower(trim(properties.utm_medium)) IN ('cpc', 'cpm', 'cpv', 'cpa', 'ppc', 'retargeting')- OR startsWith(lower(trim(properties.utm_medium)), 'paid')- ) AS paid_event_count,- countIf(- (properties.gclid IS NOT NULL AND properties.gclid != '')- OR (properties.gad_source IS NOT NULL AND properties.gad_source != '')- ) AS google_click_id_count,+ countIf({paid_medium}) AS paid_event_count,countIf(properties.utm_medium IS NOT NULL AND trim(properties.utm_medium) != '') AS tagged_medium_countFROM eventsWHERE@@ -308,27 +356,21 @@ def _fetch_utm_groups(team: Team, *, lookback_days: int) -> list[_UtmRow]:GROUP BY raw_utm_sourceORDER BY event_count DESCLIMIT {limit}- """+ """,+ placeholders={+ "paid_medium": paid_medium,+ "since": ast.Constant(value=since),+ "until": ast.Constant(value=now),+ "limit": ast.Constant(value=HOGQL_GROUP_LIMIT),+ },+ )+ assert isinstance(query, ast.SelectQuery)+ query.select.extend(ast.Call(name="countIf", args=[expression]) for expression in platform_paid.values())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),- "until": ast.Constant(value=now),- "limit": ast.Constant(value=HOGQL_GROUP_LIMIT),- },- )+ result = execute_hogql_query(query, team)rows: list[_UtmRow] = []for row in result.results or []:- raw, count, last_at, paid_count, click_id_count, tagged_count = (- row[0],- row[1],- row[2],- row[3],- row[4],- row[5],- )+ raw, count, last_at, paid_count, tagged_count = row[:5]if not raw:continuerows.append(@@ -337,7 +379,7 @@ def _fetch_utm_groups(team: Team, *, lookback_days: int) -> list[_UtmRow]:event_count=int(count or 0),last_seen_at=last_at if isinstance(last_at, datetime) else None,paid_event_count=int(paid_count or 0),- google_click_id_count=int(click_id_count or 0),+ platform_paid_event_counts={key: int(value or 0) for key, value in zip(platform_paid, row[5:])},tagged_medium_count=int(tagged_count or 0),))diff --git a/products/marketing_analytics/backend/services/marketing_diagnostic.py b/products/marketing_analytics/backend/services/marketing_diagnostic.pyindex 226cf5ede0f5..d847a12af44a 100644--- a/products/marketing_analytics/backend/services/marketing_diagnostic.py+++ b/products/marketing_analytics/backend/services/marketing_diagnostic.py@@ -58,7 +58,7 @@ IntegrationStatus = Literal["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)+ "events_only", # no platform sync but UTM-matched events with paid attribution arrive"schema_misconfigured", # connected and syncing but required schema columns unmapped"not_connected", # no source for this integration]@@ -237,25 +237,26 @@ def _diagnose_one(has_matched_events = attr is not None and attr.events_matched_last_7d > 0has_likely_yours = attr is not None and attr.events_unmatched_likely_yours_last_7d > 0+ has_paid_events = attr is not None and attr.events_matched_paid_last_7d > 0- if not_connected and not has_matched_events and not has_likely_yours:+ if not_connected and not has_paid_events: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.",+ diagnosis=f"{display} is not connected and no matching events with paid attribution were seen.",data_source=ds,attribution=attr,recommended_actions=[],)- if not_connected and (has_matched_events or has_likely_yours):+ if not_connected:actions.append(RecommendedAction(title=f"Connect {display}",detail=(- f"Events with utm_source matching {display} are arriving "+ f"Events with utm_source matching {display} include traffic with paid attribution "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."@@ -270,7 +271,7 @@ def _diagnose_one(display_name=display,overall_status="events_only",diagnosis=(- f"{display} is not connected, but UTM-tagged events for it are arriving. "+ f"{display} is not connected, but matching events with paid attribution are arriving. ""Connect the platform to attribute spend to those events."),data_source=ds,diff --git a/products/marketing_analytics/backend/services/setup_plan.py b/products/marketing_analytics/backend/services/setup_plan.pyindex 92af92099f5a..e20a07fa46f3 100644--- a/products/marketing_analytics/backend/services/setup_plan.py+++ b/products/marketing_analytics/backend/services/setup_plan.py@@ -282,27 +282,14 @@ def _integration_suggestion(integration: IntegrationDiagnostic) -> Suggestion |source_type = integration.source_typeds = integration.data_sourceattribution = integration.attribution- # Both counters: `events_only` is set when either one is non-zero, so reading just the- # likely-yours side reports "0 events" as the reason to connect a platform whose- # utm_source matched exactly. They never overlap — a utm_source either matches an alias- # or is only fuzzy-suggested — so the sum is every event carrying this platform's source.+ # Exact and fuzzy source matches do not overlap, so both contribute to the source volume.volume = (attribution.events_matched_last_7d + attribution.events_unmatched_likely_yours_last_7d if attribution else 0)if status == "events_only":- # `utm_source` alone doesn't mean paid — `google` also covers gmail links and- # `linkedin` organic posts, so this fired "connect an ad account you don't- # have" at error severity. Suppressed only on positive evidence: most of the- # traffic carries a medium and none of it is paid. An untagged event is absence- # of evidence, not evidence of organic, so a tagged minority doesn't get to- # speak for it — a team that tags its posts but not its ad links still gets asked.- attr = integration.attribution- if (- attr is not None- and attr.events_matched_paid_last_7d == 0- and attr.events_matched_tagged_medium_last_7d * 2 > attr.events_matched_last_7d- ):+ # Organic and referral links can carry both utm_source and utm_campaign.+ if attribution is None or attribution.events_matched_paid_last_7d == 0:return None# Traffic arrives but no spend data, so cost, ROAS and CAC are all unavailable.@@ -313,8 +300,8 @@ def _integration_suggestion(integration: IntegrationDiagnostic) -> Suggestion |confidence=0.95,title=f"Connect {display}",evidence=(- f"{volume:,} events in the last 7 days carry a {display} utm_source, but the platform "- "isn't connected — none of that traffic has cost attached."+ f"{volume:,} events in the last 7 days carry a {display} utm_source, "+ "including traffic with paid attribution. Connect the platform to add spend data."),unlocks=[Capability.COST, Capability.ROAS, Capability.CAC],apply=OpenSourceWizard(kind=source_type),diff --git a/products/marketing_analytics/backend/services/test_attribution_health.py b/products/marketing_analytics/backend/services/test_attribution_health.pyindex 2c22e7a2bd6c..da2917205ba9 100644--- a/products/marketing_analytics/backend/services/test_attribution_health.py+++ b/products/marketing_analytics/backend/services/test_attribution_health.py@@ -2,13 +2,16 @@ from datetime import UTC, datetime, timedeltaimport pytestimport time_machine-from posthog.test.base import APIBaseTest, BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events+from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_eventsfrom unittest.mock import AsyncMock, patch+from django.test import SimpleTestCasefrom django.utils import timezonefrom parameterized import parameterized+from posthog.models.team.team import Team+from products.marketing_analytics.backend.services.attribution_health import (HOGQL_GROUP_LIMIT,_suggest_integration_by_alias_token,@@ -42,9 +45,10 @@ class TestSuggestIntegrationByAliasToken:assert _suggest_integration_by_alias_token(f"{alias}_paid", _ALIAS_MAP, allowed_without) is None-class TestGetAttributionHealth(APIBaseTest):+class TestGetAttributionHealth(SimpleTestCase):def setUp(self):super().setUp()+ self.team = Team(id=1)from products.marketing_analytics.backend.services.native_integrations import canonical_source_aliasesfetch_patcher = patch(@@ -93,6 +97,23 @@ class TestGetAttributionHealth(APIBaseTest):assert google.events_matched_last_7d == 80assert meta.matched_pct == round(120 / 200 * 100, 2)+ @pytest.mark.asyncio+ async def test_custom_mapping_uses_only_the_mapped_platform_paid_signals(self) -> None:+ self.mock_fetch.return_value = [+ _UtmRow(+ raw_utm_source="custom-source",+ event_count=3,+ last_seen_at=None,+ paid_event_count=1,+ platform_paid_event_counts={"openai_ads": 2, "google_ads": 3},+ ),+ ]+ response = await get_attribution_health(self.team, custom_source_mappings={"OpenAIAds": ["custom-source"]})+ openai = next(e for e in response.integrations if e.integration_key == "openai_ads")+ google = next(e for e in response.integrations if e.integration_key == "google_ads")+ assert openai.events_matched_paid_last_7d == 2+ assert google.events_matched_paid_last_7d == 0+@pytest.mark.asyncioasync def test_token_variant_classified_as_likely_yours(self):self.mock_fetch.return_value = [@@ -366,60 +387,110 @@ class TestAttributionHealthSourceTypeFilterClickhouse(ClickhouseTestMixin, BaseTassert response.total_events_matched_to_any_integration == 2+@time_machine.travel("2026-09-15T12:00:00Z", tick=False)class TestAttributionHealthPaidSignalClickhouse(ClickhouseTestMixin, BaseTest):- """Paid is decided the way PostHog decides it everywhere else — the channel-type- rule at posthog.com/docs/data/channel-type — so a `linkedin` utm_source from an- organic post isn't counted as ad traffic."""-CLASS_DATA_LEVEL_SETUP = False- def setUp(self) -> None:- super().setUp()- _pageview(self.team, "u1", utm_source="linkedin", utm_medium="cpc")- _pageview(self.team, "u2", utm_source="linkedin", utm_medium="paid-social")- _pageview(self.team, "u3", utm_source="linkedin", utm_medium="organic-social")- _pageview(self.team, "u4", utm_source="linkedin")- _pageview(self.team, "u5", utm_source="google", gclid="abc123")- # A link copied from an address bar that still held a Google click id, then- # shared organically. The gclid names Google Ads, not LinkedIn.- _pageview(self.team, "u6", utm_source="linkedin", utm_medium="social", gclid="stale123")- flush_persons_and_events()-- def tearDown(self) -> None:+ @parameterized.expand(+ [+ ("google", "google_ads", "gclid"),+ ("google", "google_ads", "gbraid"),+ ("google", "google_ads", "wbraid"),+ ("google", "google_ads", "gad_source"),+ ("google", "google_ads", "gad_campaignid"),+ ("chatgpt", "openai_ads", "oppref"),+ ("bing", "bing_ads", "msclkid"),+ ("linkedin", "linkedin_ads", "li_fat_id"),+ ("reddit", "reddit_ads", "rdt_cid"),+ ("snapchat", "snapchat_ads", "ScCid"),+ ("snapchat", "snapchat_ads", "sccid"),+ ("tiktok", "tiktok_ads", "ttclid"),+ ("rokt", "rokt_ads", "rtid"),+ ("pinterest", "pinterest_ads", "pp"),+ ]+ )+ @pytest.mark.asyncio+ async def test_platform_ad_signals_count_each_event_once(self, source: str, key: str, parameter: str) -> None:+ value = "0" if parameter == "pp" else "example-click"+ event_properties = [+ {parameter: value},+ {"$current_url": f"https://example.com/?{parameter}={value}"},+ {parameter: value, "utm_medium": "cpc"},+ {"utm_medium": " paid-social "},+ {"utm_campaign": "product-guide", "utm_medium": "referral"},+ {parameter: ""},+ {parameter: " ", "$current_url": f"https://example.com/?{parameter}=%20"},+ {"msclkid" if key != "bing_ads" else "gclid": "other-platform-click"},+ ]+ for index, properties in enumerate(event_properties):+ _create_event(+ team=self.team,+ distinct_id=f"visitor-{index}",+ event="$pageview",+ timestamp=timezone.now() - timedelta(hours=1),+ properties={"utm_source": source, **properties},+ )flush_persons_and_events()- super().tearDown()- async def _entry(self, key: str):- response = await get_attribution_health(self.team, lookback_days=30)- return next(e for e in response.integrations if e.integration_key == key)-- @pytest.mark.asyncio- async def test_counts_cost_bearing_and_paid_prefixed_mediums(self) -> None:- linkedin = await self._entry("linkedin_ads")+ response = await get_attribution_health(self.team, custom_source_mappings={})- assert linkedin.events_matched_last_7d == 5- # `cpc` by name, `paid-social` by prefix. `organic-social`, the untagged one and- # the stale-gclid one are not paid; four of the five carry a medium.- assert linkedin.events_matched_paid_last_7d == 2- assert linkedin.events_matched_tagged_medium_last_7d == 4+ entry = next(e for e in response.integrations if e.integration_key == key)+ assert entry.events_matched_last_7d == len(event_properties)+ assert entry.events_matched_paid_last_7d == 4+ assert entry.events_matched_tagged_medium_last_7d == 3+ @parameterized.expand(+ [+ ("openai_referral", "chatgpt", "openai_ads", {"utm_campaign": "product-guide"}),+ ("chatgpt_domain_referral", "chatgpt.com", "openai_ads", {"utm_campaign": "product-guide"}, 0, 0),+ ("google_campaign", "google", "google_ads", {"utm_campaign": "spring-guide"}),+ ("meta_click", "facebook", "meta_ads", {"fbclid": "example-click"}),+ ("meta_url", "facebook", "meta_ads", {"$current_url": "https://example.com/?fbclid=example-click"}),+ ("pinterest_click", "pinterest", "pinterest_ads", {"epik": "example-click"}),+ (+ "pinterest_earned",+ "pinterest",+ "pinterest_ads",+ {"pp": "1", "utm_medium": "cpc", "epik": "example-click"},+ ),+ (+ "pinterest_earned_url",+ "pinterest",+ "pinterest_ads",+ {"utm_medium": "paid-social", "$current_url": "https://example.com/?pp=1"},+ ),+ ("snap_cookie", "snapchat", "snapchat_ads", {"_scid": "example-cookie"}),+ ("apple_campaign", "apple", "apple_ads", {"utm_campaign": "product-guide"}),+ ("amazon_campaign", "amazon", "amazon_ads", {"utm_campaign": "product-guide"}),+ ("meta_paid", "facebook", "meta_ads", {"utm_medium": "cpc"}, 1),+ ("apple_paid", "apple", "apple_ads", {"utm_medium": "cpc"}, 1),+ ("amazon_paid", "amazon", "amazon_ads", {"utm_medium": "cpc"}, 1),+ ]+ )@pytest.mark.asyncio- async def test_a_google_click_id_does_not_make_another_platform_paid(self) -> None:- # gclid and gad_source name Google Ads specifically, and ride along on whatever- # URL carries them. Crediting them to whatever utm_source they land on would put- # `connect LinkedIn Ads` back in front of a team that only posts there.- linkedin = await self._entry("linkedin_ads")-- assert linkedin.events_matched_paid_last_7d == 2+ async def test_campaigns_and_tracking_parameters_require_paid_evidence(+ self,+ _name: str,+ source: str,+ key: str,+ properties: dict[str, str],+ expected_paid: int = 0,+ expected_matched: int = 1,+ ) -> None:+ _create_event(+ team=self.team,+ distinct_id="visitor",+ event="$pageview",+ timestamp=timezone.now() - timedelta(hours=1),+ properties={"utm_source": source, **properties},+ )+ flush_persons_and_events()- @pytest.mark.asyncio- async def test_a_click_id_is_paid_even_with_no_medium(self) -> None:- # Ad platforms attach gclid; nothing else does. Requiring utm_medium here would- # miss every team that relies on auto-tagging.- google = await self._entry("google_ads")+ response = await get_attribution_health(self.team, custom_source_mappings={})- assert google.events_matched_paid_last_7d == 1- assert google.events_matched_tagged_medium_last_7d == 0+ entry = next(e for e in response.integrations if e.integration_key == key)+ assert entry.events_matched_last_7d == expected_matched+ assert entry.events_matched_paid_last_7d == expected_paid@time_machine.travel("2025-06-15", tick=False)diff --git a/products/marketing_analytics/backend/services/test_marketing_diagnostic.py b/products/marketing_analytics/backend/services/test_marketing_diagnostic.pyindex cd6a6ee44cae..51a88edf13a2 100644--- a/products/marketing_analytics/backend/services/test_marketing_diagnostic.py+++ b/products/marketing_analytics/backend/services/test_marketing_diagnostic.py@@ -1,11 +1,14 @@from typing import Any, castimport pytest-from posthog.test.base import APIBaseTestfrom unittest.mock import AsyncMock, patch+from django.test import SimpleTestCase+from parameterized import parameterized+from posthog.models.team.team import Team+from products.marketing_analytics.backend.services.attribution_health import (AttributionHealthEntry,AttributionHealthResponse,@@ -68,7 +71,13 @@ _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),+ (+ "events_only_when_paid_no_source",+ None,+ {"events_matched_last_7d": 200, "events_matched_paid_last_7d": 1},+ "events_only",+ None,+ ),("sync_broken_on_error",{"last_sync_status": "error", "last_error": "auth", "diagnosis": "Google Ads last sync failed."},@@ -140,9 +149,10 @@ class TestComputeOverallStatus:assert _compute_overall_status(diags) == expected-class TestGetMarketingDiagnostic(APIBaseTest):+class TestGetMarketingDiagnostic(SimpleTestCase):def setUp(self):super().setUp()+ self.team = Team(id=1)ds_patcher = patch("products.marketing_analytics.backend.services.marketing_diagnostic.get_data_source_health",new_callable=AsyncMock,@@ -183,16 +193,40 @@ class TestGetMarketingDiagnostic(APIBaseTest):# Encourages configuring goals when none exist.assert any(a.target_tool == "marketing_suggest_conversion_goals" for a in response.recommended_actions)+ @parameterized.expand(+ [+ ("source_only", 100, 0, 0, 0, "not_connected"),+ ("organic_medium", 100, 0, 100, 0, "not_connected"),+ ("mostly_untagged", 100, 0, 10, 0, "not_connected"),+ ("fuzzy_source_only", 0, 100, 0, 0, "not_connected"),+ ("paid_medium", 100, 0, 100, 100, "events_only"),+ ("mixed_traffic", 100, 0, 100, 1, "events_only"),+ ("click_id_without_medium", 100, 0, 0, 1, "events_only"),+ ]+ )@pytest.mark.asyncio- async def test_events_only_corner_case_surfaced(self):+ async def test_connect_recommendation_requires_paid_evidence(+ self, _name: str, matched: int, unmatched: int, tagged: int, paid: int, expected_status: str+ ) -> None:self.mock_attr.return_value = AttributionHealthResponse(lookback_days=7,- integrations=[_attr_entry(events_matched_last_7d=100)],+ integrations=[+ _attr_entry(+ events_matched_last_7d=matched,+ events_unmatched_likely_yours_last_7d=unmatched,+ events_matched_tagged_medium_last_7d=tagged,+ events_matched_paid_last_7d=paid,+ )+ ],)- response = await get_marketing_diagnostic(self.team)+ response = await get_marketing_diagnostic(self.team, include_conversion_goals=False)+google = next(i for i in response.integrations if i.integration_key == "google_ads")- assert google.overall_status == "events_only"+ assert google.overall_status == expected_status+ assert bool(google.recommended_actions) is (paid > 0)+ assert bool(response.recommended_actions) is (paid > 0)+ assert response.overall_status == ("degraded" if paid else "no_sources")@pytest.mark.asyncioasync def test_sync_broken_propagates_to_overall(self):diff --git a/products/marketing_analytics/backend/services/test_setup_plan.py b/products/marketing_analytics/backend/services/test_setup_plan.pyindex 44214356e744..5593714fd6f1 100644--- a/products/marketing_analytics/backend/services/test_setup_plan.py+++ b/products/marketing_analytics/backend/services/test_setup_plan.py@@ -1,10 +1,13 @@import pytest-from posthog.test.base import APIBaseTestfrom unittest.mock import AsyncMock, patch+from django.test import SimpleTestCase+from parameterized import parameterizedfrom pydantic import ValidationError+from posthog.models.team.team import Team+from products.marketing_analytics.backend.services.attribution_health import AttributionHealthResponsefrom products.marketing_analytics.backend.services.conversion_goals_inspector import (ConversionGoalsListResponse,@@ -128,12 +131,13 @@ def _attribution(total=1000, matched=900) -> AttributionHealthResponse:)-class SetupPlanTestCase(APIBaseTest):+class SetupPlanTestCase(SimpleTestCase):"""Every leaf the plan gathers is mocked; these tests are about how the plancomposes, ranks and explains, not about the leaves' own logic."""def setUp(self):super().setUp()+ self.team = Team(id=1)self.diagnostic = MarketingDiagnosticResponse(integrations=[_integration()],overall_status="healthy",@@ -284,7 +288,7 @@ class TestInvariants(SetupPlanTestCase):self.diagnostic = MarketingDiagnosticResponse(integrations=[_integration("google_ads", "GoogleAds", status="sync_broken"),- _integration("meta_ads", "MetaAds", status="events_only", unmatched=900),+ _integration("meta_ads", "MetaAds", status="events_only", matched=900, paid=900),],overall_status="broken",conversion_goals=ConversionGoalsListResponse(goals=[_goal()]),@@ -298,7 +302,7 @@ class TestInvariants(SetupPlanTestCase):@pytest.mark.asyncioasync def test_suggestion_ids_are_deterministic_not_positional(self):self.diagnostic = MarketingDiagnosticResponse(- integrations=[_integration("meta_ads", "MetaAds", status="events_only", unmatched=900)],+ integrations=[_integration("meta_ads", "MetaAds", status="events_only", matched=900, paid=900)],overall_status="degraded",conversion_goals=ConversionGoalsListResponse(goals=[_goal()]),)@@ -315,7 +319,7 @@ class TestRanking(SetupPlanTestCase):# Connecting the platform unblocks the goal-flag work, so it must come first# even though the goal suggestion carries far more event volume.self.diagnostic = MarketingDiagnosticResponse(- integrations=[_integration("meta_ads", "MetaAds", status="events_only", unmatched=10)],+ integrations=[_integration("meta_ads", "MetaAds", status="events_only", matched=10, paid=10)],overall_status="degraded",conversion_goals=ConversionGoalsListResponse(goals=[_goal(count=5_000_000)]),)@@ -567,58 +571,42 @@ class TestConversionGoals(SetupPlanTestCase):class TestConnectSourceNeedsPaidEvidence(SetupPlanTestCase):- """`utm_source` maps to an ad platform on the source alone, so `google` also catches- gmail links and `linkedin` catches organic posts. Suggesting someone connect an ad- account they don't run is worse than saying nothing."""-- async def _plan_for(self, *, matched=900, **kwargs):- # `matched`, not `unmatched`: tagged_medium is only accumulated for rows that- # resolved to an integration, so tagged traffic with zero matched can't happen.+ @parameterized.expand(+ [+ ("organic_medium", 900, 0, 900, 0, False),+ ("source_without_medium", 900, 0, 0, 0, False),+ ("organic_minority_without_paid_evidence", 900, 0, 100, 0, False),+ ("fuzzy_source_without_paid_evidence", 0, 900, 0, 0, False),+ ("missing_attribution", 0, 0, 0, 0, False),+ ("paid_medium", 900, 0, 900, 900, True),+ ("mixed_paid_and_organic", 900, 0, 900, 1, True),+ ("google_click_id_without_medium", 900, 0, 0, 1, True),+ ]+ )+ @pytest.mark.asyncio+ async def test_connect_suggestion_requires_paid_evidence(+ self, _name: str, matched: int, unmatched: int, tagged_medium: int, paid: int, expected: bool+ ) -> None:self.diagnostic = MarketingDiagnosticResponse(- integrations=[_integration("linkedin_ads", "LinkedinAds", status="events_only", matched=matched, **kwargs)],- overall_status="broken",+ integrations=[+ _integration(+ "google_ads",+ "GoogleAds",+ status="events_only",+ matched=matched,+ unmatched=unmatched,+ tagged_medium=tagged_medium,+ paid=paid,+ )+ ],+ overall_status="degraded",conversion_goals=ConversionGoalsListResponse(goals=[_goal()]),)- return await get_setup_plan(self.team)-- def _connects(self, plan) -> list:- return [s for s in plan.suggestions if s.kind == SuggestionKind.CONNECT_SOURCE]- @pytest.mark.asyncio- async def test_organic_traffic_alone_does_not_ask_you_to_connect_an_ad_account(self):- plan = await self._plan_for(tagged_medium=900, paid=0)-- assert self._connects(plan) == []-- @pytest.mark.asyncio- async def test_paid_traffic_still_asks_you_to_connect(self):- plan = await self._plan_for(tagged_medium=900, paid=900)-- assert len(self._connects(plan)) == 1-- @pytest.mark.asyncio- async def test_one_paid_event_among_organic_is_enough_to_ask(self):- # Spend exists; the mix says the team runs both, not that it runs neither.- plan = await self._plan_for(tagged_medium=900, paid=1)-- assert len(self._connects(plan)) == 1-- @pytest.mark.asyncio- async def test_untagged_traffic_still_asks_because_absence_is_not_evidence(self):- # A team that never sets utm_medium tells us nothing either way, and staying- # silent there would hide the case this suggestion exists for.- plan = await self._plan_for(tagged_medium=0, paid=0)-- assert len(self._connects(plan)) == 1-- @pytest.mark.asyncio- async def test_a_tagged_minority_does_not_speak_for_the_untagged_rest(self):- # Tagged organic posts plus a larger body of untagged traffic. The untagged half- # is unclassified, not organic, and it's exactly where unlinked ad spend hides —- # so a team that tags its posts but not its ad links still gets asked.- plan = await self._plan_for(matched=900, tagged_medium=100, paid=0)+ plan = await get_setup_plan(self.team)- assert len(self._connects(plan)) == 1+ connects = [s for s in plan.suggestions if s.kind == SuggestionKind.CONNECT_SOURCE]+ assert bool(connects) is expectedclass TestIntegrationSuggestions(SetupPlanTestCase):@@ -657,7 +645,6 @@ class TestIntegrationSuggestions(SetupPlanTestCase):@parameterized.expand([("exact_utm_source_match_only", 0, 700, 700),- ("fuzzy_match_only", 500, 0, 500),("both_kinds_of_match", 500, 700, 1200),])@@ -665,12 +652,10 @@ class TestIntegrationSuggestions(SetupPlanTestCase):async def test_connect_suggestion_counts_every_event_carrying_the_utm_source(self, _name, unmatched, matched, expected):- # `events_only` is set when either counter is non-zero, so a platform whose utm_source- # matched exactly used to advertise "0 events" as the reason to connect it.self.diagnostic = MarketingDiagnosticResponse(integrations=[_integration(- "pinterest_ads", "PinterestAds", status="events_only", unmatched=unmatched, matched=matched+ "pinterest_ads", "PinterestAds", status="events_only", unmatched=unmatched, matched=matched, paid=1)],overall_status="degraded",diff --git a/products/marketing_analytics/frontend/generated/api.schemas.ts b/products/marketing_analytics/frontend/generated/api.schemas.tsindex fda9a9a7ea45..a4731def1e73 100644--- a/products/marketing_analytics/frontend/generated/api.schemas.ts+++ b/products/marketing_analytics/frontend/generated/api.schemas.ts@@ -1429,9 +1429,9 @@ export interface AttributionHealthEntryApi {matched_pct: number/** Sample of likely-yours unmatched utm_source values */sample_unmatched_utm_sources: UnmatchedUtmSampleApi[]- /** Of the matched events, how many look paid: a cost-bearing utm_medium (cpc, cpm, cpv, cpa, ppc, retargeting, or anything starting with 'paid') or a gclid/gad_source click id. */+ /** Of the matched events, how many show paid evidence for this integration: a cost-bearing utm_medium (cpc, cpm, cpv, cpa, ppc, retargeting, or anything starting with 'paid') or one of this integration's own ad click parameters in the event properties or the current URL (for example gclid for Google Ads or msclkid for Microsoft Ads). Pinterest clicks with pp=1 never count. Campaign names, fbclid, and epik alone do not count. */events_matched_paid_last_7d: number- /** Of the matched events, how many carry any utm_medium. Zero paid with a non-zero count here means the traffic is tagged and organic; both zero means the team doesn't tag medium, which says nothing. */+ /** Matched events carrying any utm_medium in the lookback window. Zero means no matched event carried a medium, including when no events matched. Missing paid signals do not prove organic traffic. */events_matched_tagged_medium_last_7d: number}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 3411617aed48..5e53c913907f 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -11924,9 +11924,9 @@ export namespace Schemas {matched_pct: number;/** Sample of likely-yours unmatched utm_source values */sample_unmatched_utm_sources: UnmatchedUtmSample[];- /** Of the matched events, how many look paid: a cost-bearing utm_medium (cpc, cpm, cpv, cpa, ppc, retargeting, or anything starting with 'paid') or a gclid/gad_source click id. */+ /** Of the matched events, how many show paid evidence for this integration: a cost-bearing utm_medium (cpc, cpm, cpv, cpa, ppc, retargeting, or anything starting with 'paid') or one of this integration's own ad click parameters in the event properties or the current URL (for example gclid for Google Ads or msclkid for Microsoft Ads). Pinterest clicks with pp=1 never count. Campaign names, fbclid, and epik alone do not count. */events_matched_paid_last_7d: number;- /** Of the matched events, how many carry any utm_medium. Zero paid with a non-zero count here means the traffic is tagged and organic; both zero means the team doesn't tag medium, which says nothing. */+ /** Matched events carrying any utm_medium in the lookback window. Zero means no matched event carried a medium, including when no events matched. Missing paid signals do not prove organic traffic. */events_matched_tagged_medium_last_7d: number;}